Mục tiêu
Sau bài này, bạn sẽ:
- Hiểu cách truyền dữ liệu từ Controller xuống View trong Spring MVC
- Sử dụng thành thạo
Model,ModelMap,ModelAndView - Biết các biểu thức Thymeleaf cơ bản để hiển thị dữ liệu
- Thực hành hiển thị văn bản, đối tượng, danh sách, và xử lý điều kiện
1. So sánh với Servlet/JSP
Servlet/JSP:
// Servlet
request.setAttribute("message", "Xin chào");
request.setAttribute("products", productList);
request.getRequestDispatcher("products.jsp").forward(request, response);<!-- JSP -->
<p><%= request.getAttribute("message") %></p>
<c:forEach items="${products}" var="p">
<p>${p.name}</p>
</c:forEach>Spring Boot + Thymeleaf:
// Controller
@GetMapping("/products")
public String showProducts(Model model) {
model.addAttribute("message", "Xin chào");
model.addAttribute("products", productList);
return "products"; // -> products.html
}<!-- products.html (Thymeleaf) -->
<p th:text="${message}"></p>
<div th:each="p : ${products}">
<p th:text="${p.name}"></p>
</div>2. Các cách truyền dữ liệu trong Spring MVC
2.1. Sử dụng Model (phổ biến nhất)
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello World");
model.addAttribute("now", new Date());
return "hello";
}2.2. Sử dụng ModelMap (tương tự Model)
@GetMapping("/hello")
public String hello(ModelMap model) {
model.addAttribute("message", "Hello World");
model.put("now", new Date()); // put cũng được
return "hello";
}2.3. Sử dụng ModelAndView (gộp view và model)
@GetMapping("/hello")
public ModelAndView hello() {
ModelAndView mav = new ModelAndView("hello");
mav.addObject("message", "Hello World");
mav.addObject("now", new Date());
return mav;
}3. Giới thiệu Thymeleaf
Thymeleaf là một template engine (giống JSP) nhưng mạnh mẽ và hiện đại hơn. Đặc điểm:
- File template là HTML thuần, có thể mở trực tiếp trong trình duyệt (không cần chạy server)
- Sử dụng thuộc tính
th:*để xử lý dữ liệu động - Tích hợp sâu với Spring Boot (mặc định khi thêm starter)
Cú pháp cơ bản:
| Biểu thức | Ý nghĩa | Ví dụ |
|---|---|---|
${...} | Lấy giá trị từ model (biến) | <p th:text="${message}"> |
*{...} | Lấy giá trị từ object đã chọn (dùng với th:object) | <span th:text="*{name}"> |
#{...} | Lấy message từ file properties (i18n) | <span th:text="#{home.welcome}"> |
@{...} | Tạo đường dẫn URL | <a th:href="@{/products/{id}(id=${p.id})}"> |
4. Thực hành: Hiển thị dữ liệu đơn giản
4.1. Tạo Controller
@Controller
public class DemoController {
@GetMapping("/demo")
public String demo(Model model) {
model.addAttribute("title", "Trang demo Thymeleaf");
model.addAttribute("message", "Chào mừng bạn đến với Thymeleaf!");
model.addAttribute("today", java.time.LocalDate.now());
return "demo";
}
}4.2. Tạo view demo.html trong src/main/resources/templates/
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="${title}">Tiêu đề mặc định</title>
</head>
<body>
<h1 th:text="${title}">Tiêu đề</h1>
<p th:text="${message}">Nội dung mẫu</p>
<p>Hôm nay: <span th:text="${today}">2024-01-01</span></p>
</body>
</html>Kết quả: khi chạy, các giá trị từ model sẽ thay thế nội dung trong thẻ.
5. Hiển thị đối tượng
5.1. Tạo class Product
public class Product {
private Long id;
private String name;
private Double price;
// constructor, getters, setters
public Product(Long id, String name, Double price) {
this.id = id; this.name = name; this.price = price;
}
// getters/setters...
}5.2. Controller trả về một đối tượng
@GetMapping("/product")
public String showProduct(Model model) {
Product product = new Product(1L, "Laptop Dell", 1500.0);
model.addAttribute("product", product);
return "product-detail";
}5.3. View product-detail.html
Cách 1: Dùng ${product.property}
<h2>Chi tiết sản phẩm</h2>
<p>ID: <span th:text="${product.id}">1</span></p>
<p>Tên: <span th:text="${product.name}">Tên</span></p>
<p>Giá: <span th:text="${product.price}">0</span></p>Cách 2: Dùng th:object và *{...}
<div th:object="${product}">
<p>ID: <span th:text="*{id}">1</span></p>
<p>Tên: <span th:text="*{name}">Tên</span></p>
<p>Giá: <span th:text="*{price}">0</span></p>
</div>6. Hiển thị danh sách với th:each
6.1. Controller trả về danh sách
@GetMapping("/products")
public String listProducts(Model model) {
List<Product> products = Arrays.asList(
new Product(1L, "Laptop Dell", 1500.0),
new Product(2L, "Mouse Logitech", 25.0),
new Product(3L, "Bàn phím cơ", 80.0)
);
model.addAttribute("products", products);
return "product-list";
}6.2. View product-list.html
<h2>Danh sách sản phẩm</h2>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Tên</th>
<th>Giá</th>
</tr>
</thead>
<tbody>
<tr th:each="p : ${products}">
<td th:text="${p.id}">1</td>
<td th:text="${p.name}">Tên</td>
<td th:text="${p.price}">0</td>
</tr>
</tbody>
</table>Giải thích: th:each="p : ${products}" lặp qua từng phần tử, mỗi phần tử gán vào biến p.
7. Xử lý điều kiện với th:if và th:unless
<p th:if="${#lists.isEmpty(products)}">Không có sản phẩm nào.</p>
<div th:each="p : ${products}">
<span th:text="${p.name}"></span>
<span th:if="${p.price > 100}" style="color:red">(Giá cao)</span>
<span th:unless="${p.price > 100}" style="color:green">(Giá thấp)</span>
</div>#lists là một utility object có sẵn. Còn nhiều utility khác: #strings, #dates, #numbers.
8. Tạo URL với @{...}
8.1. Đường dẫn tĩnh
<a th:href="@{/}">Trang chủ</a>8.2. Đường dẫn có tham số
<!-- Sinh ra: /products/detail?id=1 -->
<a th:href="@{/products/detail(id=${p.id})}">Xem chi tiết</a>
<!-- Hoặc dạng path variable: /products/1 -->
<a th:href="@{/products/{id}(id=${p.id})}">Xem chi tiết</a>9. Thực hành tổng hợp: Trang danh sách + chi tiết
9.1. ProductController
@Controller
@RequestMapping("/products")
public class ProductController {
// Giả lập dữ liệu
private List<Product> products = Arrays.asList(
new Product(1L, "Laptop Dell", 1500.0),
new Product(2L, "Mouse Logitech", 25.0),
new Product(3L, "Bàn phím cơ", 80.0)
);
@GetMapping
public String list(Model model) {
model.addAttribute("products", products);
return "product-list";
}
@GetMapping("/{id}")
public String detail(@PathVariable Long id, Model model) {
Product product = products.stream()
.filter(p -> p.getId().equals(id))
.findFirst()
.orElse(null);
model.addAttribute("product", product);
return "product-detail";
}
}9.2. View product-list.html (bổ sung link chi tiết)
<table>
<tr th:each="p : ${products}">
<td th:text="${p.id}"></td>
<td>
<a th:href="@{/products/{id}(id=${p.id})}" th:text="${p.name}"></a>
</td>
<td th:text="${p.price}"></td>
</tr>
</table>9.3. View product-detail.html
<h2 th:if="${product == null}">Không tìm thấy sản phẩm</h2>
<div th:if="${product != null}">
<h3 th:text="${product.name}"></h3>
<p>Giá: <span th:text="${product.price}"></span></p>
<a th:href="@{/products}">Quay lại danh sách</a>
</div>10. Một số utility object hữu ích
Thymeleaf cung cấp các đối tượng tiện ích trong biểu thức ${...}:
| Utility | Mục đích | Ví dụ |
|---|---|---|
#dates | Định dạng ngày | ${#dates.format(today, 'dd/MM/yyyy')} |
#numbers | Định dạng số | ${#numbers.formatDecimal(price, 0, 'COMMA', 2, 'POINT')} |
#strings | Xử lý chuỗi | ${#strings.substring(name,0,10)} |
#lists | Xử lý list | ${#lists.size(products)} |
#arrays | Xử lý mảng | |
#sets | Xử lý set |
Ví dụ định dạng giá:
<p th:text="${#numbers.formatDecimal(p.price, 0, 'COMMA', 0, 'POINT')}"></p>11. Tổng kết
- Dùng
Model(hoặcModelMap,ModelAndView) để truyền dữ liệu từ Controller xuống View. - Thymeleaf dùng các thuộc tính
th:*để hiển thị dữ liệu động. th:texthiển thị văn bản,th:eachlặp,th:if/th:unlessrẽ nhánh.@{...}tạo URL động.- Các utility object giúp xử lý dữ liệu phức tạp.
So với JSP, Thymeleaf sạch hơn, dễ đọc hơn, và đặc biệt là file HTML vẫn mở được bình thường khi không chạy server.
12. Bài tập
- Hiển thị danh sách sinh viên:
- Tạo class
Student(id, name, age, className) - Controller trả về danh sách sinh viên
- Hiển thị dưới dạng bảng, có màu sắc xen kẽ (dùng
th:classhoặcth:stylevới điều kiện)
- Tạo class
- Trang chi tiết sinh viên:
- Khi click vào tên sinh viên, chuyển đến trang
/students/{id} - Hiển thị đầy đủ thông tin
- Khi click vào tên sinh viên, chuyển đến trang
- Định dạng:
- Hiển thị ngày tháng năm sinh (thêm field
birthdaykiểuLocalDate) với định dạng dd/MM/yyyy - Nếu sinh viên chưa có tuổi (age null), hiển thị “Chưa cập nhật”
- Hiển thị ngày tháng năm sinh (thêm field
Bài tiếp theo
[Xây dựng CRUD hoàn chỉnh với 3-layer architecture]
