ThymeLeaf概述
Thymeleaf是一种模板引擎,负责将前端html页面中的表达式解析出来,将后端封装好的数据填充到相应位置,最终输出页面
解析页面路径前缀:“classpath:/templates/”,后缀:".html"
导入ThymeLeaf依赖
<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring5 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
在html页面首部加入命名空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
使用样例
controller层
@RequestMapping("/t1")
public String test1(Model model){
//存入数据
model.addAttribute("msg","Hello,Thymeleaf");
//classpath:/templates/test.html
return "test";
}
html页面
<!--th:text就是将div中的内容设置为它指定的值,和之前学习的Vue一样-->
<div th:text="${msg}"></div>
th(ThymeLeaf)语法
通常用于:1.资源导入 2.填充后台数据
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-r4SUpKUM-1615815962534)(C:\Users\Redgoat\AppData\Roaming\Typora\typora-user-images\image-20210308171444624.png)]
SpringMVC配置
自定义MVC配置
实例——自定义视图解析器
@Configuration
public class myMVCConfig implements WebMvcConfigurer {
//ViewResolver,实现了视图解析器接口的类,就可以看做视图解析器
@Bean //放到bean中
public ViewResolver myViewResolver(){
return new MyViewResolver();
}
//我们写一个静态内部类,视图解析器就需要实现ViewResolver接口
private static class MyViewResolver implements ViewResolver{
@Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
}
}
在实现了WebMvcConfigurer的自定义配置类中写好相应组件,交给SpringBoot中即可
页面国际化——i18n
1.在idea中编写相关配置
2.编写按钮相关代码,实现页面语言切换
前端页面编写相应功能按钮
<--!语言切换按钮--!>
<a class="btn btn-sm" th:href="@{/index.html(lang='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(lang='en_US')}">English</a>
配置文件夹config下自定义地区解析器
//新建 "自定义地区解析器"
public class MyLocaleResolver implements LocaleResolver {
//解析语言切换请求
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
//获取请求中的语言参数
String language = httpServletRequest.getParameter("lang");
//获取到默认的地区的语言配置
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(language)){
//将字符串分割
String[] splitLocale = language.split("_");
//根据分割出的“ 国家 地区 ”信息创建Locale对象并将值传递给locale
locale = new Locale(splitLocale[0], splitLocale[1]);
}
return locale;
}
}
※ 在MyMvcConfig中注册相应组件到Spring中
public class MyMvcConfig implements WebMvcConfigurer {
//自定义的国际化组件,注入到spring中托管
@Bean
public LocaleResolver MyLocaleResolver(){
return new MyLocaleResolver();
}
}