靜态頁面通路
(其他靜态資源也行)
spring boot項目隻有src目錄,沒有webapp目錄,會将靜态通路(html/圖檔等)映射到其自動配置的靜态目錄,如下
/META-INF/resources
/src/java/resources
/static
/public
/resources
比如,在resources建立一個static目錄和index.htm靜态檔案,通路位址 http://localhost:8080/index.html

隻有這三個行,放在templates 和直接放在src/main/resources 下是沒辦法靜态通路的。
HTML
第一個thymeleaf程式 1234567890!!!xx
靜态效果
靜态首頁
spring-boot靜态首頁的支援,即index.html放在以下目錄結構會直接映射到應用的根目錄下:
classpath:/META-INF/resources/index.html
classpath:/resources/index.html
classpath:/static/index.html
calsspath:/public/index.html
我一個一個試了,就截這一個圖吧,不都放上來了。
HTML
第一個thymeleaf程式 1234567890!!!xx
就隻能上面那幾個檔案夾可以,直接放在根目錄下是不行的,通過 http://localhost:8080 通路不到
動态頁面
動态頁面需要先請求伺服器,通路背景應用程式,然後再轉向到頁面,比如通路JSP。spring boot建議不要使用JSP,預設使用Thymeleaf來做動态頁面。
在pom.xml 中添加Thymeleaf元件
org.springframework.boot
spring-boot-starter-thymeleaf
TemplatesController.java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/")
public class ThymeleafController {
@RequestMapping(value = "/thymeleaf")
public String greeting(@RequestParam(name = "name", required = false, defaultValue = "world") String name,
Model model) {
model.addAttribute("xname", name);
return "index";
}
}
@RestController:上一篇中用于将傳回值轉換成json
@Controller:現在要傳回的是一個頁面,是以不能再用@RestController,而用普通的@Controller
預設跳轉到 templates/index.html 動态頁面,templates目錄為spring boot預設配置的動态頁面路徑
預設情況下隻能放這裡。
HTML
第一個thymeleaf程式 1234567890!!!xx
通路URL, http://localhost:8080/thymeleaf 結果動态資源顯示出來了。看到明顯和靜态通路不一樣。
在spring-boot下,預設約定了Controller試圖跳轉中thymeleaf模闆檔案的的
字首prefix是”classpath:/templates/”,
字尾suffix是”.html”
這個在application.properties配置檔案中是可以修改的。
如下配置可以修改試圖跳轉的字首和字尾
spring.thymeleaf.prefix: /templates/
spring.thymeleaf.suffix: .html
更過有關thymeleaf中的預設配置可以檢視org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties這個類的屬性