1配置文件
login.properties
login.btn=登陆~ login.password=密码~ login.username=用户名~login_en_US.properties
login.btn=Sign In login.password=Password login.username=UserNamelogin_zh_CN.properties
login.btn=登陆 login.password=密码 login.username=用户名
2启动国际化(SpringBoot自动配置好了)
application.properties spring.messages.basename=i18n.login
2去页面获取国际化的值
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body class="text-center">
<form action="#" >
<label th:text="#{login.username}">username</label>
<input type="text" name="username">
<label th:text="#{login.password}">password</label>
<input type="password" name="password" >
<br>
<button type="submit" th:text="#{login.btn}">submit</button>
<br>
<a class="btn btn-sm" th:href="@{/login(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login(l='en_US')}">English</a>
</form>
</body>
</html>
当设置浏览器不同的语言时就有不同效果
2用户选择国际化
只要往容器中添加新的区域解析器就行
package feizhou.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送 /,/login 请求来到login.html
registry.addViewController("/").setViewName("login");
registry.addViewController("/login").setViewName("login");
}
// 设置自定义区域解析器,加载到容器中(关键看这里)
@Bean
public LocaleResolver localeResolver() {
// 区域解析器,加载到容器中
return new LocaleResolver() {
//解析url参数,生产区域对象
@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) {
}
};
}
}
点击中文/点击英文