背景:适应多语言环境,springboot国际化语言处理:
一、在static下新建i18n目录(静态文件夹下,位置随意)创建:
1 messages.properties(必须要有,可以为空);
2 messages_zh_CN.properties(中文对应);
内容:
user.name="用户姓名"
user.password=密码
good=商品
3 messgaes_en_US.properties(英文对应)。
内容:
user.name=username
user.password=password
good=good
4 application.properties配置文件
server.port=8090
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.messages.basename=static/i18n/messages
二、配置i18n配置文件:
@Configuration
public class I18nConfiguration extends WebMvcConfigurerAdapter {
@Bean
public LocaleResolver localeResolver(){//解析器
SessionLocaleResolver sessionLocaleResolver=new SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(Locale.ENGLISH);
return sessionLocaleResolver;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor(){//设置lang参数,对应版本参数
LocaleChangeInterceptor localeChangeInterceptor=new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
三、创建前端界面:index.html
<!DOCTYPE html>
<html lang="en">
<head>
<body>
<h3 th:text="#{user.name}">xingming</h3>
</body>
</head>
</html>
四、输入http://localhost:8090/index?lang=zh_CN 和http://localhost:8090/index?lang=en_US分别对应中文和英文版本
五、对于控制层返回的中文处理:
1 编写一个工具类,通过id取出对应的中文和英文值 MessageUtil:
@Component
public class MessageUtil {
@Autowired
private MessageSource messageSource;
public String getMessage(String str){
return messageSource.getMessage(str,null, LocaleContextHolder.getLocale());
}
}
2 之前控制层代码为:(通过访问/pro/{id},返回商品id的一个接口),在英文版就不该出现中文,所以可以按步骤3处理:
@RequestMapping(value="/pro/{id}",method = RequestMethod.GET)
public String getPro(@PathVariable String id){
return "商品id:"+id;
}
3 国际化处理之后:
@RequestMapping(value="/pro/{id}",method = RequestMethod.GET)
public String getPro(@PathVariable String id){
return messageUtil.getMessage("good")+"id:"+id;//这里当lang=zh_CN时返回对应中文值,当lang=en_US时返回对应英文值
}