1. Quản Lý Thư Viện Với Maven
Trước hết, bạn cần cập nhật file pom.xml để đưa vào các dependencies cần thiết cho khung khổ Spring và công cụ Thymeleaf. Dưới đây là cấu hình đã được điều chỉnh về tên thuộc tính:
<project xmlns="http://maven.apache.org/POM/4.0.0" ...>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.webapp</groupId>
<artifactId>demo-thymeleaf</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>Spring MVC Demo</name>
<properties>
<!-- Định nghĩa phiên bản khung chính -->
<spring.framework.ver>4.1.3.RELEASE</spring.framework.ver>
<thymeleaf.engine.ver>2.1.2.RELEASE</thymeleaf.engine.ver>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Các module cốt lõi của Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework.ver}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.framework.ver}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.framework.ver}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.framework.ver}</version>
</dependency>
<!-- Thư viện Thymeleaf tích hợp Spring -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${thymeleaf.engine.ver}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>${thymeleaf.engine.ver}</version>
</dependency>
</dependencies>
<build>
<finalName>demo-thymeleaf</finalName>
</build>
</project>
2. Định Nghĩa Context Của Spring
Vào file spring-mvc-config.xml, cần khai báo các Bean liên quan đến trình phân giải mẫu (Template Resolver) và trình xem (View Resolver) của Thymeleaf:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="...">
<!-- Kích hoạt chú thích Controller -->
<mvc:annotation-driven />
<!-- Quét package chứa Controller -->
<context:component-scan base-package="com.example.controller" />
<!-- Xử lý tài nguyên tĩnh -->
<mvc:resources location="/assets/" mapping="/assets/**" />
<!-- Cài đặt resolver cho Thymeleaf -->
<bean id="thymeleafResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<property name="characterEncoding" value="UTF-8" />
<property name="cacheable" value="false" />
</bean>
<!-- Động cơ xử lý mẫu -->
<bean id="thymeleafEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="thymeleafResolver" />
</bean>
<!-- View Resolver chuyển đổi model sang view -->
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="thymeleafEngine" />
<property name="characterEncoding" value="UTF-8" />
</bean>
</beans>
3. Tạo Giao Diện Mẫu HTML
Tạo thư mục /WEB-INF/views/ và thêm file index.html. File này sử dụng các thuộc tính th: để render dữ liệu động:
<!DOCTYPE html>
<html lang="vi" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Demo Thymeleaf Integration</title>
<script type="text/javascript" src="/assets/js/jquery.min.js"
th:src="@{/assets/js/jquery.min.js}"></script>
<script th:inline="javascript">
$(document).ready(function() {
var appPath = [[${#httpServletRequest.contextPath}]];
console.log("Context Path: " + appPath);
});
</script>
</head>
<body>
<h2>Dữ Liệu Người Dùng</h2>
<p>Xin chào: <span th:text="${userProfile.name}">Guest</span> !</p>
<p>Kết quả tìm kiếm: <span th:text="${searchKey}">N/A</span> !</p>
<p>Dữ liệu gửi đi: <span th:text="${postPayload}">Empty</span> !</p>
<a th:href="@{/display?keyword=tech}">Xem Tìm Kiếm Tech</a>
<br/>
<form th:action="@{/processData}" method="get">
Tên đăng nhập: <input type="text" name="userName"/>
Tuổi: <input type="number" name="userAge"/>
<button type="submit">Gửi Form</button>
</form>
</body>
</html>
4. Logic Điều Khiển Ứng Dụng
Trong lớp WebHandlerController, chúng ta sẽ ánh xạ các URL đến phương thức tương ứng và truyền dữ liệu vào model:
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class WebHandlerController {
@RequestMapping(value = "/{username}", method = RequestMethod.GET)
public String showUserProfile(@PathVariable String username, ModelMap map) {
map.addAttribute("userProfile", username);
map.addAttribute("searchKey", "");
map.addAttribute("postPayload", "");
return "index";
}
@RequestMapping(value = "/display", method = RequestMethod.GET)
public String performSearch(@RequestParam(value = "keyword") String key, ModelMap map) {
map.addAttribute("userProfile", "");
map.addAttribute("searchKey", key);
map.addAttribute("postPayload", "");
return "index";
}
@RequestMapping(value = "/processData", method = RequestMethod.GET)
public String handleSubmission(@RequestParam("userName") String uname,
@RequestParam("userAge") String age, ModelMap map) {
map.addAttribute("userProfile", "");
map.addAttribute("searchKey", "");
map.addAttribute("postPayload", uname + "-" + age);
return "index";
}
}