科技资讯眺望|Boot 12 国际化,Spring

建立多语言网站 , 可以获得更多用户流量 。 多语言网站被称为国际化(i18n),与本地化相反 。
你比如京东、淘宝这类电商网站就是国际化的电商网站 , 它支持多国语言 。
注意:国际化是一个由18个字符组成的单词 , 第一个字符为i , 最后一个字符为n , 因此通常缩写为i18n 。
Spring通过为不同的语言环境使用Spring拦截器 , 语言环境解析器和资源包 , 为国际化(i18n)提供了广泛的支持 。 在本文中 , 我将知道您使用SpringBoot构建了一个简单的多语言网站 。
你可以预览一下示例:
在示例中 , 语言环境信息位于URL的参数上 。 语言环境信息将存储在Cookie中 , 并且用户不会在接下来的页面中重新选择语言 。
http://localhost:8080/SomeContextPath/login1?lang=zhhttp://localhost:8080/SomeContextPath/login1?lang=enURL上的语言环境信息的另一个示例:
http://localhost:8080/SomeContextPath/zh/login2http://localhost:8080/SomeContextPath/en/login212.1创建SpringBoot项目
i18n/messages_zh.properties
label.password=密码label.submit=登陆label.title=登陆页面label.userName=用户名如果你的eclipse中显示如下编码形式:
label.password=u5BC6u7801label.submit=u767Bu9646label.title=u767Bu9646u9875u9762label.userName=u7528u6237u540D修改首选项中的contentTypes下的:
label.password=Passwordlabel.submit=Loginlabel.title=LoginPagelabel.userName=UserNameEclipse支持使用消息编辑器来编辑文件的信息 。
12.2拦截器和LocaleResolver
LocaleResolver指定如何获取用户将使用的语言环境信息 。 CookieLocaleResolver将从Cookie读取语言环境信息 , 以查找用户以前使用的语言 。
MessageResource将加载属性文件内容
WebMvcConfig.java
packageme.laocat.i18n.config;importorg.springframework.context.MessageSource;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.support.ReloadableResourceBundleMessageSource;importorg.springframework.web.servlet.LocaleResolver;importorg.springframework.web.servlet.config.annotation.InterceptorRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;importorg.springframework.web.servlet.i18n.CookieLocaleResolver;importorg.springframework.web.servlet.i18n.LocaleChangeInterceptor;@ConfigurationpublicclassWebMvcConfigimplementsWebMvcConfigurer{@Bean(name=“localeResolver”)publicLocaleResolvergetLocaleResolver(){//Cookie本地化解析器CookieLocaleResolverresolver=newCookieLocaleResolver();resolver.setCookieDomain(“myAppLocaleCookie”);//60分钟resolver.setCookieMaxAge(60*60);returnresolver;}@Bean(name=“messageSource”)publicMessageSourcegetMessageResource(){//可重新加载的资源包消息源ReloadableResourceBundleMessageSourcemessageResource=newReloadableResourceBundleMessageSource();//读i18n/messages_xxx.propertiesfile.//例如:i18n/messages_en.propertiesmessageResource.setBasename(“classpath:i18n/messages”);messageResource.setDefaultEncoding(“UTF-8”);returnmessageResource;}@OverridepublicvoidaddInterceptors(InterceptorRegistryregistry){//本地化修改拦截器LocaleChangeInterceptorlocaleInterceptor=newLocaleChangeInterceptor();localeInterceptor.setParamName(“lang”);registry.addInterceptor(localeInterceptor).addPathPatterns(“/*”);}}12.3控制器和视图


推荐阅读