创建自定义LocalChangeInterceptor

时间:2017-07-08 08:59:32

标签: spring spring-mvc spring-boot

我正在使用Spring Boot编写应用程序。在我的应用程序中,我将使用像http://localhost:8080/School/**en**/xxx/...这样的本地化URL smth。我尝试实现自定义区域设置拦截器。在下面的列表中,第一个变体工作正常。我想使用第二种变体,但不是法国或德国,语言环境不会改变并保持en_US。任何人都可以建议我吗?

@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {

1 VARIANT

@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver slr = new SessionLocaleResolver();
    slr.setDefaultLocale(Locale.GERMANY);
    return slr;
}

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
    lci.setParamName("lang");
    return lci;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
}

2 VARIANT

@Bean
public LangInterceptor langInterceptor() {
    return new LangInterceptor();
}

    @Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor( langInterceptor());
}

@Bean
public SessionLocaleResolver sessionLocaleResolver() {
    SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
    sessionLocaleResolver.setDefaultLocale(Locale.GERMANY);
    return sessionLocaleResolver;
}
}

我的自定义拦截器:

public class LangInterceptor extends HandlerInterceptorAdapter {

@Autowired
LocaleResolver sessionLocaleResolver;
Locale locale;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (StringUtils.startsWithIgnoreCase(request.getServletPath(), "/it/")) {
        locale = new Locale("it");
    } else {
        locale = new Locale("en");
    }
    sessionLocaleResolver.setLocale(request, response, Locale.FRENCH);
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

}
}

2 个答案:

答案 0 :(得分:0)

您无法随机引用HandlerInterceptorAdapter来更改区域设置。 Spring默认使用AcceptHeaderLocaleResolver,您希望根据路径段解析。扩展WebMvcConfigurerAdapter,然后执行以下操作:

@Bean
public LocaleResolver localeResolver() {
   // return custom LocaleResolver
}

但是,我告诫你,你违反HTTP规范。 Accept-Language标头用于此目的,这是AcceptHeaderLocaleResolver使用的。

您不需要LocaleChangeInterceptor,因为它对查询参数进行操作。

答案 1 :(得分:0)

我找到了解决方案。如果我只是添加我的配置文件LocaleChangeInterceptor,第一个变体将起作用。原因看起来LocaleResolver没有拦截器就没有初始化,但spring文档说每个类都有默认的构造函数。所以它有效。

@Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
    lci.setParamName("lang");
    return lci;
}