How do I get the current language in Spring?
RequestContextUtils
This will allow you to get the current locale of your request:
RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
Return the LocaleResolver
one that was attached to the request DispatcherServlet
.
@param request
current HTTP request
@ return the current one LocaleResolver
or {@code null}
if not found:
public static LocaleResolver getLocaleResolver(HttpServletRequest request) {
return (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
}
This will return a LocaleResolver from where you can load the locale.
LocaleContextHolder
Or as it is believed by Mohammad tanvirul islam:
LocaleContextHolder.getLocale();
You can see the doc here:
-
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
source to share
//Return the Locale associated with the current thread,
// if any, or the system default Locale else(English)
LocaleContextHolder.getLocale();
so you check the current thread first. To set the locale in current thread usage:
setLocale(Locale locale);
and then LocaleContextHolder.getLocale () will return jp_JP locale
source to share