springBoot集成thymeleaf
thymeleaf引擎类似于jsp,freemark,velocity等等,关于他的详细使用见官网语法
1.依赖配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.application.properties配置Thymeleaf属性
#thymelea模板配置
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=/**
这里的配置不是必须的,如果配置了会覆盖默认的
3.controller配置
@RequestMapping("/thymeleaf")
@Controller
public class ThtmeleafController {
private final static Log log = LogFactory.getLog(FreemarkerController.class);
@Autowired
private UserService userService;
@RequestMapping("/{id}")
public String getUser(@PathVariable String id, Model model){
log.info("*********查询用户页面开始**********");
Users user = userService.getUserById(id);
model.addAttribute("user",user);
log.info("*********查询用户页面结束**********");
return "user";
}
}
4.user.html文件配置
- 文件目录:
resources/templates/user.html
- html标签:
可以不引入 xmlns:th="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<title>thymeleaf测试</title>
<meta charset=UTF-8>
<meta http-equiv="x-ua-compatible" content="IE=edge">
<link rel="stylesheet" th:href="@{/bootstrap-3.3.7/dist/css/bootstrap.css}">
</head>
<body>
<div class="container">
<h3 th:text="${user.name}"></h3>
<p><button class="btn btn-default">测试</button></p>
<div class="row">
<div class="col-md-12">
<table>
<tr>
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.password}"></td>
</tr>
</table>
</div>
</div>
</div>
</body>
<script type="text/javascript" th:src="@{/jquery-3.3.1/jquery-3.3.1.js}"></script>
<script type="text/javascript" th:src="@{/bootstrap-3.3.7/dist/js/bootstrap.js}"></script>
</html>