SSM框架整合thymeleaf-spring5模板引擎

1、pom.xml文件增加依賴:

<!--thymeleaf-spring5 -->
<dependency>
	 <groupId>org.thymeleaf</groupId>
	 <artifactId>thymeleaf-spring5</artifactId>
	 <version>3.0.11.RELEASE</version>
</dependency>

2、將spring-mvc.xml中原先jsp的視圖解析器修改:

<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>

3、測試,controller:

@Controller
@RequestMapping("/test")
public class TestController {
    @RequestMapping("")
    public String test(Model model)
    {
        model.addAttribute("name","I'm thymeleaf !");
        return "test";
    }
}

4、編寫test.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1 th:text="${name}"></h1>
</body>
</html>

5、訪問:
在這裏插入圖片描述
注意

  • <property name="prefix" value="/WEB-INF/templates/"/>這裏寫頁面相應的目錄。
  • 在html頭添加xmlns:th="http://www.thymeleaf.org",以便提示thymeleaf語法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章