JSP là một dạng template đầu tiên mà java sử dụng cho các dự án web. Tuy nhiên với cá nhân mình lại không thích JSP vì mình cảm giác cú pháp của nó có những cái phức tạp, ví dụ để lặp qua một mảng chúng ta sẽ cần đoạn mã như sau:

<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<html>
   <head>
      <title><c:forEach> Tag Example</title>
   </head>

   <body>
      <c:forEach var = "i" begin = "1" end = "5">
         Item <c:out value = "${i}"/><p>
      </c:forEach>
   </body>
</html>

Ở đây có thêm khái niệm về taglib mà chúng ta phải học. Hồi đầu mình không tài nào mà hiểu nổi taglib nó là cái gì và làm theo kiểu học vẹt.
Với Thymeleaf một thư viện hỗ trợ lập trình view với template ở dạng html đến từ cộng đồng, cũng gần giống với JSP mình cảm thấy có những cái đơn giản hơn, vậy nên trong bài này Dũng sẽ cùng các bạn đi tìm hiểu về Thymeleaf và spring boot nhé.

Khởi tạo module

Chúng ta sẽ cần khởi tạo module có tên spring-boot-thymeleaf.

Cấu hình dự án

Chúng ta sẽ cần thay đổi mã nguồn của tập tin spring-boot-thymeleaf/pom.xml thành như sau:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>vn.techmaster</groupId>
        <artifactId>mastering-spring-boot</artifactId>
        <version>1.0.0</version>
    </parent>

    <artifactId>spring-boot-thymeleaf</artifactId>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
</project>

Chúng ta đã bổ sung thêm thư viện spring-boot-starter-thymeleaf, ở bên trong thì thư viện này đã bao gồm thư viện thymeleaf cho chúng ta:

<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf-spring6</artifactId>
  <version>3.1.2.RELEASE</version>
  <scope>compile</scope>
</dependency>

Cần lưu ý rằng thymeleaf không phải là thư viện do spring tạo ra mà nó chỉ sử dụng mà thôi.

Tạo HomeController

Cũng tương tự như sử dụng với jsp, chúng ta vẫn cần tạo ra một controller có tên HomeController như sau:

package vn.techmaster.thymeleaf.controller;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import vn.techmaster.thymeleaf.service.GreetingService;

@Controller
@AllArgsConstructor
public class HomeController {

    private final GreetingService greetingService;

    @GetMapping("/")
    public String home(
        @RequestParam(name="name") String name,
        Model model
    ) {
        String greetingMessage = greetingService.greet(name);
        model.addAttribute("message", greetingMessage);
        return "home";
    }
}

Ở đây chúng ta sẽ sử dụng một template có tên là home, nó sẽ là template home.html mà chúng ta sẽ tạo ở phía bên dưới.
Lớp GreetingService có mã nguồn như sau:

package vn.techmaster.thymeleaf.service;

import org.springframework.stereotype.Service;

@Service
public class GreetingService {

    public String greet(String name) {
        return "Hello, " + name + "!";
    }
}

Tạo tập tin template

Như đã nói ở trên chúng ta sẽ tạo ra một tập tin home.xml trong thư mục spring-boot-thymeleaf/src/main/resources/templates như sau:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Greeting</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>

Mã nguồn này khá đơn giản khi chỉ in ra một message mà thôi.

Khởi chạy chương trình

Để khởi chạy chương trình, chúng ta sẽ cần cài đặt lớp ThymeleafStartUp như sau:

package vn.techmaster.thymeleaf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ThymeleafStartUp {

    public static void main(String[] args) {
        SpringApplication.run(ThymeleafStartUp.class, args);
    }
}

Khi chạy chương trình, chúng ta sẽ có một máy chủ chạy trên cổng 8080 theo log như sau:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.3.1)

2024-07-01T15:23:45.479+07:00  INFO 4999 --- [           main] v.techmaster.thymeleaf.ThymeleafStartUp  : Starting ThymeleafStartUp using Java 17.0.7 with PID 4999 (/Users/tvd12/Documents/techmaster/mastering-spring-boot/spring-boot-thymeleaf/target/classes started by tvd12 in /Users/tvd12/Documents/techmaster/mastering-spring-boot)
2024-07-01T15:23:45.487+07:00  INFO 4999 --- [           main] v.techmaster.thymeleaf.ThymeleafStartUp  : No active profile set, falling back to 1 default profile: "default"
2024-07-01T15:23:46.840+07:00  INFO 4999 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2024-07-01T15:23:46.863+07:00  INFO 4999 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2024-07-01T15:23:46.863+07:00  INFO 4999 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.25]
2024-07-01T15:23:46.942+07:00  INFO 4999 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2024-07-01T15:23:46.945+07:00  INFO 4999 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1387 ms
2024-07-01T15:23:47.474+07:00  INFO 4999 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2024-07-01T15:23:47.484+07:00  INFO 4999 --- [           main] v.techmaster.thymeleaf.ThymeleafStartUp  : Started ThymeleafStartUp in 2.631 seconds (process running for 3.832)

Truy cập vào địa chỉ http://localhost:8080/?name=Techmaster chúng ta sẽ nhận được kết quả là:

Tổng kết

Như vậy chúng ta đã cùng nhau khởi tạo một dự án sử dụng spring boot và thymeleaf và khởi chạy thành công.


Cám ơn bạn đã quan tâm đến bài viết|video này. Để nhận được thêm các kiến thức bổ ích bạn có thể:

  1. Đọc các bài viết của TechMaster trên facebook: https://www.facebook.com/techmastervn
  2. Xem các video của TechMaster qua Youtube: https://www.youtube.com/@TechMasterVietnam nếu bạn thấy video/bài viết hay bạn có thể theo dõi kênh của TechMaster để nhận được thông báo về các video mới nhất nhé.
  3. Chat với techmaster qua Discord: https://discord.gg/yQjRTFXb7a