如何实现i18n使用spring mvc在获取请求中使用url而不是param?

时间:2018-09-02 12:43:39

标签: spring internationalization

大多数教程都是通过GET请求实现的,例如:www.xxx.com.index?lang = zh-CN。

我想得到这样的解决方案:[https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/index][1]

语言环境(“ en-US”)位于域之后。

我也不想修改现有的控制器。

1 个答案:

答案 0 :(得分:0)

我已经解决了。解决方案是实施LocaleChangeInterceptor, 春季此类的preHandle方法是:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
    String newLocale = request.getParameter(this.paramName);
    if (newLocale != null && this.checkHttpMethod(request.getMethod())) {
        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));
    }

    return true;
}

我的preHandle方法:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
    if (this.checkHttpMethod(request.getMethod())) {
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if (localeResolver == null) {
            throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
        }

        localeResolver.setLocale(request, response, I18nUtil.getLocaleByUrl(request.getServletPath()));
    }

    return true;
}

只需实施I18nUtil.getLocaleByUrl(request.getServletPath())。 非常感谢您!@M。迪尼姆