1.创建自己的国际化类
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;
/**
* 国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象);
* implements LocaleResolver
*/
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取页面请求的language值
String language = request.getParameter("language");
//先创建一个默认中文语言
Locale locale = Locale.getDefault();
//判断页面发送了什么语言的请求,并设置什么语言展示页面
//zh_CN 中文
//en_US 英文
if(!StringUtils.isEmpty(language)){
String[] split = language.split("_");
//创建语言类
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { }
}
2.扩展SpringMvc的功能,创建自己的国际化类加入容器
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
/*
implements WebMvcConfigurer 可以扩展SpringMVC的功能
*/
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//addViewController("浏览器发送请求").setViewName("请求要到的页面");
registry.addViewController("/index.html").setViewName("index.html");
}
//创建自己的国际化类加入容器
@Bean
public LocaleResolver localeResolver()
{
return new MyLocaleResolver();
}
}
3.html文件,application.properties文件,以及国际化配置文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>国际化</title>
</head>
<body>
<div th:text="#{home.username}"></div>
<div th:text="#{home.password}"></div>
<a class="btn btn-sm" th:href="@{/index.html(language='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(language='en_US')}">English</a>
</body>
</html>
4.使用了thymeleaf模板引擎
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
国际化配置文件
在这里插入图片描述