Spring Boot整合模板引擎thymeleaf

項目結構

引入依賴pom.xml

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

配置application.properties

############################################################
#
# thymeleaf 靜態資源配置
#
############################################################
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
# spring.thymeleaf.content-type=text/html
# 關閉緩存, 即時刷新, 上線生產環境須要改成true
spring.thymeleaf.cache=false

模板頁index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
Thymeleaf模板引擎
<h1 th:text="${name}">hello world~~~~~~~</h1>
</body>
</html>

控制器Controller

@Controller
@RequestMapping("demo/th")
public class ThymeleafController {
    @RequestMapping("/index")
    public String index(ModelMap map) {
        map.addAttribute("name", "thymeleaf-nick");
        return "thymeleaf/index";
    }

    @RequestMapping("center")
    public String center() {
        return "thymeleaf/center/center";
    }
}

測試

完整代碼

相關文章
相關標籤/搜索