1. 程式人生 > >SpringBoot 整合 thymeleaf

SpringBoot 整合 thymeleaf

一、pom.xml Thymeleaf 依賴

 <!-- thymeleaf依賴 -->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>

二、在 Spring Boot 專案中加入 Thymeleaf 依賴,即可啟動其預設配置。如果想要自定義配置,可以在 application.properties 配置如下

spring.thymeleaf.cache=true # Enable template caching.
spring.thymeleaf.check-template=true # Check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Check that the templates location exists.
spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

三、Controller 如何將 View 指向 Thymeleaf

@RestController
public class HelloController
{
    @RequestMapping("/")
    public String hello(Model model)
    {
        model.addAttribute("hello","hello thymeleaf");//新增一個值為"hello thymeleaf"的hello變數到檢視
        return "hello";//在templates下尋找hello.html
    }
	// 上面方法 等價於 下面方法
	 @RequestMapping("/")
	 public String hello(HttpServletRequest request)
    {
        request.setAttribute("hello","hello thymeleaf");//新增一個值為"hello thymeleaf"的hello變數到檢視
        return "hello";//在templates下尋找hello.html
    }
}

四、建立模版頁面
在resources/templates建立一個hello.html頁面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><!-- xmlns:th="http://www.thymeleaf.org" 減少ide報錯,可以沒有 -->
<head>
    <meta charset="UTF-8"/>
    <title>Hello</title>
</head>
<body>
<h1 th:text="${hello}">LieRabbit</h1><!-- 使用hello變數 -->
<img src="lierabbit.jpg"/>
</body>
</html>

五、新增圖片資源

在resources/static新增lierabbit.jpg

六、執行結果
在這裡插入圖片描述