一、描述
在應用系統開發的過程中,不可避免的需要使用靜態資源(瀏覽器看的懂,他可以有變量,例:HTML頁面,css樣式文件,文本,屬性文件,圖片等);
並且SpringBoot內置了Thymeleaf模板引擎,可以使用模板引擎進行渲染處理,默認版本為2.1,可以重新定義Thymeleaf的版本號,在maven的配置文件中配置如下內容:
<properties> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version> </properties>
二、默認靜態資源的映射
Spring Boot默認提供靜態資源目錄位置需置於classpath下,目錄名需符合如下規則:
- /static
- /public
- /resources
/META-INF/resources
SpringBoot默認會從META-INF/resources下的static、public、resources三個目錄下查找對應的靜態資源,而模板引擎的模板默認需要放在resources的templates目錄下;
三、示例
1、靜態資源的訪問
- 創建maven項目,在resources目錄下創建static、templates文件夾,將圖片success.jpg放置在static中;
- 創建啟動類,詳情請看:(一)SpringBoot基礎篇- 介紹及HelloWorld初體驗;
- 啟動項目,訪問,http://localhost:8080/success.jpg,圖片即可在頁面展示成功;
2、Thymeleaf模板引擎
①、使用Thymeleaf前,需引入依賴類庫:
<!-- 使用thymeleaf模板--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
②、創建啟動類Application.java;
③、創建控制層HelloController.java;
package com.cn.controller;/** * @Description: Created by xpl on 2018-05-01 13:23. */ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import java.util.HashMap; /** * Created by xpl on 2018-05-01 13:23 **/ @RestController public class HelloController { @RequestMapping("/getThymeleaf") public ModelAndView getThymeleaf() { ModelAndView modelAndView = new ModelAndView("hello"); modelAndView.addAllObjects(new HashMap<String, String>(){ { this.put("name","Andy"); } }); return modelAndView; } }
④、創建Thymeleaf模板hello.html,訪問變量使用th:進行訪問;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> Title</title> </head> <body> <h1>Hello,</h1> <h1 th:text="${name}"/> </body> </html>
⑤、啟動項目,並訪問http://localhost:8080/getThymeleaf,如下:
目錄結構如下: