springboot配置国际化
来源:互联网 发布:电商运营 知乎 编辑:程序博客网 时间:2024/06/03 19:29
1. springboot引入国际化首先要导入Thymeleaf 模板
Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持html 原型,然后在html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释html 时会忽略未定义的标签属性,所以thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf标签会动态地替换掉静态内容,使页面动态显示
①在pom.xml文件中引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
②在对应的html文件中添加<html xmlns:th="http://www.thymeleaf.org">,对要求进行语言切换的文字用th:text的属性进行动态获取可通过$(变量表达式)和#(文字国际化表达式)
变量表达式
变量表达式即OGNL表达式或Spring EL表达式(在Spring术语中也叫model attributes)。
如下所示: ${session.user.name}
它们将以HTML标签的一个属性来表示:
<span th:text="${book.author.name}">
文字国际化表达式
文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties),用Key索引Value,还可以提供一组参数(可选).#{main.title}
2. Java程序的书写
①springboot要有对应的程序入口***Application的类
②要配置语言locale的适配器和拦截器
Locale 表示地区。每一个Locale对象都代表了一个特定的地理、政治和文化地区。获取默认的locale时用Locale locale = Locale.getDefault()
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class LocaleConfigextends WebMvcConfigurerAdapter{
@Bean
publicLocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
//默认语言
slr.setDefaultLocale(Locale.CHINA);
return slr;
}
@Bean
publicLocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci =new LocaleChangeInterceptor();
//参数名
lci.setParamName("lang");
return lci;
}
@Override
public voidaddInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
③配置对应的controller
@Controller
public class GrobalController {
@Autowired
privateMessageSource messageSource;
@GetMapping("/grobal")
publicString togrobal(Model model) {
Locale locale = LocaleContextHolder.getLocale();
String add=messageSource.getMessage("add", null, locale);
model.addAttribute("add",messageSource.getMessage("add", null,locale));
return "grobal";
}
}
④java代码配置messageSource的bean用来读取国际化配置文件
注意: messageSource是一个接口,在进行实例化对象的时候我们创建的是它的实现类ResourceBundleMessageSource
获取国际化资源的方法是
String getMessage(String code, Object[] args, String defaultMessage, Locale locale)
code表示国际化资源中的属性名;args用于传递格式化串占位符所用的运行期参数;当在资源找不到对应属性名时,返回defaultMessage参数所指定的默认信息;locale表示本地化对象;
MessageSource分别被HierarchicalMessageSource和ApplicationContext接口扩展,这里我们主要看一下HierarchicalMessageSource接口的几个实现类,
该接口的setParentMessageSource (MessageSource parent)方法用于设置父MessageSource,而getParentMessageSource()方法用于返回父MessageSource。
HierarchicalMessageSource接口最重要的两个实现类是ResourceBundleMessageSource和ReloadableResourceBundleMessageSource。它们基于Java的ResourceBundle基础类实现,允许仅通过资源名加载国际化资源。
ReloadableResourceBundleMessageSource提供了定时刷新功能,允许在不重启系统的情况下,更新资源的信息。
StaticMessageSource主要用于程序测试,它允许通过编程的方式提供国际化信息。
DelegatingMessageSource是为方便操作父MessageSource而提供的代理类。
ResourceBundleMessageSource该实现类允许用户通过beanName指定一个资源名(包括类路径的全限定资源名),或通过beanNames指定一组资源名。
cacheSeconds属性让ReloadableResourceBundleMessageSource每5秒钟刷新一次资源文件(在真实的应用中,刷新周期不能太短,否则频繁的刷新将带来性能上的负面影响,一般不建议小于30分钟)。cacheSeconds默认值为-1表示永不刷新,此时,该实现类的功能就为ResourceBundleMessageSource的功能。
@Configuration
public class MessageConfig {
@Value("${spring.messages.basename}")
privateString basename;
@Value("${spring.messages.encoding}")
privateString encoding;
@Value("${spring.messages.cache-seconds}")
private intcacheSeconds;
@Bean
publicMessageSource messageSource(){
ResourceBundleMessageSource messageSource=newResourceBundleMessageSource();
if (StringUtils.hasText(this.basename)) {
messageSource.setBasenames(this.basename);
}
if(this.encoding!= null) {
messageSource.setDefaultEncoding(this.encoding);
}
messageSource.setCacheSeconds(this.cacheSeconds);
return messageSource;
}
}
对应的也要在application.yml进行国际化的配置
3. 静态页面以及国际化文件的配置
静态文件会默认的放在resources/templates的文件夹下,要进行修改的话要在application.yml文件中进行配置
国际化文件的命名方式默认为basename_语言名_国名 basename在application.yml中进行配置,放置的位置为src/main/resources/路径下
messages_en_US.properties :
add=add
messages_zh_CN.properties :
add=新增
4. 配置中的报错信息及原因
报错1: ApplicationEventMulticaster not initialized - call 'refresh' before multicas
原因: 配置messageSource的bean报错
报错2: spring boot No message found under code 'add' for locale 'zh'.
原因: 缺少java配置messageSource的bean,需要进行配置.
报错3: Can't find bundle for base name /i18n/messages, locale zh_CN
原因: 没办法找到message这个国际化资源文件,需要将文件放到resource下面的包下
报错4: Error resolving template "grobal", template might not exist or might not be accessible by any of the configured Template Resolvers
原因: Controller的return中grobal时,找不到Template模板对应的视图(相当于404错误).结果发现是classpath配置中的claspath:/Template少了/,造成页面拼接的时候找不到页面.同时grobal页面的<a href=" . /grobal?lang=en_US">English(US)</a>少了”.”,会造成无法页面的跳转<a href="./grobal?lang=zh_CN">简体中文</a>
- springboot国际化配置
- springboot配置国际化
- SpringBoot validator国际化随笔
- Springboot国际化i18n
- springboot+freemarker国际化
- SpringBoot与Thymeleaf实现国际化
- springboot配置
- springboot配置
- SpringBoot配置
- 【SpringBoot】SpringBoot核心-基本配置
- 【SpringBoot】SpringBoot核心-外部配置
- SpringBoot-01SpringBoot配置FastJson
- velocity国际化配置
- JSP国际化配置
- Spring MVC国际化配置
- Spring MVC国际化配置
- Spring国际化配置
- Struts2 配置国际化支持
- 命中注定
- LinearLayout的两个关键属性(layout_gravity&weight)
- MySql从一窍不通到入门(五)Sharding:分表、分库、分片和分区
- 记录开发当中遇到的问题及小知识点(持续更新...)
- STM32 MPU6050姿态融合(转)
- springboot配置国际化
- DUBBO学习:启动检查
- 设计模式学习之路
- DES加解密
- 分布式文件系统MFS的基本用法以及高可用实现
- window对象
- 文章标题
- Divide and Conquer:215. Kth Largest Element in an Array
- python3 迭代器与生成器