整合Thymeleaf
-
Spring Boot 可以结合 Thymeleaf 模版来整合 HTML,使用原生的 HTML 作为视图。
-
Thymeleaf 模版是面向 Web 和独立环境的 Java 模版引擎,能够处理
HTML、XML、JavaScript、CSS
等。
<p th:text="${message}"></p>
- pom.xml
<!-- 继承父包 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
</parent>
<dependencies>
<!-- web启动jar -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
- 创建
appliction.yml
server:
port: 9090
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
- Handler控制器
package com.southwind.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/index")
public class IndexHandler {
@GetMapping("/index")
public String index(){
System.out.println("index...");
return "index";
}
}
- HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
如果希望客户端可以直接访问 HTML 资源,将这些资源放置在 static 路径下即可,否则必须通过 Handler 的后台映射才可以访问静态资源。
Thymeleaf 常用语法
- 赋值、拼接
@GetMapping("/index2")
public String index2(Map<String,String> map){
map.put("name","张三");
return "index";
}
<p th:text="${name}"></p>
<p th:text="'学生姓名是'+${name}+2"></p>
<p th:text="|学生姓名是,${name}|"></p>
- 条件判断:if/unless
th:if 表示条件成立时显示内容,th:unless 表示条件不成立时显示内容
@GetMapping("/if")
public String index3(Map<String,Boolean> map){
map.put("flag",true);
return "index";
}
<p th:if="${flag == true}" th:text="if判断成立"></p>
<p th:unless="${flag != true}" th:text="unless判断成立"></p>
- 循环
@GetMapping("/index")
public String index(Model model){
System.out.println("index...");
List<Student> list = new ArrayList<>();
list.add(new Student(1L,"张三",22));
list.add(new Student(2L,"李四",23));
list.add(new Student(3L,"王五",24));
model.addAttribute("list",list);
return "index";
}
<table>
<tr>
<th>index</th>
<th>count</th>
<th>学生ID</th>
<th>学生姓名</th>
<th>学生年龄</th>
</tr>
<tr th:each="student,stat:${list}" th:style="'background-color:'+@{${stat.odd}?'#F2F2F2'}">
<td th:text="${stat.index}"></td>
<td th:text="${stat.count}"></td>
<td th:text="${student.id}"></td>
<td th:text="${student.name}"></td>
<td th:text="${student.age}"></td>
</tr>
</table>
stat 是状态变量,属性:
-
index 集合中元素的index(从0开始)
-
count 集合中元素的count(从1开始)
-
size 集合的大小
-
current 当前迭代变量
-
even/odd 当前迭代是否为偶数/奇数(从0开始计算)
-
first 当前迭代的元素是否是第一个
-
last 当前迭代的元素是否是最后一个
-
URL
Thymeleaf 对于 URL 的处理是通过 @{...}
进行处理,结合 th:href 、th:src
<h1>Hello World</h1>
<a th:href="@{http://www.baidu.com}">跳转</a>
<a th:href="@{http://localhost:9090/index/url/{na}(na=${name})}">跳转2</a>
<img th:src="${src}">
<div th:style="'background:url('+ @{${src}} +');'">
<br/>
<br/>
<br/>
</div>
- 三元运算
@GetMapping("/eq")
public String eq(Model model){
model.addAttribute("age",30);
return "test";
}
<input th:value="${age gt 30?'中年':'青年'}"/>
-
gt great than 大于
-
ge great equal 大于等于
-
eq equal 等于
-
lt less than 小于
-
le less equal 小于等于
-
ne not equal 不等于
-
switch
@GetMapping("/switch")
public String switchTest(Model model){
model.addAttribute("gender","女");
return "test";
}
<div th:switch="${gender}">
<p th:case="女">女</p>
<p th:case="男">男</p>
<p th:case="*">未知</p>
</div>
- 基本对象
#ctx
:上下文对象#vars
:上下文变量#locale
:区域对象#request
:HttpServletRequest 对象#response
:HttpServletResponse 对象#session
:HttpSession 对象#servletContext
:ServletContext 对象
@GetMapping("/object")
public String object(HttpServletRequest request){
request.setAttribute("request","request对象");
request.getSession().setAttribute("session","session对象");
return "test";
}
<p th:text="${#request.getAttribute('request')}"></p>
<p th:text="${#session.getAttribute('session')}"></p>
<p th:text="${#locale.country}"></p>
- 内嵌对象
可以直接通过 # 访问。
1、dates:java.util.Date 的功能方法
2、calendars:java.util.Calendar 的功能方法
3、numbers:格式化数字
4、strings:java.lang.String 的功能方法
5、objects:Object 的功能方法
6、bools:对布尔求值的方法
7、arrays:操作数组的功能方法
8、lists:操作集合的功能方法
9、sets:操作集合的功能方法
10、maps:操作集合的功能方法
@GetMapping("/util")
public String util(Model model){
model.addAttribute("name","zhangsan");
model.addAttribute("users",new ArrayList<>());
model.addAttribute("count",22);
model.addAttribute("date",new Date());
return "test";
}
<!-- 格式化时间 -->
<p th:text="${#dates.format(date,'yyyy-MM-dd HH:mm:sss')}"></p>
<!-- 创建当前时间,精确到天 -->
<p th:text="${#dates.createToday()}"></p>
<!-- 创建当前时间,精确到秒 -->
<p th:text="${#dates.createNow()}"></p>
<!-- 判断是否为空 -->
<p th:text="${#strings.isEmpty(name)}"></p>
<!-- 判断List是否为空 -->
<p th:text="${#lists.isEmpty(users)}"></p>
<!-- 输出字符串长度 -->
<p th:text="${#strings.length(name)}"></p>
<!-- 拼接字符串 -->
<p th:text="${#strings.concat(name,name,name)}"></p>
<!-- 创建自定义字符串 -->
<p th:text="${#strings.randomAlphanumeric(count)}"></p>
Spring Boot 数据校验
package com.daq.entity;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Data
public class User {
@NotNull(message = "id不能为空")
private Long id;
@NotEmpty(message = "姓名不能为空")
@Length(min = 2,message = "姓名长度不能小于2位")
private String name;
@Min(value = 16,message = "年龄必须大于16岁")
private int age;
}
@GetMapping("/validator")
public void validatorUser(@Valid User user,BindingResult bindingResult){
System.out.println(user);
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
for(ObjectError objectError:list){
System.out.println(objectError.getCode()+"-"+objectError.getDefaultMessage());
}
}
}