Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 页面
创建测试 Controller ,如下:
@Controller public class HelloController { @GetMapping("/hello") public String hello(HttpServletRequest request) { // 构建测试数据 Map<String, Object> map = new HashMap<>(); UserModel userModel = new UserModel(); userModel.setId(1L); userModel.setName("Spring Boot"); userModel.setAge(18); map.put("user", userModel); List<CourseModel> list = new ArrayList<>(); for (int i = 0; i < 2; i++) { CourseModel courseMode = new CourseModel(); courseMode.setId((long) i); courseMode.setName("Spring Boot:" + i); courseMode.setAddress("课程地点:" + i); list.add(courseMode); } map.put("list", list); map.put("flag", true); request.setAttribute("data", map); return "hello"; } }
在此注册测试类中,进行数据初始化并输出至页面。
- Thymeleaf 默认的模板路径
src/main/resources/templates
,只需要在这个这个路径下编写模版文件即可。
Thymeleaf 模版文件如下:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Hello Spring Boot</title> <link rel="stylesheet" th:href="@{/static/css/bootstrap.min.css}"> </head> <body> <div class="container"> <div>用户信息:</div> <table class="table table-dark"> <thead> <tr> <th scope="col">#</th> <th scope="col">姓名</th> <th scope="col">年龄</th> </tr> </thead>