• Thymeleaf


    在这里插入图片描述

    Thymeleaf

    概述

    Thymeleaf 是一个流行的模板引擎,该模板引擎采用 Java 语言开发。

    模板引擎是一个技术名词,是跨领域跨平台的概念,在 Java 语言体系下有模板引擎, 在 C#、PHP 语言体系下也有模板引擎,甚至在 JavaScript 中也会用到模板引擎技术,Java 生 态下的模板引擎有 Thymeleaf 、Freemaker、Velocity、Beetl(国产) 等。

    Thymeleaf 对网络环境不存在严格的要求,既能用于 Web 环境下,也能用于非 Web 环境下。在非 Web 环境下,他能直接显示模板上的静态数据;在 Web 环境下,它能像 Jsp 一 样从后台接收数据并替换掉模板上的静态数据。它是基于 HTML 的,以 HTML 标签为载体, Thymeleaf 要寄托在 HTML 标签下实现。

    SpringBoot 集成了 Thymeleaf 模板技术,并且 Spring Boot 官方也推荐使用 Thymeleaf 来替代 JSP 技术,Thymeleaf 是另外的一种模板技术,它本身并不属于 Spring Boot,Spring Boot 只是很好地集成这种模板技术,作为前端页面的数据展示。在过去的 Java Web 开发中,我们往往会选择使用 Jsp 去完成页面的动态渲染,但是 Jsp 编译运行的效率比较低。

    Thymeleaf 的官方网站: http://www.thymeleaf.org

    Thymeleaf 官方手册: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

    Java 项目中使用 Thymeleaf【了解】

    案例代码一:渲染静态数据

    1、导入 maven 核心依赖

    <dependencies>
        
        <dependency>
            <groupId>org.thymeleafgroupId>
            <artifactId>thymeleafartifactId>
            <version>3.0.12.RELEASEversion>
        dependency>
    
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.2version>
        dependency>
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2、测试类

    // 使用模板引擎对象渲染模板中的静态数据
    @Test
    public void test() {
        // 创建模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
    
        // 准备模板
        String input = "";
    
        // 准备模板中填充的(环境上下文)内容对象
        Context context = new Context();
    
        // 使用模板引擎处理模板和内容并获取渲染后的结果
        String output = templateEngine.process(input, context);
    
        System.out.println(output);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    案例代码二:渲染动态数据
    // 使用模板引擎对象渲染模板中的动态数据
    @Test
    public void test2() {
        // 创建模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
    
        // 准备模板(使用占位符)
        String input = "";
    
        // 准备模板中填充的(环境上下文)内容对象
        Context context = new Context();
        
        // 给内容设置参数
        context.setVariable("name", "易烊千玺");
    
        // 使用模板引擎处理模板和内容并获取渲染后的结果
        String output = templateEngine.process(input, context);
    
        System.out.println(output);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    案例代码三:渲染 HTML 模板文件

    1、html 页面

    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>测试Thymeleaftitle>
    head>
    <body>
        <input type="text" th:value="${name}">
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2、测试代码

    // 使用模板引擎对象渲染HTML模板中的动态数据
    @Test
    public void test3() {
        // 创建模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
        
        // 创建模板解析器用于读取模板文件
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        
        // 使用模板引擎设置模板解析器
        templateEngine.setTemplateResolver(templateResolver);
    
        // 准备模板中填充的(环境上下文)内容对象
        Context context = new Context();
    
        // 给内容设置参数
        context.setVariable("name", "易烊千玺");
    
        // 使用模板引擎处理模板和内容并获取渲染后的结果
        String output = templateEngine.process("index.html", context);
    
        System.out.println(output);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    案例代码四:设置模板解析器的前后缀

    1、在 resources 下新建 template 文件夹,并创建 main.html

    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>测试给模板解析器设置前后缀title>
    head>
    <body>
        <input type="text" th:value="${name}">
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2、测试类

    // 给模板解析器设置前后缀
    @Test
    public void test4() {
        // 创建模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
    
        // 创建模板解析器用于读取模板文件
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    
        // 设置模板名称路径的前缀
        templateResolver.setPrefix("template/");
    
        // 设置模板名称路径的后缀
        templateResolver.setSuffix(".html");
    
        // 使用模板引擎设置模板解析器
        templateEngine.setTemplateResolver(templateResolver);
    
        // 准备模板中填充的内容对象
        Context context = new Context();
    
        // 给内容设置参数
        context.setVariable("name", "易烊千玺");
    
        // 使用模板引擎处理模板和内容并获取渲染后的结果
        String output = templateEngine.process("main", context);
    
        System.out.println(output);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    SpringBoot 整合 Thymeleaf

    1、pom.xml 文件添加起步依赖

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
    
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    2、创建 Controller

    @Controller
    @RequestMapping("thymeleaf")
    public class ThymeleafController {
        @RequestMapping("test")
        public String test(Model model) {
            model.addAttribute("data", "Thymeleaf模板引擎");
    
            return "index";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    3、在 resources/templates 目录下新建 index.html

    1、在 html 标签中添加指定命名空间

    <html xmlns:th="http://www.thymeleaf.org">html>
    
    • 1

    2、通过如下标签属性可获取 Model 中的数据

    th:text="${data}
    
    • 1
    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试主页title>
    head>
    <body>
        <h1 align="center" style="color: aqua;" th:text="${data}">展示数据h1>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    4、Thymeleaf 中的常见配置

    spring:
      thymeleaf:
        # 开启Thymeleaf模板引擎
        enabled: true
        # 关闭Thymeleaf缓存
        cache: false
        # 设置编码集
        encoding: UTF-8
        # 设置模板类型
        mode: HTML
        # 设置访问路径的前缀
        prefix: classpath:/templates/
        # 设置访问路径的后缀
        suffix: .html
        # 处理模板前检查模板是否存在
        check-template: true
        # 是否检查模板文件的路径位置
        check-template-location: true
        servlet:
          # 设置模板内容类型
          content-type: text/html
        # 排除的视图名称
        excluded-view-names:
          # 默认模板解析器的执行顺序
        template-resolver-order:
        # 要解析的视图名称,用逗号分隔
        # view-names:
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    Thymeleaf 表达式

    表达式分类
    表达式描述案例代码
    ${…}变量表达式,可用于获取传入的参数

    数据

    *{…}选择表达式,基本没人用
    #{…}消息表达式,一般用于国际化 i18n
    @{…}链接网址表达式,用于替换网页中的 src、href 等的值,用的稍稍稍微多点th:href=“@{/css/home.css}”
    ~{…}片段表达式,可以用于引用公共的目标片段
    变量表达式
    概述

    标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和 EL 中的 ${} 相同。Thymeleaf 中的变量表达式使用 ${变量名} 的方式获取 Controller 中 model 其中的数据,也可以获取域对象中的数据。

    注意:th:text=“” 是 Thymeleaf 的一个属性,用于文本的显示,语法为 ${变量名}

    案例代码

    1、pom.xml 导入起步依赖

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    2、创建实体类

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Car {
        private String brand;
        private String color;
    }
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class User {
        private Integer id;
        private String name;
        private Integer age;
        private String gender;
        private String info;
        private Car car;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    3、创建 Controller

    @Controller
    @RequestMapping("test")
    public class TestController {
    
        @RequestMapping("testStandardExpression")
        public String testStandardExpression(Model model) {
            // 设置内容为基本数据类型和字符串
            model.addAttribute("name", "易烊千玺");
            model.addAttribute("age", 21);
    
            // 设置内容为对象
            User user = new User(1, "易烊千玺", 21, "男", "四个字", new Car("BYD", "白色"));
            model.addAttribute("user", user);
    
            // 设置跳转的路径
            return "testStandardExpression";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    4、创建 index.html

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试标准表达式title>
    head>
    <body>
        <table align="center" border="1px" width="500px">
            <caption><h1 style="color: aquamarine">基本数据类型和字符串h1>caption>
            <tr>
                <td>姓名td>
                <td><p th:text="${name}">姓名p>td>
            tr>
            <tr>
                <td>年龄td>
                <td><p th:text="${age}">年龄p>td>
            tr>
        table>
    
        <table align="center" border="1px" width="500px">
            <caption><h1 style="color: aquamarine">对象h1>caption>
            <tr>
                <td>IDtd>
                <td><p th:text="${user.id}">IDp>td>
            tr>
            <tr>
                <td>姓名td>
                <td><p th:text="${user.name}">姓名p>td>
            tr>
            <tr>
                <td>年龄td>
                <td><p th:text="${user.age}">年龄p>td>
            tr>
            <tr>
                <td>性别td>
                <td><p th:text="${user.gender}">性别p>td>
            tr>
            <tr>
                <td>信息td>
                <td><p th:text="${user.info}">信息p>td>
            tr>
            <tr>
                <td>汽车品牌td>
                <td><p th:text="${user.car.brand}">品牌p>td>
            tr>
            <tr>
                <td>汽车颜色td>
                <td><p th:text="${user.car.color}">颜色p>td>
            tr>
        table>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    选择表达式【了解】
    概述

    选择变量表达式,也叫星号变量表达式,使用 th:object 属性来绑定对象

    选择表达式首先使用 th:object 来绑定后台传来的 User 对象,然后使用 * 来代表这个对 象,后面 {} 中的值是此对象中的属性。

    选择变量表达式 *{…} 是另一种类似于标准变量表达式 ${…} 表示变量的方法

    选择变量表达式在执行时是在选择的对象上求解,而${…}是在上下文的变量 Model 上求解,这种写法比标准变量表达式繁琐,只需要了解即可。

    案例代码

    1、实体类

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Person {
        private Integer id;
        private String name;
        private Integer age;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2、Controller

    @Controller
    public class SelectiveController {
        @RequestMapping("selective")
        public String testSelective(Model model) {
            model.addAttribute("person", new Person(1, "易烊千玺", 21));
    
            return "selective";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3、Html

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试选择表达式title>
    head>
    <body>
        
        <table align="center" border="1px" th:object="${person}">
            <caption><h1 style="color: blue">选择变量表达式h1>caption>
            <tr>
                <td>IDtd>
                <td><div th:text="*{id}">div>td>
            tr>
            <tr>
                <td>姓名td>
                <td><div th:text="*{name}">div>td>
            tr>
            <tr>
                <td>年龄td>
                <td><div th:text="*{age}">div>td>
            tr>
        table>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    链接表达式
    概述

    主要用于链接、地址的展示,可用于

    <script src="...">script>
    <link href="...">
    <a href="...">a>
    <form action="...">form>
    <img src="">
    • 1
    • 2
    • 3
    • 4
    • 5

    可以在 URL 路径中动态获取数据,其他用法与标签跳转基本相同,可以是相对地址,也可以是绝对地址。

    @{/}是相对应用根路径,其他都是相对当前路径

    @{/}斜杠开头表示相对整个应用根目录,"/"表示 “/应用上下文路径”

    th:href 是一个修饰符属性,将表达式结果设置为标签 href 属性的值

    格式
    
    th:href="@{路径}"
    
    
    th:href="@{路径(参数名1=${参数1},参数名2=${参数2}})}"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    案例代码一:路径跳转

    1、控制层

    @Controller
    public class LinkController {
        @RequestMapping("test/link/test")
        public String test(Model model) {
    		// @{}无法获取Model中的数据
            model.addAttribute("url", "test/testStandardExpression");
    
            return "link";
        }
    
        @RequestMapping("test/link/url")
        @ResponseBody
        public String testLinkUrl() {
            return "当前路径";
        }
    
        @RequestMapping("test/url")
        @ResponseBody
        public String testUrl() {
            return "上级路径";
        }
    
        @RequestMapping("url")
        @ResponseBody
        public String test() {
            return "根路径";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    2、link.html

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
        <head>
            <meta charset="UTF-8">
            <title>测试链接表达式title>
        head>
        <body>
            <a th:href="@{url}" >测试当前目录a>
            <br/>
            <br/>
            <a th:href="@{/url}" >测试访问根路径a>
            <br/>
            <br/>
            <a th:href="@{./url}" >测试当前目录a>
            <br/>
            <br/>
            <a th:href="@{../url}" >测试上级目录a>
            <br/>
            <br/>
            <a th:href="@{http://www.baidu.com}" >测试访问绝对路径a>
        body>
        
        <script th:src="@{/js/jquery-1.8.3.min.js}">script>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    案例代码二:参数传递

    1、实体类

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Person {
        private Integer id;
        private String name;
        private Integer age;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2、Controller

    @Controller
    @RequestMapping("user")
    public class UserController {
        @RequestMapping("testUrl")
        public String testUrl(Model model) {
            Person person = new Person(101, "迪丽热巴", 20);
    
            model.addAttribute("person", person);
    
            return "url";
        }
    
        // 测试携带参数
        @RequestMapping("getParam")
        @ResponseBody
        public Person getParam(Person person) {
            return person;
        }
    
        // 测试RESTful风格
        @RequestMapping("testRESTFul/{id}/{name}")
        @ResponseBody
        public String testRESTFul(@PathVariable("id") Integer id,
                                  @PathVariable("name") String name) {
            return "ID:" + id + " 姓名:" + name;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    3、声明 url.html 文件

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试链接表达式传递参数title>
    head>
    <body>
    <table align="center" border="1px">
        <caption><h1 style="color: blue">测试链接表达式传递参数h1>caption>
        <tr>
            <th>IDth>
            <th>姓名th>
            <th>年龄th>
            <th>操作th>
        tr>
        <tr>
            <td><div th:text="${person.id}">div>td>
            <td><div th:text="${person.name}">div>td>
            <td><div th:text="${person.age}">div>td>
            
            <td><a th:href="@{getParam(id = ${person.id}, name = ${person.name}, age = ${person.age})}">测试带参跳转a>td>
        tr>
        <tr>
            <td colspan="4" align="center">
                <a th:href="@{getParam(id = 1, name = '易烊千玺', age = 21)}">测试传递静态参数a>
            td>
        tr>
        <tr>
            <td colspan="4" align="center">
                <a th:href="@{getParam}">测试不带参数跳转a>
            td>
        tr>
        <tr>
            <td colspan="4" align="center">
                <a th:href="@{'testRESTful/' + ${person.id} + '/' + ${person.name}}">测试RESTful风格a>
            td>
        tr>
    table>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    消息表达式【了解】
    概述

    Thymeleaf 中的消息表达式是对国际化的支持,语法格式为 #{…}

    i18n

    国际化(Internationalization)指的是同一个网站可以支持多种不同的语言,以方便不同国家,不同语种的用户访问。

    i18n(其来源是英文单词 internationalization 的首末字符i和n,18为中间的字符数)是“国际化”的简称。在资讯领域,国际化(i18n)指让产品(出版物,软件,硬件等)无需做大的改变就能够适应不同的语言和地区的需要。对程序来说,在不修改内部代码的情况下,能根据不同语言及地区显示相应的界面。 在全球化的时代,国际化尤为重要,因为产品的潜在用户可能来自世界的各个角落。通常与 i18n 相关的还有L10n(“本地化”的简称)。

    案例代码

    1、在 resources 下新建 i18N 文件夹并新建三个配置文件

    message.properties

    login=login|登录
    rememberMe=rememberMe|记住我
    username=username|账号
    password=password|密码
    
    • 1
    • 2
    • 3
    • 4

    message_en_US.properties

    login=login
    rememberMe=rememberMe
    username=username
    password=password
    
    • 1
    • 2
    • 3
    • 4

    message_zh_CN.properties

    login=登录
    rememberMe=记住我
    username=账号
    password=密码
    
    • 1
    • 2
    • 3
    • 4

    2、创建自定义国际化解析器

    // 自定义国际化解析器
    public class MyLocaleResolver implements LocaleResolver {
        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            // 从请求参数中获取语言
            String lang = request.getParameter("lang");
    
            // 从请求对象中获取区域对象
            Locale locale;
    
            // 判断是否为空
            if (lang != null && !lang.equals("")) {
                // 获取语言和地区
                String[] arr = lang.split("_");
    
                // 给区域对象赋值
                locale = new Locale(arr[0], arr[1]);
            } else {
                // 给区域对象赋值
                locale = new Locale("en", "US");
            }
    
            return locale;
        }
    
        @Override
        public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    3、自定义配置类

    @Configuration
    public class WebConfig {
        // 将自定义国际化解析器注入到Spring容器中
        @Bean
        public LocaleResolver localeResolver() {
            return new MyLocaleResolver();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    4、yml 配置文件

    spring:
      thymeleaf:
        cache: true
      messages:
        # 配置国际化配置文件的路径
        basename: i18N/message
        encoding: UTF-8
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    5、Controller

    @Controller
    public class MessageController {
        // 测试国际化
        @RequestMapping("i18n")
        public String message() {
            return "i18n";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    6、Html 页面

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试消息表达式title>
    head>
    <body>
        <form>
            <table align="center">
                <caption><h1 style="color:red">测试国际化h1>caption>
                <tr>
                    <td th:text="#{username}">td>
                    <td><input type="text" name="name"/>td>
                tr>
                <tr>
                    <td th:text="#{password}">td>
                    <td><input type="password" name="password"/>td>
                tr>
                <tr>
                    <td colspan="2" style="height: 50px" align="center">
                        <input type="checkbox" th:text="#{rememberMe}">        
                        <button type="button" th:text="#{login}">button>
                    td>
                tr>
                <tr>
                    <td colspan="2" align="center">
                        <a href="/i18n?lang=zh_CN">中文a>
                        <a href="/i18n?lang=en_US">Englisha>
                    td>
                tr>
            table>
        form>
    
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    Thymeleaf 字面量

    概述

    字面量:对应数据类型的合法取值,可以在 html 页面直接使用,不需要后台传递

    文本
    概述

    文本文字只是在单引号之间指定的字符串。它们可以包含任何字符,如果字符之中没有空格,可以不加单引号。使用 “+” 连接文本。也可以使用 “|” 连接文本

    案例代码

    1、Controller

    @Controller
    public class TestController {
        // 测试文本字面量
        @RequestMapping("text")
        public String test(Model model) {
            model.addAttribute("name", "易烊千玺");
            model.addAttribute("info", "四个字");
    
            return "text";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2、Html

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试文本字面量title>
    head>
    <body>
        <p th:text="你好">文本数据p>
        <p th:text="'你好 世界'">文本数据中带有空格必须使用单引号引起来,否则会报错p>
        <p th:text="'你好' + '世界'">拼接字符串需要使用单引号引起来p>
        <p th:text="'你好' + ${name}">字符串拼接变量表达式p>
        <p th:text="|你好 ${name}|">字符串拼接变量表达式p>
        <p th:text="|你好 ${name}${info}|">字符串拼接变量表达式p>
        <p th:text="true">布尔值p>
        <p th:text="123456">数值p>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    算术表达式
    概述

    数字文字就是∶数字,算术运算也可用:+,-,*,/ 和 %

    表达式中的值可以使用 > ,< ,>= ,<= 符号进行比较。以及 == 和 != 可以用来检查是否相等。还可以使用实体引用 gt(>),lt(<),ge(>=),le(<=),not(!),eq(==), neq(!=) 等

    案例代码

    1、Controller

    @Controller
    public class TestController {
    
        // 测试算术字面量
        @RequestMapping("num")
        public String testNum(Model model) {
            model.addAttribute("num", "100");
    
            return "num";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2、html

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试算术字面量title>
    head>
    <body>
        <p th:text="100">数值p>
        <p th:text="${num}">变量表达式获取到的数值p>
        <p th:text="${num} + 100">数值相加p>
        <p th:text="100 + 100 + '字符串拼接:' + 100 + 100">字符串拼接p>
        <p th:text="100 + 100 + ':运算:' + (100 + 100)">算术运算p>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    布尔
    概述

    布尔是true, false。and(与),or(或),not(非)、!(非)

    ,布尔值为true显示标签,反之不显示<

    案例代码

    1、Controller

    @Controller
    public class TestController {
        // 测试布尔字面量
        @RequestMapping("boolean")
        public String testBoolean(Model model) {
            model.addAttribute("age", 100);
            model.addAttribute("boolean", true);
    
            return "boolean";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2、Html

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试布尔字面量title>
    head>
    <body>
        <p th:if="true">显示truep>
        <p th:if="${boolean}">model传递过来的truep>
        <p th:if="${age} eq 100">eqp>
        <p th:if="${age} == 100">==p>
        <p th:if="${age} > 20 ">大于p>
        <p th:if="${age} < 200">小于p>
        <p th:if="${boolean} and ${age} >= 100">小于等于100并且为truep>
        <p th:if="${boolean} and ${age} <= 100">大于等于100并且为truep>
        <p th:if="${age} != 100 or ${boolean}">不等于100或者truep>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    null
    概述

    null 字面量,在页面直接使用,也可以判断数据是否为null。当数据为null,标签和内容不显示。null字面量,在页面直接使用,也可以判断数据是否为null。当数据为null,标签和内容不显示。“” 字符串和 null 处理结果一样。

    案例代码

    1、Controller

    @Controller
    public class TestController {
        // 测试null字面量
        @RequestMapping("null")
        public String testNull(Model model) {
            model.addAttribute("value", null);
            model.addAttribute("string", "");
    
            return "null";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2、Html

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试null字面量title>
    head>
    <body>
        <p th:text="null">null:不显示p>
        <p th:text="${value}">value:不显示p>
        <p th:text="${string}">string:不显示p>
        <p th:if="${value} eq null">null值p>
        <p th:if="${string} eq ('')">使用括号显示空字符串p>
        <p th:if="${string} eq ''">显示空字符串p>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    逻辑字面量
    概述

    逻辑运算符:and(与)、or(或)、!(非),not(非)

    案例代码

    1、Controller

    @Controller
    public class TestController {
        // 测试null字面量
        @RequestMapping("null")
        public String testNull(Model model) {
            model.addAttribute("value", null);
            model.addAttribute("string", "");
    
            return "null";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2、Html

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试逻辑字面量title>
    head>
    <body>
        <p th:if="value">显示p>
        <p th:if="${!value}">!:不显示p>
        <p th:if="not ${value}">not:不显示p>
        <p th:if="not(null)">not(null):显示p>
        <p th:if="!null">!null:显示p>
        <p th:if="${num} > 0 and ${num} < 30">and:显示p>
        <p th:if="${num} > 0 or ${num} < 20">or:显示p>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    三元运算
    概述

    Thymeleaf中的三元运算与Java以及JavaScript中基本一致,如 A > B ? X : Y,在 X、Y 中可以继续嵌套,只是 Thymeleaf 中需要使用括号包含起来,否则报错。

    案例代码

    1、Controller

    @Controller
    public class TestController {
        // 测试三元运算符
        @RequestMapping("ternary")
        public String testTernary(Model model) {
            model.addAttribute("name", "易烊千玺");
            model.addAttribute("age", "20");
            model.addAttribute("gender", true);
    
            return "ternary";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2、Html

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试三元表达式title>
    head>
    <body>
        <p th:text="${name} eq '易烊千玺'">true | falsep>
        <p th:text="${name} eq '易烊千玺' ? '易烊千玺' : '迪丽热巴'">易烊千玺 | 迪丽热巴p>
        <p th:text="${name} eq '易烊千玺' ? (${age} < 20 ? '年轻' : '年老') : '迪丽热巴'">年轻 | 年老 | 迪丽热巴p>
        <p th:text="${gender} ? '' : ''">男 | 女p>
        <p th:text="${!gender} ? '' : ''">男 | 女p>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    Thymeleaf 常见属性

    【注意】Thymeleaf 属性用法和 HTML中的标签属性基本一致,一般情况下如果需要从后台获取数据,建议使用 Thymeleaf 属性

    常见属性
    属性描述
    th:value用于标签赋值,类似标签的 value 属性
    th:action定义后台控制器的路径,类似
    标签的 action 属性 ,主要结合 URL 表达式获取动态变量
    th:method设置请求方法类型
    th:href定义超链接,主要结合 URL 表达式,获取动态变量
    th:src用于外部资源引入,比如