[Thực hành] Đếm số lượt view trang
NỘI DUNG BÀI VIẾT
Mục tiêu
Luyện tập triển khai cơ chế session trong Spring MVC.
Mô tả
Trong phần này, chúng ta sẽ phát triển một tính năng cho phép ghi nhận số lần người dùng truy cập trang web trong một phiên làm việc.
Ứng dụng sẽ ghi nhận và hiển thị số lần truy cập. Khi người dùng truy cập vào một trang trong ứng dụng thì số lần truy cập sẽ tăng lên.
Để hoàn thành bài thực hành, học viên cần:
- Đưa mã nguồn lên GitHub
- Dán link của repository lên phần nộp bài trên CodeGymX
Hướng dẫn
Bước 1: Tạo dự án Spring MVC.
Để tạo mới dự án, các bạn chọn File -> New -> Project.
Sau đó chọn Gradle -> Tích chọn Java, Web -> Chọn Next
Bạn nhập thông tin vào GroupId, và ArtifactId. Sau đó nhấn Next:
Màn hình sau đó bạn tiếp tục nhấn Next:
Nhập vào Project name, Project location. Sau đó nhấn Finish.
Bước 2: Tạo cấu trúc của dự án.
Bạn tạo cấu trúc của dự án như sau. Nhớ xóa file index.jsp trong trong thư mục webapp.
Bước 3: Cấu hình dependency trong build.gradle:
dependencies {
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.17.RELEASE'
compile group: 'org.thymeleaf', name: 'thymeleaf-spring4', version: '3.0.4.RELEASE'
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
}
Code language: JavaScript (javascript)
Bước 4: Cấu hình cho ứng dụng
4.1. Tạo class AppConfiguration trong thư mục com.codegym cấu hình thymeleaf và views
package com.codegym;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
@Configuration
@ComponentScan("com.codegym.controller")
@EnableWebMvc
public class AppConfiguration implements ApplicationContextAware {
@Bean
public SpringResourceTemplateResolver templateResolver(){
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
@Bean
public TemplateEngine templateEngine(){
TemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
public ViewResolver viewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
}
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
Code language: JavaScript (javascript)
4.2. Tạo class AppInitializer trong thư mục com.codegym
package com.codegym;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{AppConfiguration.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[0];
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
Code language: JavaScript (javascript)
Bước 5: Tạo lớp MyCounter trong thư mục model
package com.codegym.model;
public class MyCounter {
private int count;
public MyCounter() {
}
public MyCounter(int count) {
this.count = count;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int increment() {
return count++;
}
}
Code language: PHP (php)
Trong lớp MyCounter chúng ta khai báo một biến count để tăng lượt view sau mỗi lần người dùng truy cập trang và một phương thức increment() để thi hành việc tăng giá trị cho biến count.
Bước 6: Xây dựng lớp CounterController
package com.codegym.controller;
import com.codegym.model.MyCounter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@SessionAttributes("mycounter")
public class CounterController {
/* add MyCounter in model attribute */
@ModelAttribute("mycounter")
public MyCounter setUpCounter() {
return new MyCounter();
}
@GetMapping("/")
public String get(@ModelAttribute("mycounter") MyCounter myCounter) {
myCounter.increment();
return "index";
}
}
Code language: CSS (css)
Trong đó:
- Annotation @SessionAttributes(“mycounter”) được sử dụng để lưu trữ model attribute trong session. Trong đoạn mã trên, model attribute “mycounter” sẽ được thêm vào session nếu tên attribute của @ModelAttribute và @SessionAttributes giống nhau.
- Annotation @ModelAttribute liên kết một tham số phương thức hoặc một phương thức trả về giá trị cho một model attribute và sau đó trả nó về một view cụ thể.
- hàm increment() có nhiệm vụ tăng giá trị thuộc tính count của đối tượng myCounter
Bước 7: Xây dựng view hiển thị lượt truy cập trang
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${'View count: ' + mycounter.getCount()}"></h1>
</body>
</html>
Code language: HTML, XML (xml)
Bước 8: Cấu hình Artifact và Tomcat
Bước 9: Chạy ứng dụng
Ứng dụng sau khi chạy sẽ hiển thị như sau:
Hãy refresh trình duyệt để thấy kết quả.
Mã nguồn tham khảo: https://github.com/codegym-vn/java-spring-hit-counter
Leave a Reply