新建Srpring Boot项目
引入thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.5.3</version>
</dependency>
项目配置application.yml
spring:
messages:
# 国际化文件名
basename: i18n/login
thymeleaf:
# 禁用thymeleaf缓存,否则热部署看不出效果
cache: false
# 设置编码格式
encoding: utf-8
server:
port: 8888
resources下添加i18n文件夹并添加登录配置文件:
templates文件夹下添加index.html文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>消息国际化</title>
</head>
<body>
<div>
<label th:text="#{login.username}">UserName</label>
<input th:placeholder="#{login.username}" placeholder="UserName">
<br>
<label th:text="#{login.password}">Password</label>
<input th:placeholder="#{login.password}" placeholder="Password">
<br>
<button th:text="#{login.btn}">Login</button>
<br>
<a class="btn btn-sm" th:href="@{/index(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index(l='en_US')}">English</a>
</div>
</body>
</html>
添加访问控制器IndexController
package com.whw.gjh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping
public class IndexController {
@GetMapping("/index")
public String index() {
return "index";
}
}
添加自定义语言环境解析并注入到容器
package com.whw.gjh.config;
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;
/**
* @描述 自定义语言解析器,解析header中的语言
**/
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l");
Locale locale = Locale.getDefault();
if (!StringUtils.isEmpty(l)) {
String[] split = l.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
注入容器
package com.whw.gjh.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
@Configuration
public class MyConfig {
@Bean
public LocaleResolver localeResolver() {
return new MyLocaleResolver();
}
}
配置热部署(非必须):
引入热部署依赖并配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
运行程序并访问:
切换语言: