SSH/SSM项目中如何集成thymeleaf

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(1050)   2023-03-28 11:29:14
      SSH/SSM项目中如何集成thymeleaf?本文将讲解SSH/SSM项目中如何集成thymeleaf模板引擎。为啥要用thymeleaf模板引擎呢?相信用过的小伙伴都知道使用它之后和前端打交道是否更容易了呢?接下来进入正题吧。
 

1.添加必须依赖

<!--视图模板引擎-->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>2.1.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring4</artifactId>
    <version>2.1.6.RELEASE</version>
</dependency>

注意:如果是用3.X版本需要引入

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.0</version>
</dependency>

版本大于2.5.0如果当前项目因其他依赖关系则放弃3.x使用2.x即可不依赖该库


2.配置

SSH/SSM项目一般都有spring mvc的配置。修改spring mvc配置文件。添加以下内容
<!--定义视图模板引擎-->
<!--org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver-->
<!--org.thymeleaf.templateresolver.ServletContextTemplateResolver-->
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
    <property name="prefix" value="/WEB-INF/templates/"/>
    <property name="suffix" value=".htm"/>
    <property name="templateMode" value="HTML5"/>
    <property name="cacheable" value="false"/><!-- 缓存-->
    <property name="characterEncoding" value="UTF-8"/><!--解决中文乱码-->
</bean>
<bean id="templateEngine"
      class="org.thymeleaf.spring4.SpringTemplateEngine">
    <property name="templateResolver" ref="templateResolver"/>
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine"/>
    <property name="order" value="2"/>
    <property name="viewNames" value="*_th"/>
    <property name="characterEncoding" value="UTF-8"/><!--解决中文乱码-->
</bean>

注意,order必须小于JSP的大小默认不设置即可。设置一定要注意否则各种404问题。

上面使用htm作为后缀是因为老项目将HTML后缀做过特殊统一处理。这里所以放弃HTML使用htm

添加layout扩展插件

1.添加依赖
 

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    <version>1.4.0</version>
</dependency>
2.修改spring mvc配置
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine"/>
    <property name="order" value="2"/>
    <property name="viewNames" value="*_th"/>
    <property name="characterEncoding" value="UTF-8"/><!--解决中文乱码-->
</bean>
 
标签: thymeleaf
地址:https://www.leftso.com/article/418.html

相关阅读

SSH/SSM项目中如何集成thymeleaf?本文将讲解SSH/SSM项目中如何集成thymeleaf模板引擎
Thymeleaf 递归,Thymeleaf模板引擎递归展示如评论留言等场合适用
本文说一下在thymeleaf模板引擎中,如何给 textarea 赋值
thymeleaf模板 报错信息:​​​​​​​org.thymeleaf.exceptions.TemplateInputException: Error resolving template...
thymeleaf 设置不校验html标签
springboot 使用thymeleaf 模板引擎中url中的&引起的org.xml.sax.SAXParseException: 对实体 "uid" 的引用必须以 ';' 分隔符结尾。问题解决
一、项目环境Spring Boot 2.1.2.RELEASEshiro-spring 1.4二、去掉URL jsessionid在shiro配置中,配置关闭url中显示sessionId ...
spring boot 开发技巧,在开发web项目中跳过thyemeleaf模板/js/css等缓存避免每次修改资源文件都需要重启服务器
Spring Boot 1.x升级到Spring Boot 2.0迁移指南