比方说我们有一个页面路径为:/WEB-INF/templates/footer.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <div th:fragment="copy"> © 2011 The Good Thymes Virtual Grocery </div> </body> </html在其他页面中可以这样引用:
<body> ... <div th:insert="~{footer :: copy}"></div> </body>th:insert 将公共片段整个插入到引入的元素中 th:replace 将声明处替换为公共片段 th:include 将被引入的片段包含到这个标签中 引入方式
<div th:indeclude="~{footer :: copy}"></div>引入效果
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <div th:fragment="copy"> © 2011 The Good Thymes Virtual Grocery </div> </body> </html>实践
<h2><a class="btn btn-sm btn-success" href="emp" th:href="@{/emp}">员工添加</a></h2> <div class="table-responsive"> <table class="table table-striped table-sm"> <thead> <tr> <th>#</th> <th>lastName</th> <th>email</th> <th>gender</th> <th>department</th> <th>birth</th> <th>操作</th> </tr> </thead> <tbody> <tr th:each="emp:${emps}"> <td th:text="${emp.id}"></td> <td>[[${emp.lastName}]]</td> <td th:text="${emp.email}"></td> <td th:text="${emp.gender}==0?'女':'男'"></td> <td th:text="${emp.department.departmentName}"></td> <td th:text="${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></td> <td> <a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a> <button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">删除</button> </td> </tr> </tbody> </table>
员工Controller中添加方法
@GetMapping("/emp/toUpdate/{id}") public String toUpdatePage(@PathVariable(value="id",required =true)Integer id, Model model){ Employee employee = employeeDao.get(id); model.addAttribute("emp",employee); Collection<Department> departments = departmentDao.getDepartments(); model.addAttribute("departments",departments); return "emp/add"; } @PutMapping("/emp") public String updateEmp(Employee employee){ System.out.println("修改后的员工数据:" + employee); employeeDao.save(employee); return "redirect:/emps"; }当修改员工提交表单时,利用HttpHiddenMethodFilter发送Put请求:
<form th:action="@{/emp}" method="post"> <input type="hidden" name="_method" th:value="${emp!=null}?'put':'post'"/> <input type="hidden" name="id" th:if="${emp!=null}" th:value="${emp.id}">注意到SpringBoot2.3并没有自动注册HttpHiddenMethod过滤器
@Bean @ConditionalOnMissingBean(HiddenHttpMethodFilter.class) @ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false) public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() { return new OrderedHiddenHttpMethodFilter(); }需要我们手动在全局配置文件中开启
用th:attr为删除按钮添加自定义属性del_uri
<button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">删除</button>创建一个共享表单,用来提交删除请求
<form id="deleteEmpForm" method="post"> <input type="hidden" name="_method" value="delete"/> </form>绑定按钮的点击事件使之可以触发表单的提交
<script> $(".deleteBtn").click(function(){ //删除当前员工的 $("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit(); return false; }); </script>处理删除请求
@DeleteMapping("/emp/{id}") public String deleteEmp(@PathVariable("id") Integer id){ employeeDao.delete(id); return "redirect:/emps"; }