2)、国际化
1)、编写国际化配置文件;
2)、使用ResourceBundleMessageSource管理国际化资源文件
3)、在页面使用fmt:message取出国际化内容
步骤:
1)、编写国际化配置文件,抽取页面需要显示的国际化消息
2)、SpringBoot自动配置好了管理国际化资源文件的组件;
@ConfigurationProperties(prefix ="spring.messages")publicclassMessageSourceAutoConfiguration{/**
* 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.
*/privateString basename
="messages";//我们的配置文件可以直接放在类路径下叫messages.properties;@BeanpublicMessageSourcemessageSource(){ResourceBundleMessageSource
messageSource
=newResourceBundleMessageSource();if(StringUtils.hasText(this.basename))
{//设置国际化资源文件的基础名(去掉语言国家代码的)messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(this.basename)));}if(this.encoding
!=null)
{messageSource.setDefaultEncoding(this.encoding.name());}messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);messageSource.setCacheSeconds(this.cacheSeconds);messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);returnmessageSource;}
3)、去页面获取国际化的值;
Please sign inUsernamePassword[[#{login.remember}]]Sign in© 2017-2018中文English
效果:根据浏览器语言设置的信息切换了国际化;
原理:
国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象);
@Bean@ConditionalOnMissingBean@ConditionalOnProperty(prefix
="spring.mvc", name
="locale")publicLocaleResolverlocaleResolver(){if(this.mvcProperties.getLocaleResolver()
== WebMvcProperties.LocaleResolver.FIXED)
{returnnewFixedLocaleResolver(this.mvcProperties.getLocale());}AcceptHeaderLocaleResolver
localeResolver
=newAcceptHeaderLocaleResolver();localeResolver.setDefaultLocale(this.mvcProperties.getLocale());returnlocaleResolver;}默认的就是根据请求头带来的区域信息获取Locale进行国际化
4)、点击链接切换国际化
/**
* 可以在连接上携带区域信息
*/publicclassMyLocaleResolverimplementsLocaleResolver{@OverridepublicLocaleresolveLocale(HttpServletRequest
request){ String l = request.getParameter("l"); Locale
locale = Locale.getDefault();if(!StringUtils.isEmpty(l)){
String[] split = l.split("_"); locale
=newLocale(split[0],split[1]); }returnlocale;
}@OverridepublicvoidsetLocale(HttpServletRequest request,
HttpServletResponse response, Locale locale){
}}@BeanpublicLocaleResolverlocaleResolver(){returnnewMyLocaleResolver();
}}
网友评论