spring-boot学习:十五、spring-boot集成thymeleaf

springboot2.x和spring5.x不再支持velocity,推荐使用thymeleaf,原因是velocity更新太慢或太少,社区不够活跃。

实现步骤:

1.引入jar包

<dependency><!--Web相关依赖-->
   <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>

2.在application.properties中配置thymeleaf

# thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.check-template=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.suffix=.htm

注意:
1) 网上很多文章说需要配置spring.thymeleaf.mode=LEGACYHTML5,在新版springboot中LEGACYHTML5已经废弃,使用HTML
2) spring.thymeleaf.prefix=必须配正确,特别是斜杠,否则可能报错template might not exist or might not be accessible by any of the configured

3.编写页面Controller

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {
	@RequestMapping("/index.do")
	public String index(Model model) {
		model.addAttribute("welcome", "Hello Kevin");
		return "index";
	}
}

4.编写页面index.htm

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
<h1 th:text="${welcome} + ' Hello World'"></h1>
</body>
</html>

备注:<html xmlns:th="http://www.thymeleaf.org">命名空间标记当前页面属于thyemeleaf模板

  1. 启动测试
    在这里插入图片描述

  2. 其他
    1)如果前端用到layui,thymeleaf会与layui中的table存在冲突

col:[[]] 改成
col:[
        [
        ]
     ]

thymeleaf语法参考:
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining

猜你喜欢

转载自blog.csdn.net/guangcaiwudong/article/details/107917700