SpringBoot集成Thymeleaf模版引擎

1、前言

  1. Thymeleaf 是一个优秀的、面向Java 的XML、HTML/HTML5 页面模板,具备丰富的标签语言和函数。所以,在使用Spring Boot 框架进行页面设计时, 通常都会选择Thymeleaf 模板。
  2. 相似thymeleaf的模版还有freemarker,推荐使用thymeleaf,先后端分离。

2、springboot集成Thymeleaf模版引擎

  1. pom.xml引入依赖html

    <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-thymeleaf</artifactId>
           </dependency>
  2. application.properties中配置:spring

    ##去除thymeleaf的html严格校验
    spring.thymeleaf.mode=LEGACYHTML5
    #设定thymeleaf文件路径 默认为src/main/resources/templates
    spring.freemarker.template-loader-path=classpath:/templates
  3. 在controller中书写相关代码,注意controller层中注解使用@controller,不要是用@RestController,不然就会出现页面返回字符串而不是正常的html页面。
  4. 模版html页面中,也是须要引入thymeleaf:后端

    <html xmlns:th="http://www.thymeleaf.org">
  5. 最后启动项目便可

3、须要注意的问题

  1. 经过以上配置后,咱们发现,有时候本身写的html页面会没法解析,这种状况就有多是由于使用springboot的thymeleaf模板时,默认会对HTML进行严格的检查,致使当标签没有闭合时就会通不过。nekohtml这个依赖能够解决这一问题。
  2. 为了解决html严格校验报错的问题,能够在pom.xml增添依赖nekohtmlspringboot

    <dependency>
               <groupId>net.sourceforge.nekohtml</groupId>
               <artifactId>nekohtml</artifactId>
               <version>1.9.15</version>
           </dependency>
相关文章
相关标签/搜索