application.properties添加对thymeleaf的支持

1
2
3
4
5
6
7
8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

加入相关依赖

1
2
3
4
5
6
7
8
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

注意:thymeleaf模板使用的资源文件位于/resources/static,html文件一般则位于/resources/templates/。

测试controller

1
2
3
4
5
6
7
8
9
10
@Controller
public class TestController {
    @GetMapping("/test")
    public ModelAndView test() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("test");
        modelAndView.addObject("your_name","World");
        return modelAndView;
    }
}

test.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>socket.io demo</title>
    <script type="text/javascript" th:src="@{/js/jquery.js}"></script>
    <script type="text/javascript">
        $(function() {
            alert('page load.');
        });
    </script>
</head>
<body>
    Hello,<span th:text="${your_name}">!</span>
</body>
</html>


thymeleaf使用HTML5,对文件格式要求严格,比如:<input type=text>会报出下面的错误:
org.xml.sax.SAXParseException: 元素类型 “input” 必须由匹配的结束标记 ““ 终止。

解决方法参考:spring-boot-starter-thymeleaf 避坑指南

thymeleaf用法参考:https://www.cnblogs.com/ityouknow/p/5833560.html

打赏