Springboot i18n 国际化
1.在资源目录下新建文件夹i18n
2.以页面开头,创建一个properties,例如:hello.properties
3. 创建hello_zh_CN.properties
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iPtxWuxG-1582526307300)(C:\Users\chang\AppData\Roaming\Typora\typora-user-images\image-20200224141828260.png)]
4.实现resolveLocale方法
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;
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 httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
5.将自己实现的地区解析器注入到spring容器
Spring 5.0后,WebMvcConfigurerAdapter被废弃,取代的方法有两种:
①implements WebMvcConfigurer(官方推荐)
②extends WebMvcConfigurationSupport
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.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
5.thymeleaf取值
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>国际化</title>
</head>
<body>
通过springMVC的LocaleResolver 地区解析器
<a th:href="@{/hello(l='zh_CN')}">中</a>
<a th:href="@{/hello(l='en_US')}">en</a>
<h1 th:text="#{hello.msg}"></h1>
</body>
</html>