一、创建自定义MyLocaleResolver类
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
//国际化
public class MyLocaleResolver implements LocaleResolver{
private static final String I18N_LANGUAGE = "i18n_language";
private static final String I18N_LANGUAGE_SESSION = "i18n_language_session";
@Override
public Locale resolveLocale(HttpServletRequest req) {
String i18n_language = req.getParameter(I18N_LANGUAGE);
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(i18n_language)) {
String[] language = i18n_language.split("_");
locale = new Locale(language[0], language[1]);
//将国际化语言保存到session
HttpSession session = req.getSession();
session.setAttribute(I18N_LANGUAGE_SESSION, locale);
}else {
//如果没有带国际化参数,则判断session有没有保存,有保存,则使用保存的,也就是之前设置的,避免之后的请求不带国际化参数造成语言显示不对
HttpSession session = req.getSession();
Locale localeInSession = (Locale) session.getAttribute(I18N_LANGUAGE_SESSION);
if(localeInSession != null) {
locale = localeInSession;
}
}
return locale;
}
@Override
public void setLocale(HttpServletRequest req, HttpServletResponse res, Locale locale) {
}
}
二、创建配置类MyMvcConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
//国际化
@Configuration
public class MyMvcConfig {
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
三、application.properties文件配置
#国际化配置
spring.messages.basename=i18n.fwm
四、配置资源文件
五、进行请求访问,测试代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.ib{
display: inline-block;
}
.ml20{
margin-left: 20px;
}
.mt20{
margin-top: 20px;
}
</style>
</head>
<body>
<div>
<div>[[#{fwm.user.name}]]:<input th:placeholder="#{fwm.user.name}"/></div>
</div>
<div class="mt20">
<span class="ib"><a th:href="@{/m(i18n_language=zh_CN)}">中文</a></span>
<span class="ib ml20"><a th:href="@{/m(i18n_language=en_US)}">英文</a></span>
</div>
</body>
</html>