在以前的示例中,咱們都是經過@RestController來處理請求,因此返回的內容爲json對象。咱們如今須要實現更復雜的頁面顯示,就須要用到模板引擎來幫我實現了。
Spring Boot默認提供靜態資源目錄位置需置於classpath下,目錄名需符合以下規則:html
/static /public /resources /META-INF/resources
例如:咱們在src/main/resources/目錄下建立static,並在該位置放置一個圖片文件A.jpg。啓動程序後,訪問http://localhost:8080/A.jpg。如能顯示圖片,則配置成功。web
在動態HTML實現上Spring Boot依然能夠完美勝任,而且提供了多種模板引擎的默認配置支持,因此在推薦的模板引擎下,咱們能夠很快的上手開發動態網站。spring
Spring Boot提供了默認配置的模板引擎主要有如下幾種:json
Thymeleaf FreeMarker Velocity Groovy Mustache
在這裏咱們發現沒有咱們曾經最熟悉的JSP,那是由於JSP沒法實現Spring Boot的多種特性,若是非要使用JSP,也是能夠經過配置進行實現的。後面咱們再說。緩存
Thymeleaf是一種簡單且容易上手的模板引擎,咱們如今就選擇它來進行具體的介紹吧!app
咱們根據上一篇文章新建一個項目,在選擇依賴的時候須要選擇Web和Thymeleaf便可。spring-boot
打開pom.xml文件咱們能夠看到引入的依賴。測試
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
在Spring Boot中使用Thymeleaf,只須要引入上面的依賴,並在默認的模板路徑src/main/resources/templates下編寫模板文件便可完成。網站
下面咱們來簡單的寫一個示例:編碼
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>測試頁面</title> </head> <body> <h1 th:text="${newWorld}">Hello World</h1> </body> </html>
注意:若是想要使用模板引擎的話,就須要在頁面引用thymeleaf語法空間。就是 xmlns:th="http://www.thymeleaf.org",thymeleaf的語法就是th:xxxx=「數據」,具體能夠看官方說明文檔。
@RequestMapping("/index") public String index(ModelMap map){ map.addAttribute("newWorld","WELCOME TO NEW WORLD!!!"); return "index"; }
運行項目,輸入項目地址再次查看頁面顯示內容,內容被替換了。
在application.yml中能夠配置thymeleaf模板解析器屬性
# THYMELEAF (ThymeleafAutoConfiguration) #開啓模板緩存(默認值:true) spring.thymeleaf.cache=true #Check that the template exists before rendering it. spring.thymeleaf.check-template=true #檢查模板位置是否正確(默認值:true) spring.thymeleaf.check-template-location=true #Content-Type的值(默認值:text/html) spring.thymeleaf.content-type=text/html #開啓MVC Thymeleaf視圖解析(默認值:true) spring.thymeleaf.enabled=true #模板編碼 spring.thymeleaf.encoding=UTF-8 #要被排除在解析以外的視圖名稱列表,用逗號分隔 spring.thymeleaf.excluded-view-names= #要運用於模板之上的模板模式。另見StandardTemplate-ModeHandlers(默認值:HTML5) spring.thymeleaf.mode=HTML5 #在構建URL時添加到視圖名稱前的前綴(默認值:classpath:/templates/) spring.thymeleaf.prefix=classpath:/templates/ #在構建URL時添加到視圖名稱後的後綴(默認值:.html) spring.thymeleaf.suffix=.html #Thymeleaf模板解析器在解析器鏈中的順序。默認狀況下,它排第一位。順序從1開始,只有在定義了額外的TemplateResolver Bean時才須要設置這個屬性。 spring.thymeleaf.template-resolver-order= #可解析的視圖名稱列表,用逗號分隔 spring.thymeleaf.view-names=