Spring Boot + Thymeleaf 语法

Spring Boot + Thymeleaf 语法

Github项目地址https://github.com/zhfushengx2048/myspringbootthymeleaf.git

常用标签

1、th : text - 用于文本显示,将业务数据的值填充到 HTML 标签中。

具体使用:

业务逻辑视图处理代码

@GetMapping("/index")
    public String index(Model model){
        System.out.println("index....");
        List<Student> list = new ArrayList<>();
        list.add(new Student(1L,"fusheng",22));
        list.add(new Student(2L,"zhanghao",21));
        list.add(new Student(3L,"gonglin",20));
        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>

2、 th : if - 用于条件判断,对业务数据的值进行判断,如果条件成立则显示内容,否则不显示内容。

具体使用:

业务逻辑视图处理代码

    @GetMapping("/ifTest")
    public ModelAndView ifTest(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("score",88);
        modelAndView.setViewName("iftest");
        return modelAndView;
    }

前端代码

<body>
    <p th:if="${score>=90}">优秀</p>
    <p th:if="${score<90 && score>=80}">良好</p>
</body>

3、 th : unless - 用作条件判断,逻辑与 th : if 恰好相反,如果条件不成立策显示内容,否则不显示。

具体使用:

业务逻辑视图处理代码

    @GetMapping("/unlessTest")
    public ModelAndView unlessTest(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("score",88);
        modelAndView.setViewName("unlesstest");
        return modelAndView;
    }

前端代码

<body>
    <p th:unless="${score>=90}">优秀</p>
    <p th:unless="${score<90 && score>=80}">良好</p>
</body>

4、 th : switch / th : case - 两个结合起来使用,用作多条件等值判断,逻辑与 Java 中的switch-case 一致,当 switch 中的业务数据值等于 case 值时,就显示这个对应的值。

具体使用:

  • 1.首先要创建一个 login.html
  • 2.输入用户名和密码后提交表单至 /login,这里需要注意的是我们不能直接访问 login.html, 因为这里需要通过 Thymeleaf 模板动态为 form 表单的 action 属性赋值,所以必须通过 Handler 来映射到 HTML,否则无法完成动态赋值,在 Handler 中添加如下方法。
  • 3.当服务端接收到一个 GET 请求 login 时,映射到 login.html 并且响应给客户端,这样 th : action="@{/login}" 才能生效,同时再添加一个处理 login 的业务方法。
  • 4.接收到客户端创来的参数并且打印输出,两个 login 方法分别用 @GetMapping("/login")和@PostMapping("/login")进行区分,如果是 GET 请求则响应动态 HTML 页面,如果是 POST 请求则进行业务逻辑处理。

业务逻辑视图处理代码

@GetMapping("/switchcaseTest")
    public ModelAndView switchcaseTest(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("studentId",1);
        modelAndView.setViewName("switchcasetest");
        return modelAndView;
    }

前端代码

<body>
    <div th:switch="${studentId}">
        <p th:case="1">zhangsan</p>
        <p th:case="2">lisi</p>
        <p th:case="3">wangwu</p>
    </div>
</body>

5、 th : action - 用来指定请求的 URL ,相当于 form 表单种 action 属性。

具体使用:

业务逻辑视图处理代码

package xyz.fusheng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class LoginHandler {
    //Get请求响应动态 HTML 页面
    @GetMapping("/login")
    public String login(){
        return "login";
    }
}
package xyz.fusheng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginHandler1 {
    //POST请求进行业务逻辑处理
    @PostMapping("/login")
    public String login(@RequestParam("userName") String userName,@RequestParam("password") String password){
        System.out.println("userName:"+userName);
        System.out.println("password:"+password);
        return "login";
    }
}

前端代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form th:action="@{/login}" method="post">
        用户名:<input type="text" name="userName"/><br/>
        密码:<input type="password" name="password"/><br/>
        <input type="submit" value="登录"/>
    </form>
</body>
</html>

6、th : each 用来遍历集合

具体使用:

添加依赖 Lombok

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

User实体类

package xyz.fusheng.entity;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer gender; //性别 1-男 0-女
}

业务逻辑视图处理代码

package xyz.fusheng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import xyz.fusheng.entity.User;

import java.util.ArrayList;
import java.util.List;

@Controller
public class UserHandler {
    @GetMapping("/each")
    public ModelAndView each(){
        List<User> list = new ArrayList<>();
        list.add(new User(1L,"zhangsan",1));
        list.add(new User(2L,"lisi",1));
        list.add(new User(3L,"wangwu",0));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("usertest");
        modelAndView.addObject("list",list);
        return modelAndView;
    }
}

前端代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>用户信息</h1>
    <table>
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>性别</th>
        </tr>
        <tr th:each="user:${list}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:if="${user.gender == 1}">男</td>
            <td th:if="${user.gender == 0}">女</td>
        </tr>
    </table>
</body>
</html>

7、th : value - 用作给标签赋值。

具体使用:

业务逻辑视图处理代码

package xyz.fusheng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ValueHandler {
    @GetMapping("/valueTest")
    public ModelAndView valueTest(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("valuetest");
        modelAndView.addObject("value","Spring Boot -- Code-fusheng");
        return modelAndView;
    }
}

前端代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input th:value="${value}" />
</body>
</html>

8、th : src 用作引入静态资源,相当于 HTML 原生标签 img、script 的 src 属性。

具体使用:

  • 1.首先在工程中添加图片,这里注意所有的静态资源,包括图片、JavaScript 资源、CSS 资源、HTML 资源(通过 Handler 访问的资源除外)等都需要放置在 /resources/static 路径下才可以访问,因为 Spring Boot 默认从 static 路径下读取静态资源。

业务逻辑视图处理代码

package xyz.fusheng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class SrcHandler {
    @GetMapping("/srcTest")
    public ModelAndView srcTest(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("srctest");
        modelAndView.addObject("src","/images/SpringBoot.png");
        return modelAndView;
    }
}

前端代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <img th:src="${src}" />
</body>
</html>

PS : src 的值可以从模式数据中获取,也可以在 HTML 中直接定义,如果采用这种方式, Handler 中就无需传递业务数据。

Handler

package xyz.fusheng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class SrcHandler1 {
    @GetMapping("srcTest1")
    public ModelAndView srcTest1(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("srctest1");
        return modelAndView;
    }
}

HTML

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<img th:src="@{../images/SpringBoot.png}" />
</body>
</html>

9、th : href - 用作设置超链接的 href。

具体使用:

业务逻辑视图处理代码

package xyz.fusheng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HrefHandler {
    @GetMapping("/hrefTest")
    public ModelAndView hrefTest(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("href","https://spring.io/projects/spring-boot/");
        modelAndView.setViewName("hreftest");
        return modelAndView;
    }
}

前端代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a th:href="${href}">Spring Boot</a>
</body>
</html>

PS : 这里也可以使用,同理 th :src

<a th:hred="@{https://spring.io/projects/spring-boot/}">Spring Boot</a>

10、th : selected - 用作给 HTML 元素设置选中,条件成立则选中,否则不选中。

具体使用:

业务逻辑视图处理代码

package xyz.fusheng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import xyz.fusheng.entity.User;

import java.util.ArrayList;
import java.util.List;

@Controller
public class SelectedHandler {
    @GetMapping("/selectedTest")
    public ModelAndView selectedTest(){
        List<User> list = new ArrayList<>();
        list.add(new User(1L,"zhangsan",1));
        list.add(new User(2L,"lisi",0));
        list.add(new User(3L,"wangwu",1));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("selectedtest");
        modelAndView.addObject("list",list);
        modelAndView.addObject("name","lisi");
        return modelAndView;
    }
}

前端代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <select>
        <option th:each="user:${list}" th:value="${user.id}" th:text="${user.name}" th:selected="${user.name == name}"></option>
    </select>
</body>
</html>

11、th : attr 用作给 HTML 标签的任意属性赋值。

具体使用:

业务逻辑视图处理代码

@Controller
public class AttrHandler {
    @GetMapping("/attrTest")
    public ModelAndView attrTest(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("attrtest");
        modelAndView.addObject("attr","Spring Boot");
        return modelAndView;
    }
}

前端代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input th:attr="value=${attr}"/>
</body>
</html>

Thymeleaf 对象

Thymeleaf 支持直接访问 Servlet Web 原生资源,即 HttpServletRequest、HttpServletResponse、HttpSession、ServletContext 对象

  • #request : 获取 HttpServletRequest 对象
  • #response : 获取 HttpServletResponse 对象
  • #session : 获取 HttpSession 对象
  • #servletContext : 获取 ServletContext 对象

具体使用:

业务逻辑处理代码

package xyz.fusheng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class ServletHandler {
    @GetMapping("/servletTest")
    public String servletTest(HttpServletRequest request){
        request.setAttribute("value","request");
        request.getSession().setAttribute("value","session");
        request.getServletContext().setAttribute("value","servletContext");
        return "servlettest";
    }
}

前端视图代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p th:text="${#request.getAttribute('value')}"></p>
    <p th:text="${#session.getAttribute('value')}"></p>
    <p th:text="${#servletContext.getAttribute('value')}"></p>
    <p th:text="${#response}"></p>
</body>
</html>

Thymeleaf 内置对象

Thymeleaf 除了可以访问 Servlet Web 原生资源,同时还提供了内置对象来简化视图层对于业务数据的处理,可以吧内置对象简单理解为工具类,通过相关方法可以实现业务需求。

  • dates : 日期格式化内置对象
  • calendars : 日期操作内置对象
  • numbers : 数字格式化内置对象
  • strings : 字符串格式化内置对象
  • bools : boolean 类型内置对象
  • arrays : 数组操作内置对象
  • lists : List 集合内置对象
  • sets : Set 集合内置对象
  • maps : Map 集合内置对象

具体使用:

业务逻辑处理代码

package xyz.fusheng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import xyz.fusheng.entity.User;

import java.util.*;

@Controller
public class UtilityHandler {
    @GetMapping("/utilityTest")
    public ModelAndView utilityTest(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("utilitytest");
        modelAndView.addObject("date",new Date());
        Calendar calendar = Calendar.getInstance();
        calendar.set(2020,2,3);
        modelAndView.addObject("calendar",calendar);
        modelAndView.addObject("number",0.06);
        modelAndView.addObject("string","Spring Boot");
        modelAndView.addObject("boolean",true);
        modelAndView.addObject("array", Arrays.asList("张三","李四","王五"));
        List<User> list = new ArrayList<>();
        list.add(new User(1L,"zhangsan",1));
        list.add(new User(2L,"lisi",1));
        list.add(new User(3L,"wangwu",0));
        modelAndView.addObject("list",list);
        Set<User> set = new HashSet<>();
        set.add(new User(1L,"zhangsan",1));
        set.add(new User(2L,"lisi",1));
        set.add(new User(3L,"wangwu",0));
        modelAndView.addObject("set",set);
        Map<Long,User> map = new HashMap<>();
        map.put(1L,new User(1L,"zhangsan",1));
        map.put(2L,new User(2L,"lisi",1));
        map.put(3L,new User(3L,"wangwu",0));
        modelAndView.addObject("map",map);
        return modelAndView;
    }
}

前端视图代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    date格式化:<span th:text="${#dates.format(date,'yyyy-MM-dd')}"></span><br/>
    当前日期:<span th:text="${#dates.createToday()}"></span><br/>
    当前时间:<span th:text="${#dates.createNow()}"></span><br/>
    calendar格式化:<span th:text="${#calendars.format(calendar,'yyyy-MM-dd')}"></span><br/>
    number百分比格式化:<span th:text="${#numbers.formatPercent(number,2,2)}"></span><br/>
    name是否为空:<span th:text="${#strings.isEmpty(string)}"></span><br/>
    name的长度:<span th:text="${#strings.length(string)}"></span><br/>
    name拼接:<span th:text="${#strings.concat('I Love',string)}"></span><br/>
    boolean是否为true:<span th:text="${#bools.isTrue(boolean)}"></span><br/>
    arrays的长度:<span th:text="${#arrays.length(array)}"></span><br/>
    arrays是否包含张三:<span th:text="${#arrays.contains(array,'张三')}"></span><br/>
    List是否为空:<span th:text="${#lists.isEmpty(list)}"></span><br/>
    List的长度:<span th:text="${#lists.size(list)}"></span><br/>
    Set是否为空:<span th:text="${#sets.isEmpty(set)}"></span><br/>
    Set的长度:<span th:text="${#sets.size(set)}"></span><br/>
    Map是否为空:<span th:text="${#maps.isEmpty(map)}"></span><br/>
    Map的长度:<span th:text="${#maps.size(map)}"></span><br/>
</body>
</html>

Spring Boot 整合 Thymeleaf 的具体操作,Thymeleaf 是一个支持原生 HTML 文件的 Java 模板引擎。既能以静态页面的方式直接运行,也可以结合后端代码动态生成,大大简化了前后d端开发人员的工作对接。

Thymeleaf 模版标签的使用,相比于 JSP,Thymeleaf 渲染页面的性能更高,可以提高整个程序的运行效率,同时提供了功能非常强大模版标签,JSP 能实现的各种功能,Thymeleaf 也同样可以实现,所以在实际开发中,建议使用 Thymeleaf 作为视图层解决方案。

发布了4 篇原创文章 · 获赞 3 · 访问量 202

猜你喜欢

转载自blog.csdn.net/qq_42999835/article/details/104158038