springboot Thymeleaf模板引擎及国际化

Thymeleaf模板引擎及国际化

  • Thymeleaf是一种现代的基于服务器端的Java模板引擎技术,也是一个优秀的面向java的XML、XHTML、HTML5页面模板,具有丰富的标签语言、函数和表达式,在使用springboot框架进行页面设计时,一般会选择Thymeleaf模板。
  • 代码示例
<!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/gtvg.css" th:href="@{/css/gtvg.css}"/>
    <title>Title</title>
</head>
<body>
<p th:text="${hello}">Thymeleaf</p></body>
</html>
1. Thymeleaf语法
  • 常用标签
标签说明
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用于指定标签显示的文本内容
  • 标准表达式
表达式语法说明
${…}变量表达式
*{…}选择变量表达式
#{…}消息表达式
@{…}链接URL表达式
~{…}片段表达式
  1. 变量表达式${…},主要功能是获取上下文中的变量值
<p th:text="${title}">这是标题</p>

上面示例代码,如果上下文不存在title,会显示这是标题,如果存在会显示title对应的值,达到页面数据动态替换的效果

  • Thymeleaf为变量所在域提供的内置对象

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

  • 如下,可以使用#locale内置对象获取当前国家信息
The locale country is: <span th:text="${#locale.country}">US</span>
  1. 选择变量表达式*{…},
  • 从被选定对象而不是上下文中获取属性值,如果没有选定对象,和变量表达式一样,如下
<div th:object="${book}">
	<p>titile: <span th:text="*{title}"></span>.</p>
</div>
  1. 消息表达式#{…}
  • 主要用于Thymeleaf模板页面国际化内容的动态替换和展示
  1. 链接URL表达式@{…}
  • 一般用于页面跳转和资源引入
 <a th:href="@{http://localhost:8080/order/details(orderId=${o.id})}">view</a>
  <a th:href="@{/order/details(orderId=${o.id})}">view</a>
  1. 片段表达式~{…}
  • 用来标记一个片段模板,并根据需要移动或传递给其他模板,常见用法是使用th:insert或者th:replace属性插入片段,如下
<div th:insert="~{thymeleafDemo::title}"></div>

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

  • 表达式实用程序对象
#dates : 为 java.util.Date对象提供工具方法,比如:格式化,提取年月日等;
#calendars : 类似于#dates , 但是只针对java.util.Calendar对象;
#numbers : 为数值型对象提供工具方法;
#strings :为String 对象提供工具方法。如: contains, startsWith, prepending/appending等;
#objects : 为object 对象提供常用的工具方法;
#bools : 为boolean 对象提供常用的工具方法;
#arrays : 为arrays 对象提供常用的工具方法;
#lists :为lists对象提供常用的工具方法;
#sets : 为sets对象提供常用的工具方法;
#maps : 为maps对象提供常用的工具方法;
#aggregates :为创造一个arrays 或者 collections聚集函数提供常用的工具方法;
#messages :用于在变量表达式中获得外部消息的实用方法,与使用#{...}语法获得的方式相同;
#uris:用于在Thymeleaf标准表达式中执行URI / URL操作(特别是转义/消除转义)的实用对象;
#conversions:允许在模板的任意位置执行转换服务的实用程序对象;
#ids : 为可能需要循环的ID属性提供常用的工具方法。
2. thymeleaf基本使用
  1. 引入jar包
 <dependency>
	<groupId>org.springframework.boot</groupId> 
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
  1. 基本配置
spring.thymeleaf.cache = true				#启用模板缓存
spring.thymeleaf.encoding = UTF-8		#模板编码
spring.thymeleaf.mode = HTML5			#应用于模板的模板模式
spring.thymeleaf.prefix = classpath:/templates/	#指定模板页面路径  默认值: classpath:/templates/
spring.thymeleaf.suffix = .html			#指定模板名称后缀,默认值: .html
  1. springboot静态资源访问路径
    在这里插入图片描述
3. 简单使用
  • 创建Spring Boot项目,引入Thymeleaf依赖
    在这里插入图片描述

  • application.properties文件中配置spring.thymeleaf.cache=false,测试环境方便调试,正式环境设置为true

  • 创建controller

@创建Controller
public class LoginController {

    @RequestMapping("/toLoginPage")
    public String toLoginPage(Model model){
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "login";
    }
}
  • 创建模板页面
<!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>
  • 启动服务,可以看到页面底部动态显示的2020-2021,而不是静态文件中的2019-2020
4. 配置国际化页面
  1. 编写多语言配置文件
    在这里插入图片描述
  • 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
  1. 编写配置文件
# thymeleaf页面缓存设置
spring.thymeleaf.cache=false
#配置国际化文件基础名
spring.messages.basename=i18n.login
  1. 自定义区域信息解析器
@Configuration
public class MyLocaleResovle implements LocaleResolver {

    // 自定义 区域解析方式
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        // 获取页面手动传递的语言参数值l  : zh_CN  en_US  ''
        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();
    }
}
  1. 创建国际化页面及使用
<!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" 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>
  1. 效果测试
    在这里插入图片描述
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值