前言
有些初學(xué)SpringBoot?thymeleaf模板的同學(xué),會(huì)容易犯些小錯(cuò)誤热康。所以這里簡(jiǎn)單說(shuō)一下
一、thymeleaf安裝
根據(jù)SpringBoot官方文檔褐隆,要配置一下啟動(dòng)器庶弃,如下
thymeleaf官網(wǎng)文檔得知目前最新為版本3
只要我們把HTML頁(yè)面放在classpath:/templates/歇攻,thymeleaf就能自動(dòng)渲染缴守;
使用:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#using-texts
<html xmlns:th="http://www.thymeleaf.org">
二屡穗、使用注意事項(xiàng)
如果使用到模板的話那么要使用@Controller注解而非@RestController注解村砂。這樣在安裝templates模板的情況下就會(huì)自動(dòng)跳轉(zhuǎn)到對(duì)應(yīng)的模板頁(yè)屹逛。
所查到的模板頁(yè)名字與你對(duì)應(yīng)的處理函數(shù)返回值一樣罕模,如:
//在有@Controller注解下淑掌,去模板目錄resources/templates查找名為hello.html的模板
? ? @RequestMapping("/")
? ? public String hello(){
? ? ? ? return "hello";
? ? }
三、把數(shù)據(jù)推到模板中
使用thymeleaf模板時(shí)芋绸,我們往往需要把數(shù)據(jù)推到thymeleaf模板中展示出來(lái)侥钳,如把變量柄错、對(duì)象、請(qǐng)求參數(shù)結(jié)果等给猾。我們?cè)趕pringMVC中知道我3種方式
3.1 使用ModelAndView
HelloController.java代碼
resources/templates/success.html模板內(nèi)容如下:
運(yùn)行結(jié)果:
3.2?使用map
如果map可以直接用使用key扯饶,語(yǔ)法:"${keyName}"
HelloController.java代碼修改如下:
其它不變尾序,發(fā)現(xiàn)結(jié)果上3.1是一樣的
3.3 使用使用Model類(lèi)型
HelloController.java代碼修改如下:
運(yùn)行結(jié)果也是一樣的