spring-boot-starter-thymeleaf 避坑指南


第一步:pom配置环境 先不要管包是做什么的 总之必须要有 否则进坑


      
          net.sourceforge.nekohtml
          nekohtml
          1.9.22
      
       
      
          org.springframework.boot
          spring-boot-starter-thymeleaf

第二步:配置application.properties 

       注意  1.结尾一定要有------ #thymeleaf end ---------  否则掉坑

                2.#模板编码 spring.thymeleaf.mode=LEGACYHTML5

                要想使用LEGACYHTML5这个编码格式必须引入 上面pom中‘避坑包’  否则用不了

               肯定有人要问为什么不用HTML5 ,你可以试试

                因为你可能会发现在默认配置下,thymeleaf对.html的内容要求很严格,比如

                如果少最后的标签封闭符号/,就会报错而转到错误页。也比如你在使用Vue.js这样的库,然后有

这样的html代码,

               也会被thymeleaf认为不符合要求而抛出错误。因此,建议增加下面这段:

                 spring.thymeleaf.mode = LEGACYHTML5
                 spring.thymeleaf.mode的默认值是HTML5,其实是一个很严格的检查,改为LEGACYHTML5可以得到一个可能更友好亲切的格式要求。

               需要注意的是,LEGACYHTML5需要搭配一个额外的库NekoHTML才可用  也就时上文的避坑包

#
spring.thymeleaf.cache=false
## 检查模板是否存在,然后再呈现
spring.thymeleaf.check-template-location=true
#Content-Type值
spring.thymeleaf.content-type=text/html
#启用MVC Thymeleaf视图分辨率
spring.thymeleaf.enabled=true
## 应该从解决方案中排除的视图名称的逗号分隔列表
##spring.thymeleaf.excluded-view-names=
#模板编码
spring.thymeleaf.mode=LEGACYHTML5
# 在构建URL时预先查看名称的前缀
spring.thymeleaf.prefix=classpath:/templates/
# 构建URL时附加查看名称的后缀.
spring.thymeleaf.suffix=.html
# 链中模板解析器的顺序
#spring.thymeleaf.template-resolver-order= o
# 可以解析的视图名称的逗号分隔列表
#spring.thymeleaf.view-names=
#thymeleaf end

 这是我的静态网页结构

第三步:controller层

   注入的时候一定要是Controller 不要是RestController 因为它是rest接口(json格式) 是解析不到html

@Controller  注意不要是RestController
@RequestMapping(value = "/")
public class MainController {
 
 
    @Autowired
    MainService mainService;
 
          @GetMapping(value = "/home")
          public String homePage(){
 
              return "test";
          }
}

实在没有那么多需求 就用原生态 随便玩想跳哪里跳哪里

 @GetMapping(value = "/home")
          public void homePage(HttpServletResponse response)throws IOException{
              response.sendRedirect("index.html");
//              return "index";
          }

需要传值的话,java界面使用正常的方法就可 

  model.addAttribute("yu","Hello world Thymeleaf");

在html 界面需在html 标签里引用地址 。thymeleaf 使用的是OGNL 标签,和jstl 标签差不多个人感觉,例如:

"en" xmlns:th="http://www.thymeleaf.org">


"${yu}">

我是用的是IDEA 编译 使用标签的话 会报错 只有添加 注释才不会报错

标签的话不需要自己写,点击左边报错的小红点会提示标签注释,自动生成

  最后收工,这么简单的东西也是走过腥风血雨过来的!!!