在一个Web应用中,通常会采用MVC设计模式实现对应的模型、视图和控制器,其中,视图是用户看到并与之交互的界面。对最初的Web应用来说,视图是由HTML元素组成的静态界面;而后期的Web应用更倾向于使用动态模板技术,从而实现前后端分离和页面的动态数据展示。Spring Boot框架为简化项目的整体开发,提供了一些视图技术支持,并主要推荐整合模板引擎技术实现前端页面的动态化内容。本文对SpringBoot常用的Thymeleaf进行整合。
Thymeleaf是一种现代的基于服务器端的Java模板引擎技术,也是一个优秀的面向Java的XML、XHTML、HTML5页面模板,它具有丰富的标签语言、函数和表达式,在使用Spring Boot框架进行页面设计时,一般会选择 Thymeleaf模板。我们在这里学习Thymeleaf 常用的标签、表达式。
Thymeleaf标签
| th:标签 | 说明 |
|---|---|
| th:insert | 页面片段包含(类似JSP中的include标签) |
| th:replace | 页面片段包含(类似JSP中的include标签) |
| th:each | 元素遍历(类似JSP中的c:forEach标签) |
| th:if | 条件判断,条件成立时显示th标签内容 |
| th:unless | 条件判断,条件不成立时显示内容 |
| th:switch | 条件判断,进行选择性匹配 |
| th:case | th:switch分支,选择的元素 |
| th:object | 用于替换对象 |
| th:with | 用于定义局部遍历 |
| th:attr | 用于属性修改 |
| th:attrprepend | 通用属性修改,将计算结果追加前缀到现有属性值 |
| th:attrappend | 通用属性修改,将计算的结果追加后缀现有属性值 |
| th:value | 属性值修改,指定标签属性值 |
| th:href | 用于设定链接地址 |
| th:src | 用于设定链接地址 |
| th:text | 用于指定标签显示文本内容 |
| th:utext | 用于指定标签显示内容,对特殊标签不转译 |
| th:fragment | 声明片段 |
| th:removve | 移除片段 |
使用标签只需要加上一个命名空间就可以了。<html lang="en" xmlns:th="http://thymeleaf.org"> 即修改原html的第二行就可以了。
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"> <head> <title>Good Thymes Virtual Grocery</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" media="all" href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" /> </head> <body> <p th:text="#{home.welcome}">Welcome to our grocery store!</p> </body></html>| 表达式 | 说明 |
|---|---|
| ${..} | 变量表达式 |
| *{..} | 选择变量表达式 |
| #{..} | 消息表达式 |
| @{..} | 链接URL表达式 |
| ~{..} | 片段表达式 |
变量表达式${..}主要用于获取上下文中的变量值,示例代码如下。
这是标题
- 使用了Thymeleaf模板的变量表达式${..}用来动态获取p标签中的内容- 如果当前程序没有启动或者当前上下文中不存在title变量,该片段会显示标签默认值“这是标题”;- 如果当前上下文中存在title 变量并且程序已经启动,当前p标签中的默认文本内容将会被tite变量的值所替换,从而达到模板引擎页面数据动态替换的效果。Thymeleaf为变量所在域提供了一些内置对象
| 内置对象 | 说明 |
|---|---|
| #ctx | 上下文对象 |
| #vars | 上下文变量 |
| #locale | 上下文区域设置 |
| #request | (仅限 Web Context)HttpServletRequest 对象 |
| #response | (仅限Web Context)HttpServletResponse 对象 |
| #session | 仅限Web Context) HttpSession对象 |
| #servletContext | (仅限 Web Context)ServletContext 对象 |
结合上述内置对象的说明,假设要在Thymeleaf模板擎页面中动态获取当前国家信息,可以使用#locale内置对象
<span th:text="${#locale.country}">China</span>选择交量表达式和变量表达式用法类似,一般用于从被选定对象而不是上下文中获取属性值,如果没有选定对象,则和变量表达式一样,示例代码如下。
<div th:object="$(session.user)"> <p>Name: <span th:text="s(object.firstName)">Sebastiahk</span></p> <p>username:<span th:text="$(session.user,lastName)">Pepper</span></p> <p>Nationality:<span th:text="*(nationality)">Saturn</span>.</p> </div>消息表达式#{..}主要用于Thymeleaf模板页面国际化内容的动态替换和展示。使用消息表这式#{..}进行国际化设置时,还需要提供一些国际化配置文件。关于消息表达式的使用,下文写国际化时会详细说明。
链接表达式@{..}一般用于页面跳转或者资源的引入,在Web开发中占据着非常重要的地位,并且使用也非常频繁。
<a href="details.html" th:href="@{http:localhost:8080/gtvg/order/details(order=$o.id})}">view</a><a href="details.html" th:href="@{/order/details(order=$o.id})}">view</a>片段表达式~{..}是一种用来将标记片段移动到模板中的方法。其中,最常见的用法是使用th:insert或th:replace 属性插入片段
<div th:insert="~(thymeleafDemo::title】"></div>Spring Boot默认设置了静态资源的访问路径,默认将/**所有访问映射到以下目录。
我们创建一个springboot项目用于本次实验。项目名为springboot_01_thyme。java8,springboot2.6.6
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency># thymeleaf cachespring.thymeleaf.cache=falsespring.thymeleaf.encoding=utf-8spring.thymeleaf.mode=HTML5spring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.html创建一个LoginController类用于数据替换效果测试。
package com.hjk.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import java.util.Calendar;@Controllerpublic class LoginController { @GetMapping("toLoginPage") public String toLoginPage(Model model){ model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR)); return "login"; }}我们写一个login.html进行测试。我们导入一个bootstrap的样式到static/login里面,并且自己定义一些css。
<!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"> <style type="text/css"> html, body { height: 100%; } body { align-items: center; padding-top: 40px; padding-bottom: 40px; background-color: greenyellow; } .form-signin { width: 100%; max-width: 330px; padding: 15px; margin: 0 auto; } </style></head><body ><!-- 用户登录form表单 --><form > <h1 >请登录</h1> <input type="text" placeholder="用户名"> <input type="password" placeholder="密码"> <div> <label> <input type="checkbox" value="remember-me"> 记住我 </label> </div> <button type="submit">登录</button> <p >? <span th:text="${currentYear}">2018</span>-<span th:text="${currentYear}+1">2019</span></p></form></body></html>xmlns:th="http://thymeleaf.org"引入Thymeleaf标签最后我们通过访问http://localhost:8080/toLoginPage 可以查看效果
在resources目录下创建名为i18n的文件夹,数一数这个单词多少个字母internationalization,就知道为什么叫i18n了。
然后我们在i18n文件夹下面创建login.properties、 login_zh_CN.properties、 login_en_US.properties文件。
目录结构:这个Resource Bundle 'login'时idea自动创建的,我们不需要管,只需要完成我们的就行。
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 inlogin.username=Usernamelogin.password=Passwordlogin.rememberme=Remembermelogin.button=Login然后我们在配置文件application.properties里面添加代码
spring.messages.basename=i18n.login我们在config包下面创建一个MyLocalResovel类,自定义国际化功能区域信息解析器。
package com.hjk.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.util.StringUtils;import org.springframework.web.servlet.LocaleResolver;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.Locale;@Configurationpublic class MyLocalResovel implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { String parameter = request.getParameter("1"); String header = request.getHeader("Accept-Language"); Locale locale = null; if (!StringUtils.isEmpty(parameter)){ String[] s = parameter.split("_"); locale = new Locale(s[0], s[1]); }else{ String[] split = header.split(","); String[] split1 = split[0].split("-"); locale = new Locale(split1[0],split1[1]); } return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { } @Bean public LocaleResolver localeResolver(){ return new MyLocalResovel(); } }<!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"> <style type="text/css"> html, body { height: 100%; } body { align-items: center; padding-top: 40px; padding-bottom: 40px; background-color: greenyellow; } .form-signin { width: 100%; max-width: 330px; padding: 15px; margin: 0 auto; } </style></head><body ><!-- 用户登录form表单 --><form > <h1 th:text="#{login.tip}">请登录</h1> <input type="text" th:placeholder="#{login.username}"> <input type="password" th:placeholder="#{login.password}" \> <div> <label> <input type="checkbox" value="remember-me"> [[#{login.rememberme}]] </label> </div> <button type="submit" th:text="#{login.button}">登录</button> <p >? <span th:text="${currentYear}">2018</span>-<span th:text="${currentYear}+1">2019</span></p> <a th:href="@{/toLoginPage(1='zh_CN')}">中文</a> <a th:href="@{/toLoginPage(1='en_US')}">English</a></form></body></html>这里我们基本就完成了,但是在访问中文的时候会出现乱码现象。
我们打开idea的file->settings->file Encodings.
将Default encoding for properties的编码改为utf-8,同时勾选Transparentnative-to-ascii conversion
然后我们重新编写login.properties和其他相关的
login.tip=请登录login.username=用户名login.password=密码login.rememberme=记住我login.button=登录但是这种方法1只对当前项目有效。下次创建还是使用GBK编码
本文我们主要了解了Thymeleaf的基本语法、标签、表达式、基本使用、同时还实现了页面登录页得国际化。
....