gpt4 book ai didi

java - 如果语言环境无效,Spring mvc 从请求中获取默认语言环境

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:54:22 24 4
gpt4 key购买 nike

我已经在我的 Spring MVC 应用程序(localeInterceptor 等)中配置了 i18n。

支持两种语言(英语和波兰语)。 PL 是默认的。 I18n 当然有效。

我的情况是获取当前语言环境并将其传递给模型。这很简单,但是当我传递无效的语言环境参数(如 localhost:8080/?language=asd)时,我得到的是“asd”而不是默认的“pl”。

值得一提的是,整个 i18n 工作完美,我的意思是在这种情况下使用了 messages_pl.properties。我尝试了以下方法但没有成功:

@RequestMapping(...)
public String home(Locale locale,..)

localeResolver.resolveLocale(request);
RequestContextUtils.getLocale(request);
LocaleContextHolder.getLocale();

每一个都给我一个“asd”而不是“pl”。

Atm 我有一个有点困惑的解决方法:

if (!supportedLocaleService.isLocaleSupported(locale)) {//myservice
locale = new Locale("pl");
}

最佳答案

您可以覆盖 LocaleChangeInterceptor

public class SupportedLocaleAwareLocaleChangeInterceptor extends LocaleChangeInterceptor {

private List<String>supportedLocales = Arrays.asList("pl",....);

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws ServletException {

String newLocale = request.getParameter(this.paramName);
//if (newLocale != null) {
if (newLocale != null && supportedLocales.contains(newLocale )) {
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
if (localeResolver == null) {
throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
}
localeResolver.setLocale(request, response, StringUtils.parseLocaleString(newLocale));
}
// Proceed in any case.
return true;
}
}

关于java - 如果语言环境无效,Spring mvc 从请求中获取默认语言环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36227642/

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