SpringBoot中Thymeleaf的基本使用

SpringBoot中Thymeleaf的基本使用

引入依赖:

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

基本配置:

spring:
  thymeleaf:
  	#是否启用模板缓存,默认true,开发时通常会关闭以保证调试数据及时响应
    cache: false
    encoding: UTF-8 #模板编码
    #前缀(文件路径) 默认classpath:templates/
    prefix: classpath:templates/
    suffix: .html #后缀(文件格式) 默认.html
    mode: HTML5   #模板模式

1. 基本语法

Thymeleaf能动态的替换掉静态内容,动态显示页面内容。

引入Thymeleaf模板引擎:xmlns:th="http://www.thymeleaf.org"

Thymeleaf常用标签

th:标签说明
th:insert页面片段包含
th:replace页面片段包含
th:each元素遍历
th:if条件判断,成立时显示标签内容
th:unless条件判断,条件不成立时显示th标签的内容
th:switch条件判断,进行选择性判断
th:caseth:switch分支的条件判断
th:object用于替换对象
th:with用于定义局部变量
th:attr通过属性修改
th:attrprepend通过属性修改,将计算结果追加前缀到现有属性值
th:attrappend通过属性修改,将计算结果追加后缀到现有属性值
th:value属性值修改,指定标签属性值
th:href用于设定链接地址
th:src用于设定链接地址
th:text用于指定标签显示的文本内容
th:utext用于指定标签显示的文本内容,对特殊标签不转义
th:fragment声明片段
th:remove移除片段

注:HTML5规范不允许th:*属性,使用时需替换成data-th-*

行内表达式[[]],如[[${student.name}]]

标准表达式

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

内置对象

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

2. 在SpringBoot中的使用

SpringBoot中默认会依次从resource目录下新建的public、resource、static查找静态资源,也会查找classpath:/META-INF/resources/下的所有文件。

国际化页面的案例:

  1. 创建国际化文件

    login.properties

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

    login_zh_CN.properties

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

    login_en_US.properties

    login.button=Login
    login.password=Password
    login.rememberme=Remember me
    login.tip=Please sign in
    login.username=Username
    
  2. 配置文件

    application.yml

    spring:
      messages:
        basename: i18n.login #配置国际化文件基础名
    
  3. 自定义国际化功能区域信息解析器

    package org.example.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.LocaleResolver;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.util.Locale;
    
    /**
     * 自定义国际化功能区域信息解析器
     * @author wyp
     */
    @Configuration
    public class MyLocaleResolver implements LocaleResolver {
    
        /**
         * 自定义区域解析方式
         */
        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            Locale locale = null;
            // 获取语言传递参数
            String language = request.getParameter("l");
            // 请求头方式获取语言传递参数
            String header = request.getHeader("Accept-Language");
            if (language != null && !"".equals(language)) {
                //l=zh_CN
                String[] split = language.split("_");
                locale = new Locale(split[0],split[1]);
            }else {
                //Accept-Language:en-US,en;q=0.9,zh-CN,q=0.8,zh;q=0.7
                String[] splits = header.split(",");
                String[] split = splits[0].split("-");
                locale = new Locale(split[0],split[1]);
            }
            return locale;
        }
    
        @Override
        public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    
        }
    
        /**
         * 将自定义的MyLocaleResolver类重新注册为一个类型为LocaleResolver的Bean组件
         */
        @Bean
        public LocaleResolver localeResolver() {
            return new MyLocaleResolver();
        }
    }
    
  4. 前端页面国际化使用

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>登录页</title>
    </head>
    <body>
    <div>
        <div style="width: 500px;margin: 200px auto;border: 2px gray solid;text-align: center">
            <h2>[[#{login.tip}]]</h2>
            <label>
                <input type="text" th:placeholder="#{login.username}">
            </label><br>
            <label>
                <input type="text" th:placeholder="#{login.password}">
            </label>
            <div>
                <label>
                    <input type="checkbox" value="remember-me">
                </label>[[#{login.rememberme}]]
            </div>
            <button th:text="#{login.button}"></button>
            <br><br>
            <a th:href="@{/toLoginPage(l='zh_CN')}">中文</a>
            <a th:href="@{/toLoginPage(l='en_US')}">English</a>
            <br><br>
            <p>&copy; [[${date}]]</p>
        </div>
    </div>
    </body>
    </html>
    
  5. 控制层实现页面访问

    package org.example.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    
    @Controller
    public class LoginController {
    
        @GetMapping("/toLoginPage")
        public String toLoginPage(Model model) {
            model.addAttribute("date","2018-2022");
            return "Login";
        }
    }
    

成功实现中英文的切换。

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小辰~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值