使用Spring 4 + thymeleaf处理我的webapp以支持国际化。我尝试了很多方法来更改位置文件和basename的配置并仍然接收?? label.greeting _ ** ??在模板结果。以下是我的代码
@Configuration
@EnableSpringConfigured
@EnableWebMvc
@EnableScheduling
@ComponentScan(basePackages = {"com.categorybags.web.controller", "com.categorybags.persistence.services"})
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/res/**").addResourceLocations("/res/");
}
@Bean
public ViewResolver viewResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setCacheable(false);
templateResolver.setPrefix("/WEB-INF/jsp/");
templateResolver.setSuffix(".jsp");
templateResolver.setTemplateMode("HTML5");
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setOrder(1);
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(new Locale("en"));
return localeResolver;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("WEB-INF/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
属性文件位于WEB-INF下,其路径为src \ main \ webapp \ WEB-INF \ messages_en.properties和src \ main \ webapp \ WEB-INF \ messages_ch.properties
答案 0 :(得分:5)
我认为只能将ViewResolver
注册到Spring而不是其他2个SpringTemplateEngine
和ServletContextTemplateResolver
组件,才能重现您的问题。
所以我认为您应该尝试将配置分开一点,将这两个其他组件注册到spring容器中。这是代码:
@Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setCacheable(false);
templateResolver.setPrefix("/WEB-INF/jsp/");
templateResolver.setSuffix(".jsp");
templateResolver.setTemplateMode("HTML5");
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setOrder(1);
return viewResolver;
}