• SpringBoot(二)视图


    Thymeleaf是一种现代的基于服务器端的Java 模板引擎技术,也是一个优秀的面向Java的XML、XHTML、HTML5页面模板,它具有丰富的标签语言、函数和表达式,在使用Spring Boot框架进行页面设计时,一般会选择Thymeleaf模板

    1 语法

    1.1 常用标签

    在HTML页面上使用Thymleaf标签,Thymleaf标签能够动态地替换掉静态内容,使页面动态展示。
    为了大家更直观的认识Thymeleaf,下面展示了一个在HTML文件中嵌入Thymeleaft的页面文件,示例代码如下:

    DOCTYPE HTML>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
    	<meta charset="UTF-8">
    	<link rel="stylesheet" type="text/css" media="all" href="../../css/xx.css" th:href="@{/css/xx.css}"/>
    	<title>Titletitle>
    head>
    <body>
    	<p th:text="${hello}">欢迎学习Thymleafp>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    上述代码中,“xmlns:th=“http://www.thymeleaf.org””用于引入Thymeleaf模板引擎标签,使用关键字”th“标注标签是Thymeleaf模板提供的标签,其中,”th:href“用于引入外部样式文件,”th:text“用于动态显示标签文本内容。
    除此之外,Thymeleaf模板提供了很多标签,接下来,通过一张表格展示Thymeleaf常用标签

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

    1.2 标准表达式

    Thymeleaf模板引擎提供了多种标准表达式语法,接下来,通过一张表格展示其主要语法及说明

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

    1.2.1 变量表达式 ${…}

    变量表达式${…}主要用于获取上下文中的变量值,示例代码如下:

    <p th:text=${title}>这是一个标题p>
    
    • 1

    示例中使用了Thymeleaf模板的变量表达式${…}用来动态获取P标签中的内容,如果当前程序没有启动或者当前上下文中不存在title变量,该片段会显示标签默认值”这是一个标题“;如果当前上下文中存在title变量并且程序已经启动,当前P标签中的默认文本内容将会被title变量的值所替换,从而达到模板引擎页面数据动态替换的效果。
    通过Thymeleaf为变量所在域提供了一些内置对象,具体如下所示

    #ctx:上下文对象
    #vars:上下文变量
    #local:上下文区域设置
    #request:【仅限Web Context】HttpServletRequest对象
    #response:【仅限Web Context】HttpServletResponse对象
    #session:【仅限Web Context】HttpSession对象
    #servletContext:【仅限Web Context】HttpServletContext对象
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

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

    The locale country is <span th:text="${#locale.country}">USspan>
    
    • 1

    上述代码中,使用th:text="${#locale.country}"动态获取当前用户所在的国家信息,其中span标签内默认内容为US,程序启动后通过浏览器查看当前页面时,Thymleaf会通过浏览器语言设置来识别当前用户所在国家信息,从而实现动态替换。

    1.2.2 选择变量表达式 *{…}

    选择变量表达式和变量表达式用法类似,一般用于从被选定对象而不是上下文中获取属性值,如果没有选定对象,则和变量表达式一样,示例代码如下

    <div th:object="${book}">
    	<p>title: <span th:text="*{title}">标题span>p>
    div>
    
    • 1
    • 2
    • 3

    *{title}选择变量表达式获取当前指定对象book的title属性值。

    1.2.3 消息表达式 #{…}

    消息表达式#{…}主要用于Thymeleaf模板页面国际化内容的动态替换和展示,使用消息表达式#{…}进行国际化设置时,还需要提供一些国家化配置文件,关于消息表达式的使用,我们在4 国际化中做详细说明

    1.2.4 链接表达式 @{…}

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

    <a th:href="@{http://localhost:8443/order/details{orderId=${o.id}}}">viewa>
    <a th:href="@{/order/details{orderId=${o.id}}}">viewa>
    
    • 1
    • 2

    上述代码中,链接表达式@{…}分别编写了绝对链接地址和相对链接地址。在有参表达式中,需要按照@{路劲{参数名=参数值,参数名=参数值…}}的形式编写,同时改参数的值可以使用变量表达式来传递动态参数值。

    1.2.5 片段表达式 ~{…}

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

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

    上述代码中,使用th:insert属性将title片段模板引用到该div标签中。thymeleafDemo为模板名称,Thymeleaf会自动查找”/resources/templates/“目录下的thymeleafDemo模板,title为片段名称

    2 基本使用

    1. Thymeleaf模板基本配置
      首先,在Spring Boot项目中使用Thymeleaf模板,必须保证引入Thymeleaf依赖,示例代码如下:
    <dependency>
    	<groupId>org.springframework.bootgroupId>
    	<artifactId>spring-boot-starter-thymeleafartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4

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

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

    上述配置中,cache表示是否开启Thymeleaf模板缓存,默认为true,在开发过程中通常会关闭缓存,保证项目调试过程中数据能够及时响应;prefix指定了Thymeleaf模板页面的存放路径,默认为classpath:/templates/;suffix指定了Thymeleaf模板页面的名称后缀,默认为.html

    1. 静态资源的访问
      开发Web应用时,难免需要使用静态资源。Spring Boot默认设置了静态资源的访问路径。
      使用Spring Initializr方式创建Spring Boot项目,默认生成了一个resouces目录,在resources目录中新建public、resources、static三个子目录下,Spring Boot默认会挨个从public、resources、static里面查询静态资源

    3 数据展示

    1. 创建一个Spring Boot项目,并引入Thymeleaf依赖。(不会自行麻烦搜索)
    2. 编写配置文件
      打开application.yml全局配置文件,在该文件中对Thymeleaf模板页面的数据缓存进行默认设置
    spring:
      thymeleaf:
        cache: false # thymeleaf页面缓存设置(默认为true),开发中方便调试代码设置为false。
    
    • 1
    • 2
    • 3
    1. 创建Web控制类
      在项目中创建名为com.lxsh.controller的包,并在该包下创建一个用于前端模板页面动态数据替换效果测试的访问实体类LoginController
    @Controller
    public class LoginController{
    	/**
    	 * 获取当前时间并跳转到登录页面
    	 */
    	@RequestMapping("/loginPage")
    	public String loginPage(Model model){
    		model.addAttribute("currentTime",LocalDateTime.now());
    		return "login";
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    loginPage()方法用于向登录页面login.html跳转,同时携带了当前时间currentTime。

    1. 创建模板页面并引入静态资源文件
      在“classpath:/templates/”目录下引入一个用于登录的模板页面login.html
    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>
    	<form>
    		<h1>请登录h1>
    		<input type="text" th:placeholder="用户名" required="" autofocus=""/>
    		<input type="password" th:placeholder="密码" required=""/>
    		<button type="submit">登录button>
    		<p>当前时间:<span th:text="${currentTime}">2022-02-30 10:30:00span>p>
    	form>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    通过“xmlns:th=“http://www.thymeleaf.org””引入了Thymeleaf模板标签
    使用“th:href”引入了两个外联样式文件
    使用“th:text”引入了后台动态传递过来的当前时间currentTime

    1. 效果测试
      在这里插入图片描述

    4 国际化

    4.1 多语言国际化配置文件

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

    login.tip=请登录
    login.username=用户名
    login.password=密码
    login.buttom=登录
    
    • 1
    • 2
    • 3
    • 4

    login_zh_CN.properties

    login.tip=请登录
    login.username=用户名
    login.password=密码
    login.buttom=登录
    
    • 1
    • 2
    • 3
    • 4

    login_en_US.properties

    login.tip=Please sign in
    login.username=Username
    login.password=Password
    login.buttom=Login
    
    • 1
    • 2
    • 3
    • 4

    login.properties为自定义默认语言配置文件,login_zh_CN.properties为自定义中文国际化文件,login_en_US.properties为自定义英文国际化文件
    需要说明的是,Spring Boot默认识别的语言配置文件为类路径resources下的message.properties;其他语言国际化文件的名称必须严格按照“文件前缀名_语言代码_国家代码.properties”的形式命名
    本示例中,在项目类路径resources下自定义了一个i18n包用于统一配置管理多语言配置文件,并将项目默认语言配置文件名自定义为login.properties,因此,后续还必须在项目全局配置中进行国际化文件基础名配置,才能引用自定义国际化文件

    4.2 编写配置文件

    在application.yml全局配置文件中,添加国际化文件基础名设置。

    spring:
      thymeleaf:
        cache: false # thymeleaf页面缓存设置(默认为true),开发中方便调试代码设置为false。
      messages:
        basename: i18n.login # 配置国际化文件基础名
    
    • 1
    • 2
    • 3
    • 4
    • 5

    “spring.messages.basename=i18n.login”设置了自定义国际化文件的基础名。其中,i18n表示国际化文件相对项目类路径resources的位置,login表示多语言文件的前缀名。如果开发者完全按照Spring Boot默认识别机制,在项目类路径resources下编写messages.properties等国际化文件,可以省略国际化文件基础名的配置

    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>
    	<form>
    		<h1 th:text="#{login.tip}">请登录h1>
    		<input type="text" th:placeholder="#{login.username}" required="" autofocus=""/>
    		<input type="password" th:placeholder="#{login.password}" required=""/>
    		<button type="submit" th:text="#{login.buttom}">登录button>
    		<p>当前时间:<span th:text="${currentTime}">2022-02-30 10:30:00span>p>
    	form>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    4.3 定制区域信息解析器

    在完成上一步中多语言国际化文件的编写和配置后,就可以正式在前端页面中结合Thymeleaf模板相关属性进行国际化语言设置和展示,不过这种实现方式默认是使用请求头中的语言信息(浏览器语言信息)自动进行语言切换的,有些项目还会提供手动语言切换的功能,这就需要定制区域解析器了
    在项目中创建名为com.lxsh.config的包,并在该包下创建一个用于定制国家化功能区域信息解析器的自定义配置类MyLocaleResolver

    @Configuration
    public class MyLocaleResolver implements LocaleResolver {
    	//自定义区域解析器
    	@Override
    	public Locale resolveLocale(HttpServletRequest httpServletRequest){
    		//获取页面手动切换传递的语言参数
    		String language = httpServletRequest.getParameter("language");
    		//获取请求头自动传递的语言参数 Accept-Language
    		String header = httpServletRequest.getHeader("Accept-Language");
    		Locale locale = null;
    		//如果手动切换参数不为空,就根据手动参数进行语言切换,否则默认根据请求头信息切换
    		if(StringUtils.isNotEmpty(language)){
    			String[] split = language.split("_");
    			locale = new Locale(split[0],split[1]);
    		} else {
    			String[] headers= header.split(",");
    			String[] split = headers.split("-");
    			locale = new Locale(split[0],split[1]);
    		}
    		return locale;
    	}
    
    	//将自定义的MyLocaleResolver重新注册成一个类型为LocaleResolver的Bean组件
    	@Bean
    	public LocaleResolver localeResolver(){
    		return new MyLocaleResolver();
    	}
    }
    
    • 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

    页面添加中英文切换功能

    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>
    	<form>
    		<h1 th:text="#{login.tip}">请登录h1>
    		<input type="text" th:placeholder="#{login.username}" required="" autofocus=""/>
    		<input type="password" th:placeholder="#{login.password}" required=""/>
    		<button type="submit" th:text="#{login.buttom}">登录button>
    		<p>当前时间:<span th:text="${currentTime}">2022-02-30 10:30:00span>p>
    	form>
    	<a th:href="@{/loginPage(language='zh_CN')}">中文a>
    	<a th:href="@{/loginPage(language='en_US')}">Englisha>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  • 相关阅读:
    JavaScript正则表达式基础
    openEuler 亮相全球顶级开源盛会 OSSUMMIT 2023,持续推动智能化未来的实现
    毕业设计 基于单片机的智能盲人头盔系统 - 导盲杖 stm32
    react-router-dom6 路由懒加载与组件懒加载
    C++_多态
    JVM吞吐量与延迟关系
    Android自定义控件(三) 自定义FlowLayout
    CentOS部署Skywalking
    uniapp h5使用原生的input标签
    java计算机毕业设计分数线查询系统(0)源码+mysql数据库+系统+lw文档+部署
  • 原文地址:https://blog.csdn.net/weixin_44152160/article/details/126210772