我使用这种方法
LocaleContextHolder.getLocale()
获取切换区域设置(Japanise)但它返回英文(默认)。如何检索jp_JP语言环境?
答案 0 :(得分:4)
//Return the Locale associated with the current thread,
// if any, or the system default Locale else(English)
LocaleContextHolder.getLocale();
所以首先检查你当前的thread.for在当前线程使用中设置你的语言环境:
setLocale(Locale locale);
方法然后LocaleContextHolder.getLocale()将返回jp_JP语言环境
答案 1 :(得分:3)
<强> RequestContextUtils提供强>
这应该允许您获取请求的当前区域设置:
RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
返回LocaleResolver
已绑定到请求的DispatcherServlet
@param request
当前的HTTP请求
@return当前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
答案 2 :(得分:1)
举一个简单的例子。假设你有资源:选择任何一个代码
@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);
}
现在在请求中使用 POSTMAN 发送标题为: 接受语言:US/FN 等任何你想要的。
为其配置一个 LocaleResolver:
@Bean
public LocaleResolver localeResolver() {
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(Locale.US); // set default to US
return localeResolver;
}
现在在 application.properties 文件中添加 spring.messages.basename=message // message 是属性文件的基本名称。
在资源文件夹中添加更多文件,名称为:message_fr.properties、message.properties 并在此处添加内容。喜欢 (good.morning.message = Bonjour)
代码可以正常工作。
答案 3 :(得分:0)
有几种创建Locale对象的方法。要获取当前的Local对象。
def get_value(n):
newdict = {
"value1": ["950001", "959070", "959071", "959072", "950908", "959073"],
"value2": ["400856", "400857", "400858", "400859", "400860", "400861"],
"value3": ["920100"],
"value4": ["950107", "950109", "950108"]
}
# Loop through dictionary to find a match and its value
for value, nums in newdict.items():
if n in nums:
return(value)
或
Locale locale = LocaleContextHolder.getLocale();
获取当前语言
Locale locale;