网站建设 大公司小公司/网络推广软件免费
Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎,在C#、PHP语言体系下也有模板引擎,甚至在 Javascript中也会用到模板引擎技术,Java生态下的模板引擎有 Thymeleaf、 Freemaker、Ⅴ elocity、 Beetl(国产)等。
Thymeleaf对网络环境不存在严格的要求,既能用于web环境下,也能用于非web环境下。在非web环境下,他能直接显示模板上的静态数据;在web环境下,它能像Jsp一样从后台接收数据并替换掉模板上的静态数据。它是基于HTML的,以HIML标签为载体,Thymeleaf要寄托在HTML标签下实现。
Spring Boot集成了 Thymeleaf模板技术,并且 Spring boot官方也推荐使用 Thymeleaf来替代JSP技术, Thymeleaf是另外的一种模板技术,它本身并不属于 Spring Boot, Spring Boot只是很好地集成这种模板技术,作为前端页面的数据展示,在过去的 Java Web开发中,我们往往会选择使用Jsp去完成页面的动态渲染,但是jsp需要翻译编译运行,效率低
官网https://www.thymeleaf.org/
SpringBoot框架集成Thymealeaf,Thymealeaf代替jsp。
IDEA设置默认模板
SpringBoot简单实用Thymealeaf
@Controllerpublic class ControllerA {@RequestMapping("/hello")public String A(HttpServletRequest request){request.setAttribute("data","Thymeleaf hello world");//指定视图//逻辑名称return "A";}}
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Title</title></head><body>Thymeleaf显示数据:<p th:text="${data}"></p></body></html>
Thymeleaf模板之常用设置
application.properties配置
#开发阶段,关闭模板缓存,立即生效spring.thymeleaf.cache=false
#编码格式spring.thymeleaf.encoding=utf-8
#模型的类型(默认html)spring.thymeleaf.mode=HTML
#模板前缀、模板引擎存放路径 默认classpath:/templates/spring.thymeleaf.prefix=classpath:/templates/#模板后缀 默认.htmlspring.thymeleaf.suffix=.html
Thymeleaf模板之标准变量表达式
表达式是在页面获取数据的一种Thymeleaf语法。列:${ key}
注意:th:text=””是Thymeleaf的一个属性,用于显示文本信息。
标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和EL中的${}相同。Thymeleaf中的变量表达式使用${变量名}的方式获取Controller中model其中的数据(request作用域中的数据)。
标准变量表达式语法:${key},作用:获取key对于的文本数据,key是request作用域中的key,使用request.setAttribute(),model.addAttribute()
在html页面中获取数据th:text=”${key}”
@Controller@RequestMapping("/t")public class ControllerB {@RequestMapping("/hello2")public String B(Model model){model.addAttribute("Student",new Student(1,"小红","女"));System.out.println("ControllerB");return "abc";}}
<body>
student:<p th:text="${Student.id}"></p>
<p th:text="${Student.name}"></p>
<p th:text="${Student.sex}"></p>
</body>
Thymeleaf模板之选择变量表达式
语法格式:*{key} 作用:获取key对应的数据库,*{key}需要和th:object这个属性一起使用。
@RequestMapping("/hello3")public String C(Model model){model.addAttribute("Student",new Student(1,"小明","男"));System.out.println("ControllerC");return "C";}
<div th:object="${Student}"><p th:text="*{id}"></p><p th:text="*{name}"></p><p th:text="*{sex}"></p>
</div>
<p th:text="*{Student.name}"></p>
Thymeleaf模板之链接表达式
语法:@{url} 作用:表示链接
列如:<link href="..."><a href="..."></a><script src="..."></script><form action="..."></form><img src="...">
//链接表达式@GetMapping("/link")public String link(Model model){model.addAttribute("userId",101);return "link";}
@GetMapping("/link2")@ResponseBodypublic String link2(int id){return "id:"+id;}
@GetMapping("/link3")@ResponseBodypublic String link3(int id ,String name){return "id+name:"+id+name;}
<p>链接表达式</p>绝对地址<br><a th:href="@{http://www.baidu.com}">百度链接</a>
相对地址<br><a th:href="@{/t/link}"></a>相对地址,传递参数<br><a th:href="@{'/t/link2?id='+${userId}}">获取model数据,传递一个参数</a><a th:href="@{/t/link3(id=${userId},name='张三')}">传递多个参数</a>
Thymeleaf模板之属性使用
属性是放在html元素中的,就是html元素的属性,加上th,属性的值由模板引擎处理。
属性:th:action th:method th:href th:src th:text th:style th:each
th:action
定义后台控制器的路径,类似<form>标准的action属性 th:action="@{/t/login}"
th:method
定义get,post方法 th:method="${method}"
th:href
定义超链接,结合URL表达式,获取动态变量
<a th:href="@{http://www.baidu.com}">百度链接</a>
th:src
用于引入外部资源,类似<script>标签
<script src="@{/js/jquery-3.6.1.js}" type="text/javascript"></script>
th:text
设置显示文本 ${key}
//Thymeleaf属性的使用@GetMapping ("/property01")
public String property(Model model){model.addAttribute("id","12345");model.addAttribute("method","post");model.addAttribute("password","123455");model.addAttribute("color","color:#f76730");return "pro";
}
@PostMapping("/login")
@ResponseBody
public String login(int id,String password){return "账户id:"+id+"账户密码:"+password;
}
<body>
<p>属性的使用</p><div style="margin-left:400px"><form th:action="@{/t/login}" th:method="${method}"><input th:type="text" th:name="id" th:value="${id}"><input th:type="password" th:name="password" th:value="${password}"><input th:type="submit" th:value="submit"></form></div>
<p th:style="${color}">hello world</p>
<p th:style="'color:#f76730'">hello world</p>
<p th:style="'color:red'">hello world</p>
</body>
Thymeleaf模板之循环
th:each这个属性非常常用,与JSTL中的<c:forEach>类似.可以循环遍历集合,也可以循环变量数组和map
循环List
<div th:each="集合成员,循环的状态变量:${key}"><p th:text="${集合成员}"></p>
</div>
循环的状态变量
Index: 当前迭代对象的下标(0-n)
Count:当前迭代对象个数(0-n)
Size:被迭代对象的大小
Current:当前迭代变量
even/odd :布尔值,当前循环是否为偶数/奇数
first:是否第一个
last:是否最后一个
Controller
// 循环list@GetMapping("/eachList")public String eachList(Model model){List<String> strList = new ArrayList<>();strList.add("张三");strList.add("李四");strList.add("保国");model.addAttribute("strList",strList);List<Student> students = new ArrayList<>();students.add(new Student(10,"张三","男"));students.add(new Student(11,"李四","男"));students.add(new Student(12,"保国","男"));model.addAttribute("students",students);return "E";}
Html页面
<div th:each="集合成员,循环的状态变量:${key}"><p th:text="${集合成员}"></p>
</div>
<div th:each="list,strstate:${strList}"><p th:text="${list}"></p>
</div><div th:each="student,studentState:${students}"><p th:text="${student.id}"></p><p th:text="${student.name}"></p><p th:text="${student.sex}"></p>
</div><div><table border="1" cellpadding="0" cellspacing="0"><thead><tr><td>下标</td><td>id</td><td>name</td><td>sex</td></tr></thead><tbody><tr th:each="student,studentState:${students}"><td th:text="${studentState.index}"></td><td th:text="${student.id}"></td><td th:text="${student.name}"></td><td th:text="${student.sex}"></td></tr></tbody></table>
</div>
循环数组Array
controller
//循环数组@GetMapping("/eachArray")public String array(Model model){String[] name =new String[3];name[0]="张三2";name[1]="李四2";name[2]="保国2";model.addAttribute("names",name);return "array";
}
Html页面
循环Array<div><table border="1" cellpadding="0" cellspacing="0"><thead><tr><td>编号</td><td>name</td></tr></thead><tbody><tr th:each="name,nameState:${names}"><td th:text="${nameState.count}"></td><td th:text="${name}"></td></tr></tbody></table>
</div>
循环Map
Controller
//循环map@GetMapping("/eachMap")public String eachMap(Model model){Map<String,Student> map =new HashMap<>();map.put("stu1",new Student(11,"保国1","男"));map.put("stu2",new Student(12,"保国2","男"));map.put("stu3",new Student(13,"保国3","男"));map.put("stu4",new Student(14,"菜坤","男"));model.addAttribute("stuMap",map);return "Map";}
Html页面
循环Map<div><table border="1" cellpadding="0" cellspacing="0"><thead><tr><td>编号</td><td>key</td><td>id</td><td>name</td><td>sex</td></tr></thead><tbody><tr th:each="stu,stuState:${stuMap}"><td th:text="${stuState.count}"></td><td th:text="${stu.key}"></td><td th:text="${stu.value.id}"></td><td th:text="${stu.value.name}"></td><td th:text="${stu.value.sex}"></td></tr></tbody></table>
</div>
循环List<Map<key,value>>
@GetMapping("/eachListMap")
public String eachListMap(Model model){List<Map<String,Student>> listMap =new ArrayList<>();Map<String,Student> map1 =new HashMap<>();map1.put("stu1",new Student(11,"保国11","男"));map1.put("stu2",new Student(12,"保国12","男"));map1.put("stu3",new Student(13,"保国13","男"));map1.put("stu4",new Student(14,"菜坤1","男"));Map<String,Student> map2 =new HashMap<>();map2.put("stu12",new Student(11,"保国112","男"));map2.put("stu22",new Student(12,"保国122","男"));map2.put("stu32",new Student(13,"保国132","男"));map2.put("stu42",new Student(14,"菜坤12","男"));listMap.add(map1);listMap.add(map2);model.addAttribute("ListMap",listMap);model.addAttribute("listMap",listMap);return "Map";
}
循环List-Map<div><table border="1" cellpadding="0" cellspacing="0"><thead><tr><td>编号</td><td>key</td><td>id</td><td>name</td><td>sex</td></tr></thead><tbody><div th:each="list:${ListMap}"><tr th:each="map,mapState:${list}"><td th:text="${mapState.count}"></td><td th:text="${map.key}"></td><td th:text="${map.value.id}"></td><td th:text="${map.value.name}"></td><td th:text="${map.value.sex}"></td></tr></div></tbody></table>
</div>
Thymeleaf模板之if和unless
语法:th:if”boolean条件”,条件为true显示体内容
Th:unless是th:if的一个相反操作
<div th:if="true">显示内容</div>
<div th:unless="true">显示内容</div>
用例
controller
@GetMapping("/ifl")public String ifanUnless(Model model){model.addAttribute("name","z");model.addAttribute("login","true");model.addAttribute("age",30);model.addAttribute("empty1","");model.addAttribute("fnull",null);return "IfUnless";}
html
<body>
<div th:if="${name=='z'}">张三</div>
<div th:if="${login}">登入成功</div>
<div th:if="${age < 40}">年龄小于40</div>
<!--""空字符是true-->
<div th:if="${empty1}">true</div>
<!--null为false-->
<div th:unless="${fnull}">为null</div>
</body>
Thymeleaf模板之switch-case
@GetMapping("/switch")
public String switchCase(Model model){model.addAttribute("sex",'m');return "switch";}
switch的使用
<div th:switch="${sex}"><p th:case="m">男</p><p th:case="f">女</p><p th:case="*">未知</p>
</div>
Thymeleaf模板之内联text
@GetMapping("/inline")
public String inlineDemo(Model model){model.addAttribute("name","z");model.addAttribute("age",30);model.addAttribute("sex","m");model.addAttribute("stu",new Student(14,"菜坤","男"));
return "inline";
}
<div th:inline="text"><!--/*[[${name}]]会转义,[(${name})]不会转义*/--><p>名字[[${name}]]</p><p>年龄[(${age})]</p><p>[['I love yue']]</p><p>[[${stu.id}]],[[${stu.name}]],[[${stu.sex}]]</p>
</div>
Thymeleaf模板之内联javascript
<script type="text/javascript" th:inline="javascript">var name = [[${name}]];
var age = [[${age}]];alert("获得模板中的数据:"+name+" "+age)
function fun(){alert("获得模板中的数据:"+name+" "+age)}
</script>
Thymeleaf模板之字面值
文本字面量
<p th:text="'名字'+${name}"></p>
数字字面量
<div th:if="${age < 40}">年龄小于40</div>
Bollean字面量
<div th:if="${login}">登入成功</div>
Null字面量
<p th:if="${name != null}">name不为null</p>
<!--""空字符是true-->
<div th:if="${empty1}">true</div>
<!--null为false-->
<div th:unless="${fnull}">为null</div>
Thymeleaf模板之字符串连接
方式1
<p th:text="'名字'+${name}+'年龄'+${age}"></p>
方式2
<p th:text="|名 字+${name}+年 龄+${age}|"></p>
Thymeleaf模板之运算符
算术运算符:+,-,*,/,%
关系比较:>,<,>=,<= (gt,lt,ge,le)
相等判断:==,!= (eq,ne)
@GetMapping("/inline")public String inlineDemo(Model model){model.addAttribute("name","z");model.addAttribute("age",30);model.addAttribute("sex","m");model.addAttribute("stu",new Student(14,"菜坤","男"));model.addAttribute("fnull",null);model.addAttribute("login",true);return "inline";
}
运算符的使用<div><p th:text="${age > 10}">年龄大于10</p><p th:text="${20 + 30}">结果</p><p th:if="${fnull == null}">为null</p>三元运算符:<p th:text="${login == true ? '登入成功' : '登入失败'}"></p>
</div>
Thymeleaf模板之内置对象使用
//内置对象@GetMapping("/object")public String built_in_Object(Model model, HttpServletRequest request, HttpSession session){model.addAttribute("name","坤坤");request.setAttribute("requestFata","request作用域数据");request.getSession().setAttribute("sessionData","session作用域的数据");return "builtinObject";}
hello builtinObject<div>获取作用域中的数据<p th:text="${#request.getAttribute('requestFata')}">获取request域中的数据</p><p th:text="${#session.getAttribute('sessionData')}"></p><p th:text="${session.name}"></p>
</div>
Thymeleaf模板之内置#request对象方法
<div>使用内置对象的方法<p th:text="${#request.getRequestURL()}"></p><p th:text="${#request.getRequestURI()}"></p><p th:text="${#request.getContextPath()}"/><p th:text="${#request.getServerName()}"/><p th:text="${#request.getServerPort()}"/></div>
Thymeleaf模板之内置对象#session对象方法
Session表示HttpSession对象的,是#session的简单表示方式。
<div><p th:text="${#session.getId()}"/><p th:text="${#session.getAttribute('sessionData')}"/></div>
Thymeleaf模板之param对象
Param对象表示url请求的参数集合
<div><p th:text="${param.id}"/><p th:text="${param.name}"/></div>
Thymeleaf模板之内置工具类
#dates
@GetMapping("/unlist")public String utileObject(Model model){model.addAttribute("Mdate",new Date());return "utileObject";}
<div>日期类工具类对象<p th:text="${#dates.format(Mdate)}"/><p th:text="${#dates.format(Mdate,'yyyy-MM-dd')}"/><p th:text="${#dates.format(Mdate,'yyyy-MM-dd HH:mm:ss')}"/><p th:text="${#dates.year(Mdate)}"/><p th:text="${#dates.month(Mdate)}"/><p th:text="${#dates.monthName(Mdate)}"/><p th:text="${#dates.createNow()}"/></div>
#numbers
@GetMapping("/unlist")public String utileObject(Model model){model.addAttribute("numbers",45.01);return "utileObject";}
<div><p th:text="${#numbers.formatCurrency(numbers)}"/><p th:text="${#numbers.formatDecimal(numbers,6,2)}"/></div>
#strings
@GetMapping("/unlist")public String utileObject(Model model){model.addAttribute("Stirng","1234fdghdtgjuefS");return "utileObject";}
<div><p th:text="${#strings.toUpperCase(Stirng)}"/><p th:text="${#strings.indexOf(Stirng,'f')}"/><p th:text="${#strings.substring(Stirng,2,6)}"/><p th:text="${#strings.substring(Stirng,1)}"/><p th:text="${#strings.concat(Stirng,'----java-----')}"/></div>
#lists
@GetMapping("/unlist")public String utileObject(Model model){List<String> list = Arrays.asList("A","B","C");return "utileObject";}
<div><p th:text="${#lists.size(Mlist)}"/><p th:text="${#lists.contains(Mlist,'A')}"/><p th:text="${#lists.isEmpty(Mlist)}"/></div>
Null处理
@GetMapping("/unlist")public String utileObject(Model model){Cat cat =new Cat();cat.setName("狸花猫");Dog dog =new Dog();dog.setName("阿拉斯加");Pet p =new Pet(cat,dog);model.addAttribute("pet",p);return "utileObject";}
当cat值不为null时,才执行name
<div>null处理<p th:text="${pet.cat?.name}"/><p th:text="${pet.dog?.name}"/></div>
Thymeleaf模板之自定义模板
自定义模板,在其他模板文件中多次使用
Hello为自定义模板名称
<div th:fragment="hello"><p>hello world</p></div>
引用模板
插入模板方式1
<div th:insert="~{custom.html :: hello}"></div>
插入模板方式2
<div th:insert="custom.html :: hello"></div>
包含模板
<div th:include="~{custom.html :: hello}"></div>
方式2
<div th:include="custom.html :: hello"></div>
html页面做模板
<div th:include="demo"></div>
<br>
<div th:include="demo :: html"></div>
<br>
<div th:insert="demo"></div>
使用其他目录中的模板
<div th:include="web/demo :: html"></div>
<div th:insert="web/demo"></div>