使用语言标识符映射网址

时间:2011-07-15 14:49:45

标签: spring-mvc

是否有一种很好的方法可以根据URL解析语言环境,另一方面可以在没有任何额外要求的情况下解决映射请求?

例如

http://example.com/ru/news    
http://example.com/iw/news

并且在控制器中仍然使用标准映射

@Controller
@RequestMapping(value = "/news")
public class NewsController {

    // Controller methods ...    

}

3 个答案:

答案 0 :(得分:2)

您可以编写一个类似LocaleChangeInterceptor

的自定义拦截器

这是一个使用正则表达式模式的示例实现(大部分代码都是从LocaleChangeInterceptor复制的):

public class CustomLocaleChangeInterceptor extends HandlerInterceptorAdapter {

    private Pattern localePattern;

    public void setLocalePattern(final String localePattern) {
        Assert.isTrue(localePattern.matches(".*\\(.*\\).*"), "Your pattern needs to define a match group");
        this.localePattern = Pattern.compile(localePattern);
    }

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

        final String pathTranslated = request.getPathTranslated();
        if (pathTranslated != null) {

            final Matcher matcher = localePattern.matcher(pathTranslated);
            if (matcher.find()) {
                final String newLocale = matcher.group(1);
                if (newLocale != null) {
                    final LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
                    if (localeResolver == null) {
                        throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
                    }
                    final LocaleEditor localeEditor = new LocaleEditor();
                    localeEditor.setAsText(newLocale);
                    localeResolver.setLocale(request, response, (Locale) localeEditor.getValue());
                }
            }
        }
        // Proceed in any case.
        return true;

    }

}

像这样连线:

<bean id="localeChangeInterceptor"
      class="foo.bar.CustomLocaleChangeInterceptor">
    <property name="localePattern" value="\b([a-z]{2})\b"/>
</bean

答案 1 :(得分:1)

我不知道有一个开箱即用的解决方案,但使用自定义拦截器和一些明智选择的映射很容易实现。

编写实现HandlerInterceptor的{​​{1}}实现,以便从请求URI中提取语言环境字符串,然后使用该语言环境标记请求(see the source code for类似{{1}它与你需要的东西类似,但使用请求参数而不是路径变量。)

然后wire it up使用preHandle例如

LocalChangeInterceptor

然后,您可以放松控制器上的请求映射,以容忍(并忽略)URI的区域设置部分:

<mvc:interceptor>

答案 2 :(得分:0)

看一下http://lrkwz.github.com/URLManagedLocale/你可以简单地将依赖项放在你的pom文件中并配置拦截器和localeresolver。