1.前言
- 静态html嵌入标签属性,浏览器可以直接打开模板文件,便于前后端联调。
- springboot官方推荐方案。
2. 实现
2.1 添加依赖
在你搭建的Web
项目中,添加starter-thymeleaf
依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.2 添加yml
配置
在你的application.yml
中再添加freemarker
的配置。
spring:
thymeleaf:
mode: HTML
encoding: UTF-8
servlet:
content-type: text/html
cache: false
2.3 Controller
IndexController
定义首页入口,若没登录会自动跳转到登录页面。
@Controller
@Slf4j
public class IndexController {
@GetMapping(value = {"", "/"})
public ModelAndView index(HttpServletRequest request) {
ModelAndView mv = new ModelAndView();
User user = (User) request.getSession().getAttribute("user");
if (ObjectUtil.isNull(user)) {
mv.setViewName("redirect:/user/login");
} else {
mv.setViewName("page/index");
mv.addObject(user);
}
return mv;
}
}
UserController
提供登录页面和登录后跳转到首页。
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
@PostMapping("/login")
public ModelAndView login(User user, HttpServletRequest request) {
ModelAndView mv = new ModelAndView();
mv.addObject(user);
mv.setViewName("redirect:/");
request.getSession().setAttribute("user", user);
return mv;
}
@GetMapping("/login")
public ModelAndView login() {
return new ModelAndView("page/login");
}
}
2.4 模板
src\main\resources\templates\common\head.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="header">
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>spring-boot-demo-template-thymeleaf</title>
</head>
<body>
</body>
</html>
src\main\resources\templates\page\index.html
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<header th:replace="~{common/head :: header}"></header>
<body>
<div id="app" style="margin: 20px 20%">
欢迎登录,<span th:text="${user.name}"></span>!
</div>
</body>
</html>
src\main\resources\templates\page\login.html
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<header th:replace="~{common/head :: header}"></header>
<body>
<div id="app" style="margin: 20px 20%">
<form action="/demo/user/login" method="post">
用户名<input type="text" name="name" placeholder="用户名"/>
密码<input type="password" name="password" placeholder="密码"/>
<input type="submit" value="登录">
</form>
</div>
</body>
</html>