自歷來公司後都沒用過jsp當界面渲染了,由於先後端分離不是很好,反而模板引擎用的比較多,thymeleaf最大的優點後綴爲html,就是隻須要瀏覽器就能夠展示頁面了,還有就是thymeleaf能夠很好的和spring集成.下面開始學習.html
1.引入依賴
maven中直接引入java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1
2
3
4
能夠查看依賴關係,發現spring-boot-starter-thymeleaf下面已經包括了spring-boot-starter-web,因此能夠把spring-boot-starter-web的依賴去掉.web
2.配置視圖解析器
spring-boot不少配置都有默認配置,好比默認頁面映射路徑爲
classpath:/templates/*.html
一樣靜態文件路徑爲
classpath:/static/spring
在application.properties中能夠配置thymeleaf模板解析器屬性.就像使用springMVC的JSP解析器配置同樣後端
#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#開發時關閉緩存,否則無法看到實時頁面
spring.thymeleaf.cache=false
#thymeleaf end
1
2
3
4
5
6
7
具體能夠配置的參數能夠查看
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties這個類,上面的配置實際上就是注入到該類中的屬性值.瀏覽器
3.編寫DEMO緩存
1.控制器app
@Controller
public class HelloController {前後端分離
private Logger logger = LoggerFactory.getLogger(HelloController.class);
/**
* 測試hello
* @return
*/
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String hello(Model model) {
model.addAttribute("name", "Dear");
return "hello";
}jsp
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2.view(註釋爲IDEA生成的索引,便於IDEA補全)
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>hello</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <!--/*@thymesVar id="name" type="java.lang.String"*/--> <p th:text="'Hello!, ' + ${name} + '!'" >3333</p> </body> </html>