springboot的thymeleaf解析html模板错误AND Thymeleaf表达式简单使用

下面出现错误的代码:

java代码:

@Controller
@RequestMapping("/sample/")
public class SampleController {

    @RequestMapping("/thymeleaf")
    public String thymeleaf(){
//        model.addAttribute("name","dada");
        return "hello";
    }
}

html代码:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" http-equiv="Content-Type">
    <title>hello</title>
</head>
<body>
    <p th:text="hello">"hello" +${name}</p>
</body>
</html>

application.properties配置代码:

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

运行后发现浏览器报无法解析hello模板,后面在下面的这两篇文章找到了原因

LINK: https://blog.csdn.net/aixp88/article/details/72848332

LINK: https://blog.csdn.net/chaofansea/article/details/79042635

springboot默认使用 Thymeleaf 2.X版本,这个版本无法识别html5中常见的自闭合标签

就是这段html代码没有使用 ''/'' 关闭标签:

<meta charset="UTF-8" http-equiv="Content-Type">

三种解决方案:

1.严格按照thymeleaf 2.X 版本的编写html (不建议)

2.使用thymeleaf 3.X 版本,在pom.xml文件加入以下代码

<properties>
    <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>

然后在application.properties中添加以下一句:

spring.thymeleaf.mode: HTML

3.在application.properties中增加:

spring.thymeleaf.content-type=text/html 
# 开发环境中关闭缓存便于测试
spring.thymeleaf.cache=false 
spring.thymeleaf.mode =LEGACYHTML5

并在pom.xml中添加依赖nekoHTML 1.9.15 or newer

<dependency>
      <groupId>net.sourceforge.nekohtml</groupId>
      <artifactId>nekohtml</artifactId>
      <version>1.9.22</version>
</dependency>

关于Thymeleaf标签的简单使用和属性:

LINK: https://www.cnblogs.com/beyrl-blog/p/6633182.html

原文地址:https://www.cnblogs.com/sybk/p/10004713.html