当前位置:   article > 正文

SpringBoot--Thymeleaf

springboot tyhmeleaf style

Thymeleaf也是一款模板引擎,但它不依赖标签库,是SpringBoot官方推荐的模板引擎,使用也比较广泛

一、项目配置

1. 导入依赖
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  4. <version>2.4.5</version>
  5. </dependency>
2. 新建html

在templates目录下新建html:

内容为:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. hello thymeleaf
  9. </body>
  10. </html>
3. Controller中新建接口

FreeMarker一样,Thymeleaf不支持直接访问

  1. @Controller
  2. public class MyController {
  3. @RequestMapping("hello")
  4. public String hello() {
  5. return "hello";
  6. }
  7. }

浏览器访问:

二、标准变量表达式

标准变量表达式就是Thpmeleaf完成数据的展示和处理的方式,必须在标签中使用,使用th命名空间,语法为:<tag th:xx="${key}"></tag>

新建test.html:

1. th:text

对应text属性,从Controller层返回一个数据:

  1. @RequestMapping("test")
  2. public String test(Model model) {
  3. model.addAttribute("msg","controller msg");
  4. return "test";
  5. }

html修改为:

  1. <!doctype html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. </head>
  6. <body>
  7. <span th:text="123"></span>
  8. </body>
  9. </html>

访问结果:

2. th:value

对应input的value属性

<input th:value="${msg}">
3. th:if

可以进行if判断来是否显示该标签

<p th:if="${name}!='张三'">hello</p>
4. th:each

用于遍历list集合,语法为:th:each="obj,index:${listName}"

  • index : 索引对象,包含索引、数据量大小、序号等
  • obj:遍历到的单个对象
  • listName:controller层传递的集合参数名

内部标签就可以使用上面对象

使用之前SpringBoot--配置MyBatis、Logback、PagerHelper、Druid中的员工集合代码,将员工显示到页面上

controller层代码和之前一样:

  1. @RequestMapping("showEmpList")
  2. public ModelAndView showEmpList(ModelAndView modelAndView) {
  3. List<Emp> allEmpList = empService.findAllEmp();
  4. modelAndView.setViewName("showEmpList");
  5. Map<String, Object> model = modelAndView.getModel();
  6. model.put("empList", allEmpList);
  7. return modelAndView;
  8. }

html代码:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <style>
  6. #empTable {
  7. margin: 0 auto;
  8. border: 1px solid antiquewhite;
  9. width: 80%;
  10. }
  11. #empTable th, td {
  12. border: 1px solid bisque;
  13. text-align: center;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <table id="empTable" cellpadding="0px" cellspacing="0px">
  19. <tr>
  20. <th>索引</th>
  21. <th>员工编号</th>
  22. <th>姓名</th>
  23. <th>职位</th>
  24. <th>上级</th>
  25. <th>薪水</th>
  26. <th>奖金</th>
  27. <th>部门编号</th>
  28. </tr>
  29. <tr th:each="emp,i:${empList}">
  30. <td th:text="${i.index}"></td>
  31. <td th:text="${emp.empno}"></td>
  32. <td th:text="${emp.ename}"></td>
  33. <td th:text="${emp.job}"></td>
  34. <td th:text="${emp.mgr}"></td>
  35. <td th:text="${emp.sal}"></td>
  36. <td th:text="${emp.comm}"></td>
  37. <td th:text="${emp.deptno}"></td>
  38. </tr>
  39. </table>
  40. </body>
  41. </html>

效果:

5. 运算符
5.1 基本运算符

标准表达式中支持基本的运算符:+、-、*、/、%

<td th:text="${i.index + 1}"></td>
5.2 关系运算符

关系运算符还是推荐使用转义:

符号转义后
>gt
>=ge
<lt
<=le
==eq
!=ne
5.3 逻辑运算符
  • 并且:&&、and
  • 或者: ||、or
5.4 三目运算符

和java相同的写法:[expression]?value1:value2

5.5 动态修改style属性

结合上面的运算符,动态修改style属性:

<td th:text="${emp.sal}" th:style="${emp.sal} ne null and ${emp.sal} gt 2000? 'color:red':''"></td>

效果:

6. th:href

用于设置a标签的href属性,语法:th:href="@{function(param1=${},param2=${}, ..)}"

实现删除员工的功能

定义Mapper:

  1. @Mapper
  2. public interface EmpMapper {
  3. ...
  4. int deleteEmp(Integer empno, String ename);
  5. }

映射文件:

  1. <!--int deleteEmp(Integer empno, String ename);-->
  2. <delete id="deleteEmp">
  3. delete from emp where empno = #{empno} and ename = #{ename}
  4. </delete>

service对应的进行编写,这边就不贴出代码了,controller新增处理单元:

  1. @RequestMapping("deleteEmpByNoAndName")
  2. public String deleteEmpByNoAndName(Integer empno, String ename) {
  3. boolean success = empService.deleteEmpByNoAndName(empno, ename);
  4. return "redirect:/showEmpList";
  5. }

html中使用:

<a th:href="@{deleteEmpByNoAndName(empno=${emp.empno},ename=${emp.ename})}">删除</a>

效果:

7. th:onclick

绑定点击事件,语法:th:οnclick="function( [[param1]], [[param2]], ..)"

实现点击删除后有一个提示

html:

  1. <a href="javascript:void(0)" th:onclick="removeEmpByNoAndName([[${emp.empno}]],[[${emp.ename}]])">删除</a>
  2. <script>
  3. function removeEmpByNoAndName(empno, ename) {
  4. var ret = confirm("确定删除员工编号为:" + empno + "的" + ename)
  5. if (ret) {
  6. window.location.href = "deleteEmpByNoAndName?empno=" + empno + "&ename=" + ename
  7. }
  8. }
  9. </script>

效果:

三、内置对象

Thymeleaf也内置了一些工具类:

作用:
#arrays:数组操作的工具;
#aggregates:操作数组或集合的工具;
#bools:判断boolean类型的工具;
#calendars:类似于#dates,但是是java.util.Calendar类的方法;
#ctx:上下文对象,可以从中获取所有的thymeleaf内置对象;
#dates:日期格式化内置对象,具体方法可以参照java.util.Date;
#numbers: 数字格式化;#strings:字符串格式化,具体方法可以参照String,如startsWith、contains等;
#objects:参照java.lang.Object;
#lists:列表操作的工具,参照java.util.List;
#sets:Set操作工具,参照java.util.Set;#maps:Map操作工具,参照java.util.Map;
#messages:操作消息的工具。

1. string对象
方法名描述
#string.isEmpty(key)判断字符串是否为空,为空返回true,反之false
#string.contains(msg,'T')判断字符串是否包含T的子串,包含返回true,反之false
#string.startsWith(msg,'a')判断字符串是否以a子串为开始,为开始返回true,反之false
#string.endsWith(msg,'a')判断字符串是否以a子串为结束,为结束返回true,反之false
#string.length(msg)返回字符串大小
#string.indexOf(msg,'a')查找字符串中包含a子串的第一个下标,包含返回下标,反之-1
2. dates对象
方法名描述
#dates.format(key)格式化日期,默认以浏览器语言为标准
#dates.format(key,'yyyy-MM-dd')自定义格式化日期
#dates.year(key)获取年
#dates.month(key)获取月
#dates.day(key)获取日

html中显示员工入职日期:

<td th:text="${!#strings.isEmpty(emp)?#dates.format(emp.hiredate,'yyyy-MM-dd'):''}"></td>
3. 域对象

controller中新增:

  1. @RequestMapping("showEmpList")
  2. public ModelAndView showEmpList(ModelAndView modelAndView, HttpServletRequest req, HttpSession session) {
  3. List<Emp> allEmpList = empService.findAllEmp();
  4. modelAndView.setViewName("showEmpList");
  5. Map<String, Object> model = modelAndView.getModel();
  6. model.put("empList", allEmpList);
  7. // 向request域放数据
  8. req.setAttribute("msg", "requestMessage");
  9. // 向session域放数据
  10. session.setAttribute("msg", "sessionMessage");
  11. // 向application域放数据
  12. req.getServletContext().setAttribute("msg", "applicationMessage");
  13. return modelAndView;
  14. }

html中获取传递的域数据:

  1. httpServletRequest:
  2. <span th:text="${#httpServletRequest.getAttribute('msg')}"></span>
  3. <span th:text="${#request.getAttribute('msg')}"></span>
  4. <hr/>
  5. httpSession:
  6. <span th:text="${#httpSession.getAttribute('msg')}"></span>
  7. <span th:text="${#session.getAttribute('msg')}"></span>
  8. <span th:text="${session.msg}"></span>
  9. <hr/>
  10. servletContext:
  11. <span th:text="${#servletContext.getAttribute('msg')}"></span>
  12. <span th:text="${application.msg}"></span>
  13. <hr/>

效果:

4. 其他对象

可以从官网查看:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects

项目地址:

https://gitee.com/aruba/spring-boot-study.git

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/204900
推荐阅读
相关标签
  

闽ICP备14008679号