Spring Boot Themeleaf语法

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状态变量,其含有如下属性

  1. index 集合中元素index值(从0开始)
  2. count 集合中元素count值(从1开始)
  3. size 集合的大小
  4. current 当前迭代的变量
  5. odd / even 当前count值的奇偶
  6. first 当前迭代元素是否是第一个
  7. 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 ? '青年':'少年'}">

在这里插入图片描述
几个判定关键字

关键字全称含义
gtgreater than大于
gegreater or equal大于等于
eqequal等于
leless or equal小于等于
ltless than小于
nenot 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>

在这里插入图片描述

内嵌对象

可以通过#直接访问

  1. dates:java.util.Date的功能方法
  2. calendar:java.util.Calendar功能方法
  3. numbers:格式化数字
  4. strings:java.lang.String的功能方法
  5. objects:Object的功能方法
  6. bools:对布尔求是的方法
  7. arrays:操作数组的功能方法
  8. lists:操作列表的功能方法
  9. sets:操作集合的功能方法
  10. 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>

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值