Integrating Thymeleaf in Spring Boot Projects
Thymeleaf aims to bring elegant natural templates in to the development workflow, allowing HTML to display correct in browsers and function as static prototypes for easier team collaboration. It supports HTML, XML, JavaScript, CSS, and plain text.
JSP has long been significant in the view layer, but Thymeleaf has emerged as a new competitor. Unlike JSP, Thymeleaf is native and does not rely on tag libraries. It can edit and render content where raw HTML is accepted. Since it is not coupled with the Servlet specification, Thymeleaf templates can access areas that JSP cannot.
In Spring Boot projects, Thymeleaf files are placed in resources/templates. This directory cannot be accessed directly via a browser URL (similar to WEB-INF), so all Thymeleaf pages must go through a controller.
Set up the project, configuration files, and code structure.
Add dependencies:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.4.5</version>
</dependency>
</dependencies>
Default Thymeleaf settings:
Create a templates folder under resources. Create index.html.
Create a controller:
package com.msb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
@Controller
public class ThymeleafController {
@RequestMapping("showIndex")
public String showIndex(){
return "index";
}
}
Start the project and test.