如何在Spring中获取当前的Locale?

Joh*_*ter 5 java spring

我用这种方法

LocaleContextHolder.getLocale()

获取切换的语言环境(Japanise),但它返回英语(默认).如何检索jp_JP语言环境?

小智 7

//Return the Locale associated with the current thread,
// if any, or the   system default Locale else(English)   
LocaleContextHolder.getLocale();
Run Code Online (Sandbox Code Playgroud)

所以首先检查您当前的线程。对于在当前线程中使用的语言环境设置:

setLocale(Locale locale); 
Run Code Online (Sandbox Code Playgroud)

方法,然后LocaleContextHolder.getLocale()将返回jp_JP语言环境


Dom*_*rer 5

请求上下文实用程序

这应该允许您获取请求的当前语言环境:

RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
Run Code Online (Sandbox Code Playgroud)

返回LocaleResolver已绑定到请求的DispatcherServlet
@paramrequest当前 HTTP 请求
@return 当前的LocaleResolver,或者{@code null}如果没有找到:

public static LocaleResolver getLocaleResolver(HttpServletRequest request) {
    return (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
}
Run Code Online (Sandbox Code Playgroud)

这将返回一个 LocaleResolver,您可以从中加载语言环境。

LocaleContextHolder

或正如所提到的:Mohammad tanvirul islam:

LocaleContextHolder.getLocale();
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看文档:

  1. RequestContextUtilshttp : //docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/support/RequestContextUtils.html

  2. LocaleResolverhttp : //docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/LocaleResolver.html

  3. LocaleContextHolderhttp : //docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/i18n/LocaleContextHolder.html