Spring Boot 初體驗(9)使用thymeleaf
阿新 • • 發佈:2018-11-01
步驟:在pom.xml中引入thymeleaf
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
關於thymeleaf的相關配置
######################################################## ###THYMELEAF (ThymeleafAutoConfiguration) ######################################################## #spring.thymeleaf.prefix=classpath:/templates/ #spring.thymeleaf.suffix=.html #spring.thymeleaf.mode=HTML5 #spring.thymeleaf.encoding=UTF-8 # ;charset=<encoding> is added #spring.thymeleaf.content-type=text/html # set to false for hot refresh 開發時設定不用快取,生產環境設定為true spring.thymeleaf.cache=false
開始使用:
編寫模板檔案 :預設都放在 src/main/resouces/templates資料夾下
例如:src/main/resouces/templates/hello.html
示例程式碼:
package com.mt.controller; import java.util.Date; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/thymeleaf")public class ThymeleafController { @RequestMapping("/hello") public String hello(Map<String, Object> map) { map.put("date", new Date()); return "thymeleafDemo"; } }
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello thymeleaf!</title>
</head>
<body>
<h1 th:inline="text">Hello.v.2</h1>
<p th:text="${date}"></p>
</body>
</html>