Spring 整合HTML
Spring boot可以结合 Thymeleaf 模板整合HTML,使用原生的HTML作为视图
Thymeleaf 模板是面向 Web 和独立环境的 java模板引擎,它能够处理HTML、xml、JavaScript、css等资源
pom.xml依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>springboot1</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 继承父包 -->
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.0.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<!-- web启动jar包 -->
<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.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
application.yml
server:
port: 9090
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
Handler
package com.makerjack.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(){
return "index";
}
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
如果希望客户端可以直接访问文件,将这些文件资源放置在static路径下即可(resources/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}"></p>
<p th:text="|我是${name}|"></p>
条件判断
if 和 unless
th:if 条件成立时显示内容
th:unless 条件不成立时显示内容
@GetMapping("/index3")
public String index3(Map<String,Boolean> map){
map.put("flag",true);
return "index";
}
注意下面的text双引号内不能有空格
<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){
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>学生ID</th>
<th>学生姓名</th>
<th>学生年龄</th>
</tr>
<tr th:each="student:${list}">
<td th:text="${student.id}"></td>
<td th:text="${student.name}"></td>
<td th:text="${student.age}"></td>
</tr>
</table>
循环时可以添加循环变量来对特定行进行操作
在each中添加stat状态变量,其含有如下属性
- index 集合中元素index值(从0开始)
- count 集合中元素count值(从1开始)
- size 集合的大小
- current 当前迭代的变量
- odd / even 当前count值的奇偶
- first 当前迭代元素是否是第一个
- last 当前迭代元素是否是最后一个
<table>
<tr>
<th>index</th>
<th>count</th>
<th>学生ID</th>
<th>学生姓名</th>
<th>学生年龄</th>
</tr>
<tr th:each="student,stat:${list}">
<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值(按count算)是奇数(odd,偶数是even),那么就背景色为#ec9bad
<tr th:each="student,stat:${list}" th:style="'background-color:'+@{${stat.odd}?'#ec9bad'}">
URL
Thymeleaf对于URL处理是通过@{…}处理的,结合th:href和th:src
@GetMapping("/test")
public String index4(Model model){
model.addAttribute("name","tom");
return "index";
}
@GetMapping("/url/{na}")
@ResponseBody
public String url(@PathVariable("na") String name){
return name;
}
通过访问 http://localhost:9090/index/test来给前端传递参数tom
<a th:href="@{http://www.baidu.com}">传送门</a>
<a th:href="@{http://localhost:9090/index/url/{na}(na=${name})}">传送门</a>
第二个超链接得到tom并映射到na上,再由这个URL http://localhost:9090/index/url/tom调用url方法
最后页面呈现tom
三元运算
给前端返回 age=23
@RequestMapping("/eq")
public String eq(Model model){
model.addAttribute("age",23);
return "index";
}
前端针对age判断,如果 age > 20 判定为青年 否则为少年
<input th:value="${age gt 20 ? '青年':'少年'}">
几个判定关键字
关键字 | 全称 | 含义 |
---|---|---|
gt | greater than | 大于 |
ge | greater or equal | 大于等于 |
eq | equal | 等于 |
le | less or equal | 小于等于 |
lt | less than | 小于 |
ne | not equal | 不等于 |
常见的对象
- #ctx 上下文对象
- #vars 上下文变量
- #locale 区域对象
- #request HttpServletRequest对象
- #response HttpServletResponse对象
- #session HttpSession对象
- #servletcontext ServletContext对象
@RequestMapping("/object")
public String object(HttpServletRequest request){
request.setAttribute("request","我是request对象");
request.getSession().setAttribute("session","我是session对象");
return "index";
}
<p th:text="${#request.getAttribute('request')}"></p>
<p th:text="${#session.getAttribute('session')}"></p>
<p th:text="${#locale.country}"></p>
内嵌对象
可以通过#直接访问
- dates:java.util.Date的功能方法
- calendar:java.util.Calendar功能方法
- numbers:格式化数字
- strings:java.lang.String的功能方法
- objects:Object的功能方法
- bools:对布尔求是的方法
- arrays:操作数组的功能方法
- lists:操作列表的功能方法
- sets:操作集合的功能方法
- maps:操作图的功能方法
@RequestMapping("/util")
public String util(Model model){
model.addAttribute("date",new Date());
model.addAttribute("name","张三");
model.addAttribute("users",new ArrayList<>());
model.addAttribute("count",23);
return "index";
}
<!-- 格式化时间 -->
<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>
<!-- 判断列表是否为空 -->
<p th:text="${#lists.isEmpty(users)}"></p>
<!-- 输出字符串长度 -->
<p th:text="${#strings.length(name)}"></p>
<!-- 拼接字符串 -->
<p th:text="${#strings.concat(name,name)}"></p>
<!-- 创建自定义字符串 -->
<p th:text="${#strings.randomAlphanumeric(count)}"></p>