SpringBoot 整合Thymeleaf

作者Gitee地址 https://gitee.com/thciweicloud
作者项目 面包博客,一个微服务架构的前后端分离博客系统。

SpringBoot 整合Thymeleaf

Spring Boot 可以结合 Thymeleaf 模版来整合 HTML,使用原生的 HTML 作为视图

Thymeleaf 模版是面向 Web 和独立环境的 Java 模版引擎,能够处理 HTML、XML、JavaScript、CSS 等

<p th:text="${message}"></p>

配置

  • pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

在resources 中新建文件夹 templates 存放 html文件

  • 配置appliction.yml
server:
  port: 8181
spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML5
    encoding: UTF-8
  • Handler
package com.thciwei.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
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 的后台映射才可以访问静态资源

因为static是springboot默认扫描的文件夹,而templates不会被扫描

Thymeleaf常用语法

idea 下 解决thymeleaf 飘红,在<!DOCTYPE html>下添加注释

<!--suppress ALL-->
引入标签
<html xmlns:th="http://www.thymeleaf.org">

html 单标签 配置 thymeleaf

语法

  • 循环
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Hello World</h1>
<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>
</body>
</html>
  • 赋值、拼接
@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},2|"></p>
学生姓名是张三2
学生姓名是,张三,2
  • 条件判断:if/unless

th:if 表示条件成立时显示内容,th:unless 表示条件不成立时显示内容

@GetMapping("/if")
public String index(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>

隔行变色 html标签全闭合才解析成功@{${stat.odd}}

<html xmlns:th="http://www.thymeleaf.org"></html>
<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

href方式

@GetMapping("/test")
public String test(Model model) {
    model.addAttribute("name","tom");
    return "test";
}

@GetMapping("/url/{name}")
@ResponseBody
public String url(@PathVariable("name") String name) {
    return name;

}
test.html
<body>
<a th:href="@{http://www.baidu.com}">跳转</a>
<a th:href="@{http://localhost:8181/index/url/{name}(name=${name})}">跳转2</a>
</body>

注意从后端拿值时 需要这样的格式 {name}(name=${name})

img方式

@GetMapping("/img")
public String img(Model model) {
    model.addAttribute("src", "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3399427526,1444995627&fm=26&gp=0.jpg");
    return "test";
}
<body>
<h1>Hello World</h1>
<a th:href="@{http://www.baidu.com}">跳转</a>
<a th:href="@{http://localhost:8181/index/url/{name}(name=${name})}">跳转2</a>
<img th:src="${src}">
<div th:style="'background:url('+@{${src}}+');'">
    <br/>
    <br/>
    <br/>
</div>
</body>
  • 三元运算
@GetMapping("/eq")
public String eq(Model model){
    model.addAttribute("age",31);
    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";
}
<input th:value="${age gt 30?'中年':'青年'}">
<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>
-- 显示
request对象
session对象
CN
  • 内嵌对象

可以直接通过 # 访问。

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>

2021-01-30 16:38:008
Sat Jan 30 00:00:00 CST 2021
Sat Jan 30 16:38:08 CST 2021
false
true
8
zhangsanzhangsanzhangsan
385YHDLHAO0ELU43KVRS1M

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值