spring-boot-starter-thymeleaf 避坑指南
第一步:pom配置環境 先不要管包是做什么的 總之必須要有 否則進坑
<!--避坑包--> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency> <!--解析html包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
第二步:配置application.properties
注意 1.結尾一定要有------ #thymeleaf end --------- 否則掉坑
2.#模板編碼 spring.thymeleaf.mode=LEGACYHTML5
要想使用LEGACYHTML5這個編碼格式必須引入 上面pom中‘避坑包’ 否則用不了
肯定有人要問為什么不用HTML5 ,你可以試試
因為你可能會發現在默認配置下,thymeleaf對.html的內容要求很嚴格,比如<meta charset=”UTF-8″ />,
如果少最后的標簽封閉符號/,就會報錯而轉到錯誤頁。也比如你在使用Vue.js這樣的庫,然后有<div v-cloak></div>這樣的html代碼,
也會被thymeleaf認為不符合要求而拋出錯誤。因此,建議增加下面這段:
spring.thymeleaf.mode = LEGACYHTML5
spring.thymeleaf.mode的默認值是HTML5,其實是一個很嚴格的檢查,改為LEGACYHTML5可以得到一個可能更友好親切的格式要求。
需要注意的是,LEGACYHTML5需要搭配一個額外的庫NekoHTML才可用 也就時上文的避坑包
#<!-- 關閉thymeleaf緩存 開發時使用 否則沒有實時畫面--> spring.thymeleaf.cache=false ## 檢查模板是否存在,然后再呈現 spring.thymeleaf.check-template-location=true #Content-Type值 spring.thymeleaf.content-type=text/html #啟用MVC Thymeleaf視圖分辨率 spring.thymeleaf.enabled=true ## 應該從解決方案中排除的視圖名稱的逗號分隔列表 ##spring.thymeleaf.excluded-view-names= #模板編碼 spring.thymeleaf.mode=LEGACYHTML5 # 在構建URL時預先查看名稱的前綴 spring.thymeleaf.prefix=classpath:/templates/ # 構建URL時附加查看名稱的后綴. spring.thymeleaf.suffix=.html # 鏈中模板解析器的順序 #spring.thymeleaf.template-resolver-order= o # 可以解析的視圖名稱的逗號分隔列表 #spring.thymeleaf.view-names= #thymeleaf end
這是我的靜態網頁結構
第三步:controller層
注入的時候一定要是Controller 不要是RestController 因為它是rest接口(json格式) 是解析不到html
@Controller 注意不要是RestController
@RequestMapping(value = "/")
public class MainController {
@Autowired
MainService mainService;
@GetMapping(value = "/home")
public String homePage(){
return "test";
}
}
實在沒有那么多需求 就用原生態 隨便玩想跳哪里跳哪里
@GetMapping(value = "/home") public void homePage(HttpServletResponse response)throws IOException{ response.sendRedirect("index.html"); // return "index"; }
需要傳值的話,java界面使用正常的方法就可
model.addAttribute("yu","Hello world Thymeleaf");
在html 界面需在html 標簽里引用地址 。thymeleaf 使用的是OGNL 標簽,和jstl 標簽差不多個人感覺,例如:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!--/*@thymesVar id="yu" type="java"*/-->
<p th:text="${yu}"></p>
我是用的是IDEA 編譯 使用標簽的話 會報錯 只有添加<!--/*@thymesVar id="yu" type="java"*/--> 注釋才不會報錯
標簽的話不需要自己寫,點擊左邊報錯的小紅點會提示標簽注釋,自動生成
最后收工,這么簡單的東西也是走過腥風血雨過來的!!!