我刚接触Spring MVC,我在应用程序中添加多语言时遇到了一些问题。
我不'使用xml配置。我有一个@Configuration类
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.springexamples.basic.controller")
public class BasicServletConfig extends BaseConfig {
@Bean
ViewResolver viewResolver() {
return getViewResolver("views/basic/", ".jsp");
}
@Bean
MessageSource messageSource() {
return getMessageSource("/messages/messages");
}
@Bean
LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("lang");
return interceptor;
}
@Bean
LocaleResolver localeResolver() {
return new SessionLocaleResolver();
}
@Bean
HandlerMapping handlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setInterceptors(new HandlerInterceptor[] { localeChangeInterceptor() });
return mapping;
}
}
当我测试de应用程序总是看到默认语言(西班牙语)。我使用参数'lang = en'或'lang = EN'发送请求,但我仍然以默认语言看到它。
¿任何人都知道解决方案吗?。
谢谢,
答案 0 :(得分:0)
我不确定HandlerMapping
如何宣布这种方式会与@EnableWebMvc
一起发挥作用。使用@EnableWebMvc
配置拦截器的更惯用的方法是使用WebMvcConfigurer
:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.springexamples.basic.controller")
public class BasicServletConfig extends BaseConfig implements WebMvcConfigurer {
...
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
...
}