我是菜鸟,想要为春季启动应用程序进行国际化。这是我尝试过的但无法让它发挥作用:
@SpringBootApplication
public class CarriersApplication extends WebMvcConfigurerAdapter {
@Autowired WebContextHolder webContextHolder;
public static void main(String[] args) {
SpringApplication.run(CarriersApplication.class, args);
}
@Bean
public RestTemplate createRestTemplate() {
return new RestTemplate();
}
@Bean
public LocaleResolver localeResolver() {
HttpSession session = webContextHolder.getSession();
String lang = ((Merchant) session.getAttribute( "principal" )).getLanguage();
// the code above is an attempt to get language from session object to set the
// default locale
// ex: lang = en,fr
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale( new Locale( lang) );
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor( localeChangeInterceptor());
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
我的问题是:当我定义localeResolver()
方法时,是否有可能以这种方式从“主要”会话对象获取区域设置?
答案 0 :(得分:0)
您可以从LocaleContextHolder获取语言环境:
@Bean
public LocaleResolver localeResolver() {
Locale locale = LocaleContextHolder.getLocale();
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(locale);
return slr;
}