官方文档https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
thymeleaf是个模板引擎,在springboot中用来取代jsp实现前端页面的开发与后台的信息传送。

thymeleaf常用命名空间:

<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head></head>
<body></body>
</html>

只修改了前端页面,不需要重启tomcat,只需要ctrl+f9就行了

1、后台向thymeleaf前台传值

后台向前台传值,只要在处理请求的方法里声明Model,然后把从service层拿来的数据放到model里就行了,看下例:

 @RequestMapping("/employee")public String toForm(Model model){//我在自己做尝试的时候为了方便直接ctronller调dao了Collection<Employee> employees = employeeDao.getAllEmployees();//利用addAttribute()方法来放拿到的值,前台通过model.addAttribute("employees",employees)中的"employees"来拿到employeesmodel.addAttribute("employees",employees);return "form";}

利用model的addAttribute()方法来放拿到的值,前台通过model.addAttribute(“employees”,employees)中的"employees"来拿到employees这个集合。当然除了能传collection,传其他任何值都可以。

后台把数据放好,前台就可以来取了,thymeleaf取值用${},看下例,去除了之前放在model里的employees并遍历:

     <!--通过${employees}取后台放进model里的值--><tr th:each="employee:${employees}"><td th:text="${employee.getId()}"></td><td th:text="${employee.getLastName()}"></td><td th:text="${employee.getEmail()}"></td><td th:text="${employee.getGender()}==0?'女':'男'"></td><td th:text="${employee.getDepartment().getDepartmentName()}"></td><td th:text="${#dates.format(employee.getBirth(),'yyyy-MM-dd')}"></td><td><a class="btn btn-sm btn-primary" th:href="@{/updateEmployee/}+${employee.getId()}" >修改</a><a class="btn btn-sm btn-danger" th:href="@{/deleteEmployee/}+${employee.getId()}">删除</a></td></tr>

th可以接管标签的任何属性,th:each="employee:${employees}"是thymeleaf具有的表达式,意思是for(Employee employee : employees){},这会遍历出employees中的每个employee,然后给后面的td标签使用。td标签的text属性被thymeleaf接管,会显示从employee中取出的值。employee是个对象,所有可以调用对象的getter来得到想要的值。

2、thymeleaf向后台传值

thymeleaf向后台传值,在表单中,只要写上input标签的name属性,后台就可以根据这个name属性来拿到值了。例如下面的实现登录用户名与密码提交的例子:

 <form class="form-signin" th:action="@{/user/login}"><!--这个表单会提交/user/login请求--><h1 class="h3 mb-3 font-weight-normal">Please sign in</h1><!--加了name属性,后台就能根据name拿到值了--><input type="email" name="username" id="inputEmail" class="form-control" placeholder="Email address"><input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password"><button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button></form>

当点击提交按钮时,这个表单会提交/user/login请求,被对应的请求映射处理,同时form的内容也随请求被传给后台代码。

    @RequestMapping("/user/login")public String signInTest(@RequestParam("username")String username,//@RequestParam("")可以根据标签的name拿到前台的值@RequestParam("password")String password,Model model,HttpSession session){//拿到参数后就来写逻辑了,判断用户名密码是否正确等等,这里先简化了写//如果输入的用户名不为空且密码为123456则让他登录成功if(!StringUtils.isEmpty(username) && password.equals("123456")){//登陆成功,重定向到dashboard页session.setAttribute("logInUser",username);//登陆成功后设置session,方便拦截功能的实现return "redirect:/dashboard.html";//重定向到/dashboard.html} else {//登录失败,转发到sigininreturn "signin";}}

在参数列表中的参数前面写上@RequestParam(“username”)表示这个参数是对应前台传来的name属性为username的input标签的值。实际上,不写这个注解,将参数名定义为和name属性相同的名字也可以自动的匹配上值。

前台向后台传值还有更方便的用法,当表单可以对应一个对象时,直接将处理请求的方法的参数设置为一个对象,表单的值就会自动地与对象的属性一一对应,前提是表单中input标签的name属性的值与类中属性的变量名一摸一样。看下例:

         <h2>添加员工</h2><form th:action="@{/addEmployee}" method="post"><div class="form-group"><label>LastName</label><input type="text" class="form-control" name="lastName"></div><div class="form-group"><label>Email</label><input type="email" class="form-control" name="email"></div><div class="form-group"><label>Gender</label><br><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="1"><label class="form-check-label">男</label></div><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="0"><label class="form-check-label">女</label></div></div><div class="form-group"><label>department</label><select class="form-control" name="department"><option th:each="department:${departments}" th:text="${department.getDepartmentName()}" th:value="${department.getId()}"></option></select></div><div class="form-group"><label>Birth</label><input type="text" class="form-control" name="birth"></div><button type="submit" class="btn btn-primary">添加</button></form>

上面的表单实现了输入信息后添加一个员工,员工的实体类:

import java.util.Date;public class Employee {private Integer id;private String lastName;private String email;private Integer gender; //0:man,1:womanprivate Department department;private Date birth;//constructor&getter&setter
}

可以看出表单中input标签的name属性的值与类中属性的变量名是一一对应的,这样就能实现自动传值了。处理请求的代码如下:

    @PostMapping("/addEmployee")//addEmployee页提交表单,post请求public String addEmployee(Employee employee){//前台传来的参数自动地被封装成一个对象,前提是前台的那么属性要与对象中的属性名一致employeeDao.addAEmployee(employee);return "redirect:/employee";}

3、页面路由与html页面访问其他静态资源

thymeleaf中的@{}是用来放链接、地址的,页面路由和html页面访问css、js、image等其他静态资源都可以被thymeleaf托管。

页面路由
页面路由由后端代码来处理,前台只需要发送http请求,后端请求映射方法就会处理并实现页面路由(重定向、转发)。看下例:

<form class="form-signin" th:action="@{/user/login}"><!--这个表单会提交/user/login请求--><h1 class="h3 mb-3 font-weight-normal">Please sign in</h1><!--加了name属性,后台就能根据name拿到值了--><input type="email" name="username" id="inputEmail" class="form-control" placeholder="Email address"><input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password"><button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button></form>

上面的html片段是实现登录功能的页面,我们可以注意到form标签中的action属性被thymeleaf托管了,只要点击按钮,这个表单就会携带参数向发送 /user/login http请求,然后被后台对应的代码处理:

    @RequestMapping("/user/login")public String signInTest(@RequestParam("username")String username,//@RequestParam("")可以根据标签的name拿到前台的值@RequestParam("password")String password,Model model,HttpSession session){//拿到参数后就来写逻辑了,判断用户名密码是否正确等等,这里先简化了写//如果输入的用户名不为空且密码为123456则让他登录成功if(!StringUtils.isEmpty(username) && password.equals("123456")){//登陆成功,重定向到dashboard页session.setAttribute("logInUser",username);//登陆成功后设置session,方便拦截功能的实现return "redirect:/dashboard.html";//重定向到/dashboard.html} else {//登录失败,转发到sigininreturn "signin";}}

从上面的java代码可见页面路由是后端处理的。页面跳转有重定向和转发两种,重定向是 return “redirect:/xxxxl”; 转发是 return “xxxx”; 二者有着较大的区别(这里在springmvc中就应该搞清楚)。

html页面访问其他静态资源
在html中通常会导入其他静态资源,这些静态资源可以一股脑的放在static目录下然后再html中直接取,但在转发时会造成访问不到的问题。也可以托管给thymeleaf,然后再访问,为了整理方便,我再static目录下新建了/css、/js、/img三个文件夹用来存放不同的静态资源。

<link th:href="@{/css/bootstraps.min.css}" rel="stylesheet">

上例中,/代表当前项目目录,css放在static目录下,正常来说应该是/static/css,但static不用写,所以直接用/css/**来访问这个css目录下的css文件了。同理访问js与图片:

<script th:src="@{/js/feather.min.js}"></script>
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" width="72" height="72">

要注意的是,再设置拦截器的时候要注意放行这些静态资源的地址。

4、restful风格

restful风格可以使得路径变得更加的简洁,也可以通过不同的请求方式映射到同一路径的不同处理方法上。
例如,下面的代码,不使用restful风格:

 @RequestMapping("/add")@ResponseBodypublic String toAdd(int a,int b){int c = a + b;return "c";}

请求的路径可能为下,路径上会显示出传的参数:
localhost:8080/add?a=1&b=2
这样不太好看,且会暴露后台代码(变量名暴露出来了)

使用restful风格如下(看注释)

 @RequestMapping("/add/{a}/{b}")//{a}这样来传参@ResponseBodypublic String toAddRestful(@PathVariable int a,@PathVariable int b){      //在参数列表中使用@PathVariable声明参数int c = a + b;return "c";}

请求路径就可以变为下面了:
localhost:8080/add/1/2
变得优雅许多

使用restful风格,同一请求路径可以映射到不同的处理方法上,通过请求方式的不同来实现。
比如下面的例子:

 @GetMapping("/add")@ResponseBodypublic String toAddRestful(){      return "c";}@PostMapping("/add")@ResponseBodypublic String toAddRestful(){      return "d";}

========================================

<a th:href="@{/add}" method="get"></a>

上面的a标签会映射到getmapping

========================================

<a th:href="@{/add}" method="post"></a>

上面的a标签会映射到postmapping

resultful风格实际使用:

<a class="btn btn-sm btn-primary" th:href="@{/updateEmployee/}+${employee.getId()}" >修改</a>

这里href属性直接通过拼接实现restful传参,${employee.getId()}是得到当前employee对象的id。处理的后台代码:

 @GetMapping("/updateEmployee/{id}")//restful风格public String toUpdatePage(@PathVariable("id")Integer id,Model model){Employee employee = employeeDao.selectAEmployeeById(id);model.addAttribute("employee",employee);Collection<Department> departments = departmentDao.getDepartments();model.addAttribute("departments",departments);return "updateEmployee";}

thymeleaf笔记相关推荐

  1. thymeleaf笔记(一)使用thymeleaf实现对数组的遍历并展示

    使用thymeleaf实现对数组的遍历并展示 1.简介 ​ thymeleaf是一个在springboot框架中使用的模板引擎,用于替代jsp页面而发展出来的,因为有人觉得jsp页面比较落后,因此部分 ...

  2. 【谷粒商城】框架扩充篇(3/4)

    gitee个人代码:https://gitee.com/HanFerm/gulimall 笔记-基础篇-1(P1-P28):https://blog.csdn.net/hancoder/article ...

  3. SpringBoot学习笔记(4)----SpringBoot中freemarker、thymeleaf的使用

    1. freemarker引擎的使用 如果你使用的是idea或者eclipse中安装了sts插件,那么在新建项目时就可以直接指定试图模板 如图: 勾选freeMarker,此时springboot项目 ...

  4. springboot thymeleaf配置_【程序源代码】Spring Boot 开发笔记web开发实战1

    关键字:<Spring Boot 开发笔记>系列文章 各位亲爱的小伙伴:大家好! <Spring Boot 开发笔记>系列文章 这套笔记和源码是我自己在学习springboot ...

  5. 【Springboot学习笔记】SpringBoot+Mybatis+Thymeleaf+Layui数据表单从零开始实现按条件模糊分页查询的方法

    [Springboot学习笔记]SpringBoot+Mybatis+Thymeleaf+Layui数据表单从零开始实现按条件模糊分页查询的方法 目录 1.搭建环境 1.1直接从网上下载SpringB ...

  6. SpringBoot学习笔记【part12】Web开发——Thymeleaf模板引擎

    SpringBoot 学习笔记 Part12 1. thymeleaf简介 SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染. Thymeleaf is a modern ...

  7. 【学习笔记】 Thymeleaf的前端渲染(价值50)

    [学习笔记] Thymeleaf的前端渲染(价值50)

  8. Thymeleaf 学习笔记 (5)

    2019独角兽企业重金招聘Python工程师标准>>> 类似于 EL 表达式的行内变量在 js 文件中的使用 Thymeleaf 在 js中,可以动态的替换变量的值,支持将一个对象转 ...

  9. thymeleaf 学习笔记

    thymeleaf,我个人认为是个比较好的模板,性能也比一般的,比如freemaker的要高,而且把将美工和程序员能够结合起来,美工能够在浏览器中查看静态效果,程序员可以在应用服务器查看带数据的效果. ...

最新文章

  1. Ubuntu下eclipse部署mysql jdbc驱动
  2. 以交互方式安装ESXi 6.0
  3. python 网盘上传_python学习笔记 day32 实现网盘上传下载功能
  4. 电脑断网分析(故障排查手册)- 自救篇
  5. (转) Hibernate注解开发
  6. Js显示Struts2中的内容之escape和escapeHtml
  7. 课程设计matlab仿真,MATLAB与仿真系统课程设计报告
  8. html制作古诗念奴娇,《念奴娇·赤壁怀古》_苏轼的诗词_诗词名句网
  9. 梦幻西游战斗中服务器维护,梦幻西游10月22日维护公告 连续战斗自动问题修复...
  10. 【Nature | EpiMap】Regulatory genomic circuitry of human disease loci by integrative epigenomics
  11. 辐射避难所买了东西显示服务器异常,辐射避难所有哪些BUG 现存BUG说明及解决方法盘点...
  12. PHP——后端跨平台脚本语言
  13. 【深度学习】一文读懂机器学习常用损失函数(Loss Function)
  14. n个元素进栈,共有多少种出栈顺序?
  15. 精通 CSS+DIV 网页样式与布局 62
  16. 关闭Hyper-v虚拟服务
  17. 扫一扫功能在手机便签的哪里
  18. 汽车油门踏板传感器信号测量-汽修示波器
  19. Qorvo 扩展 750V SiC FET 范围
  20. AS3代码播放GIF动画

热门文章

  1. 转载,汉语世界上最先进的语言(来自几年前的转发,如今重新转发)
  2. Linux创建文件的几种方式
  3. 机械硬盘哪个好?买1T好还是2T好?
  4. 群晖文件服务器ds918,群晖ds918+评测 安全而又强大
  5. Google.com.hk 更名 Google 中国,谷歌已经不复存在?
  6. android蓝牙温湿度,基于蓝牙的温湿度采集系统设计
  7. 龙场悟道,王阳明悟到了什么?
  8. 一张图看明白电信云解决方案架构
  9. 用opacity方法来隐藏元素后,照样可以触发绑定在其身上的点击事件
  10. 来,吃了许嵩这颗毒药