SpringBoot之Thymeleaf 一条龙服务

1,150 阅读5分钟

SpringBoot视图技术之Thymeleaf

1 支持的视图技术

Spring Boot框架对很多常用的模板引擎技术(如:FreeMarker、Thymeleaf、Mustache等)提供了整合支持

2 Thymeleaf

1 Thymeleaf语法

常用标签

在HTML页面上使用Thymeleaf标签,Thymeleaf 标签能够动态地替换掉静态内容,使页面动态展示。

th:标签说明
th:insert布局标签,替换内容到引入的文件
th:replace页面片段包含(类似JSP中的include标签)
th:each元素遍历(类似JSP中的c:forEach标签)
th:if条件判断,如果为真
th:unless条件判断,如果为假
th:switch条件判断,进行选择性匹配
th:case条件判断,进行选择性匹配
th:value属性值修改,指定标签属性值
th:href用于设定链接地址
th:src用于设定链接地址
th:text用于指定标签显示的文本内容

标准表达式

Thymeleaf模板引擎提供了多种标准表达式语法

说明表达式语法
变量表达式${...}
选择变量表达式*{...}
消息表达式#{...}
链接URL表达式@{...}
片段表达式~{...}

1.变量表达式 ${...}

Thymeleaf为变量所在域提供了一些内置对象,具体如下所示

# ctx:上下文对象
# vars:上下文变量
# locale:上下文区域设置
# request:(仅限Web Context)HttpServletRequest对象
# response:(仅限Web Context)HttpServletResponse对象 
# session:(仅限Web Context)HttpSession对象
# servletContext:(仅限Web Context)ServletContext对象

结合上述内置对象的说明,假设要在Thymeleaf模板引擎页面中动态获取当前国家信息,可以使用 #locale内置对象,示例代码如下

The locale country is: <span th:text="${#locale.country}">US</span>.

2.选择变量表达式 *{...}

示例代码如下

<div th:object="${book}">
<p>titile: <span th:text="*{title}">标题</span>.</p>
</div>

3.消息表达式 #{...}

进行国际化设置时

4.链接表达式 @{...}

链接表达式@{...}一般用于页面跳转或者资源的引入,在Web开发中占据着非常重要的地位,并且使用也非常频繁,示例代码如下:

<a  th:href="@{http://localhost:8080/order/details(orderId=${o.id})}">view</a>
<a  th:href="@{/order/details(orderId=${o.id})}">view</a>

5.片段表达式 ~{...}

片段表达式~{...}用来标记一个片段模板,并根据需要移动或传递给其他模板。其中,最常见的用法是使用th:insert或th:replace属性插入片段,示例代码如下:

<div th:insert="~{thymeleafDemo::title}"></div>

thymeleafDemo为模板名称,Thymeleaf会自动查找“/resources/templates/”目录下的thymeleafDemo模板,title为片段名称

2 基本使用

(1) Thymeleaf模板基本配置

首先 在Spring Boot项目中使用Thymeleaf模板,首先必须保证引入Thymeleaf依赖,示例代码如 下:

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

其次,在全局配置文件中配置Thymeleaf模板的一些参数。一般Web项目都会使用下列配置,示例代码 如:

spring.thymeleaf.cache = true #启用模板缓存 
spring.thymeleaf.encoding = UTF-8 #模板编码
spring.thymeleaf.mode = HTML5 #应用于模板的模板模式 
spring.thymeleaf.prefix = classpath:/templates/ #指定模板页面存放路径 
spring.thymeleaf.suffix = .html #指定模板页面名称的后缀

(2) 静态资源的访问

开发Web应用时,难免需要使用静态资源。Spring boot默认设置了静态资源的访问路径。

使用Spring Initializr方式创建的Spring Boot项目,默认生成了一个resources目录,在resources目录 中新建public、resources、static三个子目录下,Spring boot默认会挨个从public、resources、static 里面查找静态资源

3 代码实现

  1. 创建Spring Boot项目,引入Thymeleaf依赖

    <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.xiewz</groupId>
        <artifactId>springboot04_thymeleaf</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>springboot04_thymeleaf</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>11</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
  2. 创建项目

    创建Spring Initializr项目

    image20210116195628697.png

    image20210116195652611.png

    image20210116195758992.png

  3. 编写配置文件

    # thymeleaf页面缓存设置(默认为true),开发中方便调试应设置为false,上线稳定后应保持默 认true
    spring.thymeleaf.cache=false
    
  4. 创建web控制类

    /**
     * 获取并封装当前年份跳转到登录页login.html
     */
    @RequestMapping("/toLoginPage")
    public String toLoginPage(Model model) {
    
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "login";
    }
    
  5. 创建模板页面并引入静态资源文件

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1,shrink-
    to-fit=no">
        <title>用户登录界面</title>
        <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
        <link th:href="@{/login/css/signin.css}" rel="stylesheet">
    </head>
    <body class="text-center"> <!-- 用户登录form表单 -->
    <form class="form-signin">
        <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
        <h1 class="h3 mb-3 font-weight-normal">请登录</h1>
        <input type="text" class="form-control"
               th:placeholder="用户名" required="" autofocus=""> <input type="password" class="form-control"
                                                                     th:placeholder="密码" required="">
        <div class="checkbox mb-3">
            <label>
                <input type="checkbox" value="remember-me"> 记住我
            </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
        <p class="mt-5 mb-3 text-muted">© <span
                th:text="${currentYear}">2019</span>-<span
                th:text="${currentYear}+1">2020</span></p>
    </form>
    </body>
    </html>
    
  6. 测试效果

    输入URL:http://localhost:8080/toLoginPage

    image20210116211030901.png

4 国际化页面配置

1.编写多语言国际化配置文件

在项目的类路径resources下创建名称为i18n的文件夹,并在该文件夹中根据需要编写对应的多语 言国际化文件login.properties、login_zh_CN.properties和login_en_US.properties文件

login.properties

login.tip=请登录 
login.username=用户名 
login.password=密码 
login.rememberme=记住我 
login.button=登录

login_zh_CN.properties

login.tip=请登录 
login.username=用户名 
login.password=密码 
login.rememberme=记住我 
login.button=登录

login_en_US.properties

login.tip=Please sign in
login.username=Username
login.password=Password
login.rememberme=Remember me
login.button=Login

Spring Boot默认识别的语言配置文件为类路径resources下的 messages.properties;其他语言国际化文件的名称必须严格按照“文件前缀名 国家代码.properties”的形式命名

2. 编写配置文件

application.properties全局配置文件中添加

# 配置国际化文件基础名 
spring.messages.basename=i18n.login

此时页面还能正常显示

不过这种实现方式默认是使用请求头中的语言信息(浏览器语 言信息)自动进行语言切换的

3. 定制区域信息解析器

实现手动语言切换的功能,先添加标签用于切换语言

<a class="btn btn-sm" th:href="@{/toLoginPage(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/toLoginPage(l='en_US')}">English</a>

在项目中创建名为com.xiewz.config的包,并在该包下创建一个用于定制国际化功能区域信息解析 器的自定义配置类MyLocalResovel

@Configuration
public class MyLocaleResovle implements LocaleResolver {
    // 自定义 区域解析器  覆盖默认解析器
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        // 获取页面手动传递的语言参数值l
        String l = httpServletRequest.getParameter("l");
        Locale locale = null;
        if(!StringUtils.isEmpty(l)){
            // 如果参数不为空,就根据参数值进行手动语言切换
            String[] s = l.split("_");
            locale = new Locale(s[0],s[1]);
        }else {
            //Accept-Language: zh-CN ,zh;q=0.9
            String header = httpServletRequest.getHeader("Accept-Language");
            String[] split = header.split(",");
            String[] split1 = split[0].split("-");
            locale = new Locale(split1[0],split1[1]);
        }


        return locale;

    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }

    // 将自定义的MyLocaleResovle重新注册成一个类型为LocaleResolver的bean组件
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResovle();
    }
}

4. 页面国际化使用

在标签中添加属性如:th:text="#{login.tip}表示使用国际化配置文件的文字

标签外部的需要用中括号替换文字,如:[[#{login.rememberme}]]

替换后如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,shrink-
to-fit=no">
    <title>用户登录界面</title>
    <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/login/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center"> <!-- 用户登录form表单 -->
<form class="form-signin">
    <img class="mb-4" th:src="@{/login/img/login.png}" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">请登录</h1>
    <input type="text" class="form-control"
           th:placeholder="#{login.username}" required="" autofocus="">
    <input type="password" class="form-control"
           th:placeholder="#{login.password}"
           required="">
    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me"> [[#{login.rememberme}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.button}">登录</button>
    <p class="mt-5 mb-3 text-muted">©
        <span th:text="${currentYear}">2019</span>-
        <span th:text="${currentYear}+1">2020</span>
    </p>
    <a class="btn btn-sm" th:href="@{/toLoginPage(l='zh_CN')}">中文</a>
    <a class="btn btn-sm" th:href="@{/toLoginPage(l='en_US')}">English</a>
</form>
</body>
</html>

5. 整合效果测试

点击下方English可以切换到英文模式了

image20210116213028918.png