gpt4 book ai didi

java - 如何在 Controller 中获取当前语言?

转载 作者:行者123 更新时间:2023-11-30 07:14:47 26 4
gpt4 key购买 nike

这是我的区域设置

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>

<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>

<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>

<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>

当我尝试使用

在 Controller 中调用语言环境时
@RequestMapping(value = "customers/customer-{idCustomer:[0-9]+}/detail", method = RequestMethod.GET)
public ModelAndView detail(Map<String, Object> map, @PathVariable Integer idCustomer, Locale locale) {
logger.info(locale.toString());
logger.info(request.getLocale().toString());
...
}

它返回不同的值。但是,当我使用 URL ?lang=en 中的 GET 参数在站点上切换语言时,它在提到的 Controller 调用中没有任何改变。 i18n 工作正常,它从正确的文件加载标签。但我想在我的 Controller 中获得更改的语言。我想在打开的页面上独立获取所选语言(在 URL 中有/没有请求参数 lang)。

最佳答案

您可以使用 Spring 为此目的提供的 LocaleContextHolder 类。来自文档:

Used as a central holder for the current Locale in Spring, wherever necessary: for example, in MessageSourceAccessor. DispatcherServlet automatically exposes its current Locale here. Other applications can expose theirs too, to make classes like MessageSourceAccessor automatically use that Locale.

然后在你的 Controller 中调用:

LocaleContextHolder.getLocale();

使用 Spring 检索语言环境。

LocaleContextHolder.getLocale() javadoc.

关于java - 如何在 Controller 中获取当前语言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18318026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com