1. 程式人生 > 程式設計 >框架—Thymeleaf模板引擎 Spring5整合Thymeleaf(XML配置 和 註解配置)

框架—Thymeleaf模板引擎 Spring5整合Thymeleaf(XML配置 和 註解配置)

1. 依賴

​ 在配置好SSM框架後,在pom.xml中新增如下依賴

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.9.RELEASE</version>
</dependency>
複製程式碼

2. 配置

  • 配置檔案方式 ​ 在Sping_mvc.xml中加入如下配置,並且註釋掉jsp的viewResolver或freemarker的配置
<bean id="templateResolver"
      class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
    <property name="prefix" value="/WEB-INF/templates/"/>
    <property name="suffix" value=".html"/>
    <property name="characterEncoding" value="UTF-8"/>
    <property
name="order" value="1"/>
<property name="templateMode" value="HTML5"/> <property name="cacheable" value="false"/> </bean> <bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver"
/>
</bean> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine"/> <property name="characterEncoding" value="UTF-8"/> </bean> 複製程式碼
  • 註解配置webConfig.java中中加入如下配置,如果配置了jsp或者freemarker請註釋掉jsp的viewResolver或freemarker的配置
@Configuration
@EnableWebMvc
@ComponentScan({"com.example.controller","com.example.api"})
public class WebConfig implements WebMvcConfigurer {

    /**
     * 模板解析器
     *
     * @return
     */
    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix(TEMPLATE_PREFIX);
        templateResolver.setSuffix(TEMPLATE_SUFFIX);
        templateResolver.setCacheable(TEMPLATE_CACHEABLE);
        templateResolver.setCharacterEncoding(CHARACTER_ENCODING);
        templateResolver.setTemplateMode(TEMPLATE_MODE);
        templateResolver.setOrder(TEMPLATE_ORDER);
        return templateResolver;
    }

    /**
     * 模板引擎
     *
     * @return
     */
    @Bean
    public SpringTemplateEngine springTemplateEngine(SpringResourceTemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }

    /**
     * 檢視解析器
     *
     * @return
     */
    @Bean
    public ThymeleafViewResolver viewResolver(SpringTemplateEngine springTemplateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(springTemplateEngine);
        viewResolver.setCharacterEncoding(CHARACTER_ENCODING);
        return viewResolver;
    }
//.......其他配置請自行配置
}
複製程式碼

由於我使用了CONSTANTS類裡面的static變數,所以附上Constants類相關的引數

    public final static String CHARACTER_ENCODING = "UTF-8";

    /**
     * thymeleaf模板引擎引數
     */
    public final static String TEMPLATE_PREFIX = "/WEB-INF/templates/";
    public final static String TEMPLATE_SUFFIX = ".html";
    public final static Boolean TEMPLATE_CACHEABLE = false;
    public final static String TEMPLATE_MODE = "HTML5";
    public final static Integer TEMPLATE_ORDER = 1;
複製程式碼

此配置需要注意以下幾點:

  • templateResolver的prefix與suffix對應你的檢視層的檔案位置
  • templateResolver的characterEncoding和viewResolver的都要設定成UTF-8中文才不會亂碼。
  • templateResolver的cacheable一定要在開發的時候設定成false不然無法看到實時的頁面資料

3. 測試

  • controller:

    在ModelMap裡面隨便設定一點值

    @RequestMapping("/test")
    public String test(ModelMap map) {
        map.put("thText","設定文字內容");
        map.put("thUText","設定文字內容");
        map.put("thValue","設定當前元素的value值");
        map.put("thEach",Arrays.asList("列表","遍歷列表"));
        map.put("thIf","msg is not null");
        map.put("thObject",new 							UserEntity("sadfa","asfasfd","asfsaf","asdfasf","saf","asfd","sadf",1));
    		
        return "test";
    }
    複製程式碼
  • test.html

    <!DOCTYPE html>
    <html lang="cn" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h1>TEST</h1>
    <h2>Thymeleaf</h2>
    <!--th:text 設定當前元素的文字內容,常用,優先順序不高-->
    <p th:text="${thText}" />
    <p th:utext="${thUText}" />
    
    <!--th:value 設定當前元素的value值,常用,優先順序僅比th:text高-->
    <input type="text" th:value="${thValue}" />
    
    <!--th:each 遍歷列表,常用,優先順序很高,僅此於程式碼塊的插入-->
    <!--th:each 修飾在div上,則div層重複出現,若只想p標籤遍歷,則修飾在p標籤上-->
    <div th:each="message : ${thEach}"> <!-- 遍歷整個div-p,不推薦-->
        <p th:text="${message}" />
    </div>
    <div> <!--只遍歷p,推薦使用-->
        <p th:text="${message}" th:each="message : ${thEach}" />
    </div>
    
    <!--th:if 條件判斷,類似的有th:switch,th:case,優先順序僅次於th:each,其中#strings是變量表達式的內建方法-->
    <p th:text="${thIf}" th:if="${not #strings.isEmpty(thIf)}"></p>
    
    <!--th:insert 把程式碼塊插入當前div中,優先順序最高,類似的有th:replace,th:include,~{} :程式碼塊表示式 -->
    <div th:insert="~{grammar/common::thCommon}"></div>
    
    <!--th:object 宣告變數,和*{} 一起使用-->
    <div th:object="${thObject}">
        <p>ID: <span th:text="*{id}" /></p><!--th:text="${thObject.id}"-->
        <p>TH: <span th:text="*{username}" /></p><!--${thObject.thName}-->
        <p>DE: <span th:text="*{password}" /></p><!--${thObject.desc}-->
    </div>
    </body>
    </html>
    複製程式碼

    幾點注意:

  • 在html首標籤裡面加上xmlns

    <html lang="cn" xmlns:th="http://www.thymeleaf.org">
    複製程式碼
  • 同樣把head的meta設定一個charset=“UTF-8”

至此,你就可以去配置tomcat執行專案了。

  • 文章發表於 2018-10-09 16:10:46

關於我

  • 座標杭州,普通本科在讀,電腦科學與技術專業,20年畢業,目前處於實習階段。
  • 主要做Java開發,會寫點Golang、Shell。對微服務、大資料比較感興趣,預備做這個方向。
  • 目前處於菜鳥階段,各位大佬輕噴,小弟正在瘋狂學習。
  • 歡迎大家和我交流鴨!!!