我使用这个方法
LocaleContextHolder.getLocale()
以切换语言环境(日语),但它返回我英语(默认)。如何检索jp_JP区域设置?
//Return the Locale associated with the current thread,
// if any, or the system default Locale else(English)
LocaleContextHolder.getLocale();
所以首先你必须检查当前线程的Locale。如果你想在当前线程中设置Locale,那么使用下面的代码:
setLocale(Locale locale); LocaleContextHolder.getLocale() will return jp_JP locale
RequestContextUtils
这应该允许您获得请求的当前语言环境:
RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
返回被DispatcherServlet
绑定到请求的LocaleResolver
。
@param request
当前HTTP请求
@返回当前LocaleResolver
,如果没有找到则返回{@code null}
:
public static LocaleResolver getLocaleResolver(HttpServletRequest request) {
return (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
}
这将返回一个LocaleResolver,你可以从中加载区域设置。
LocaleContextHolder
或者正如Mohammad tanvirul islam所提到的:
LocaleContextHolder.getLocale();
你可以在这里查看文档:
RequestContextUtils : http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/support/RequestContextUtils.html
LocaleResolver : http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/LocaleResolver.html
LocaleContextHolder : http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/i18n/LocaleContextHolder.html
给出一个简单的例子。假设您的资源为:选择任意一个代码
@Autowired
private MessageSource messageSource;
@GetMapping(path = "/hello-world-I18N")
public String helloWorldInternationalize() {
return messageSource.getMessage("good.morning.message", null,
LocaleContextHolder.getLocale());
}
@GetMapping(path = "/hello-world-I18N")
public String helloWorldInternationalize(@RequestHeader(name = "Accept-Header", required = false) Locale locale) {
return messageSource.getMessage("good.morning.message", null, locale);
}
现在在请求与邮差发送报头作为:接受语言:US/FN等任何你想要的
配置一个LocaleResolver:
@Bean
public LocaleResolver localeResolver() {
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(Locale.US); // set default to US
return localeResolver;
}
正在应用中。添加属性文件spring.messages。Basename =message//message是属性文件的基本名称。
在资源文件夹中添加更多文件名为:message_fr的文件。属性,message.properties然后在这里添加内容。像(good.morning。留言=你好)
有几种方法可以创建Locale对象。获取当前的Local对象。
Locale locale = LocaleContextHolder.getLocale();
或
Locale locale;
获取当前语言
Locale locale;
locale.getLanguage()
Locale locales = LocaleContextHolder.getLocale();
locales.getLanguage();