05_thymeleaf入门案例
张创琦 2022.03.12
- 编写service
UserService.java
package com.lxs.service;import com.lxs.dao.UserDao;import com.lxs.dao.UserMapper;import com.lxs.domain.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class UserService {@Autowiredprivate UserMapper userMapper;public List<User> findAll() {return userMapper.selectAll();}}
- 编写Controller
UserController.java
package com.lxs.controller;import com.lxs.domain.User;import com.lxs.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import java.util.List;@Controllerpublic class UserController {@Autowiredprivate UserService userService;@RequestMapping("/all")public String all(Model model) {List<User> list = userService.findAll();model.addAttribute("users", list);// 默认跳转路径是: classpath:/templates/users.htmlreturn "users";}}
- pom.xml 中引入启动器
<!-- thymeleaf 相关依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
- 静态页面的搭建
resources/templates/users.html
注意第二行 html 的引入链接
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>用户</title><style type="text/css">table {border-collapse: collapse; font-size: 14px; width: 80%; margin: auto}table, th, td {border: 1px solid darkslategray; padding: 10px}</style></head><body><div style="text-align: center"><span style="color: darkslategray; font-size: 30px">欢迎光临!</span><hr/><table class="list"><tr><th>id</th><th>姓名</th><th>用户名</th><th>年龄</th><th>性别</th><th>生日</th><th>备注</th><th>操作</th></tr><tr th:each="user : ${users}" th:object="${user}"><td th:text="${user.id}">1</td><td th:text="*{name}">张三</td><td th:text="*{userName}">zhangsan</td><td th:text="${user.age}">20</td><td th:text="${user.sex} == 1 ? '男': '女'">男</td><td th:text="${#dates.format(user.birthday, 'yyyy-MM-dd')}">1980-02-30</td><td th:text="${user.note}">1</td><td><a th:href="@{/delete(id=${user.id}, userName=*{userName})}">删除</a><a th:href="|/update/${user.id}|">修改</a><a th:href="'/approve/' + ${user.id}">审核</a></td></tr></table></div></body></html>
# 开发阶段关闭thymeleaf的模板缓存spring.thymeleaf.cache=false
在 Idea 中,我们需要在修改页面后按快捷键 Ctrl + Shift + F9 对项目进行 rebuild 才可以。
