springboot国际化
最近在看B站的springboot学习视频,讲的挺好的,源码分析的部分也不少,不过目前比较菜,先学会怎么用就好了
html页面
想实现的效果
点击中文显示这样,English显示英文输入
具体步骤
-
编写国际化配置文件
-
使用ResourceBundleMessageSource管理国际化资源文件
在springboot中,已经自动配置好了国际化组件,
```@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
/**
* Comma-separated list of basenames (essentially a fully-qualified classpath
* location), each following the ResourceBundle convention with relaxed support for
* slash based locations. If it doesn't contain a package qualifier (such as
* "org.mypackage"), it will be resolved from the classpath root.
*/
private String basename = "messages";
//我们的配置文件可以直接放在类路径下叫messages.properties
所以我们更改默认设置在application.properties中
-
为了防止乱码,将setting 里面的 file encoding设置为
即可 -
实现按钮切换国际化,使用thymeleaf模板,在原生html加入如下链接,点击会发http://localhost:8080/?l=zh_CN请求
-
捕获请求,生成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 request, HttpServletResponse response, Locale locale) {
}
}
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}