0

我已經開始使用帶有百里香葉的Spring MVC項目。我想要它是國際化的。我已經複製了官方的春季教程。但是當我點擊tr按鈕時,單詞不會改變。我正在粘貼我的密碼。我認爲ResourceManager服務的getLabel函數正在獲取標籤當前語言。但我不確定。我該如何繼續?春季mvc無法在百里香葉上工作國際化

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = {"com.yummynoodlebar.web.controller","com.yummynoodlebar.web.service","com.yummynoodlebar.web.domain"}) 
public class WebConfig extends WebMvcConfigurerAdapter { 

@Override 
public void addResourceHandlers(ResourceHandlerRegistry registry) { 
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 
} 

@Override 
public void addInterceptors(InterceptorRegistry registry) { 
    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); 
    localeChangeInterceptor.setParamName("lang"); 
    registry.addInterceptor(localeChangeInterceptor); 
} 

@Bean 
public LocaleResolver localeResolver() { 

    CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); 
    cookieLocaleResolver.setDefaultLocale(StringUtils.parseLocaleString("en")); 
    return cookieLocaleResolver; 
} 

@Bean 
public ServletContextTemplateResolver templateResolver() { 
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(); 
resolver.setPrefix("/WEB-INF/views/"); 
resolver.setSuffix(".html"); 
//NB, selecting HTML5 as the template mode. 
resolver.setTemplateMode("HTML5"); 
resolver.setCharacterEncoding("UTF-8"); 
resolver.setCacheable(false); 
return resolver; 

} 

@Bean 
public SpringTemplateEngine templateEngine() { 
SpringTemplateEngine engine = new SpringTemplateEngine(); 
engine.setTemplateResolver(templateResolver()); 
return engine; 
} 

@Bean 
public ViewResolver viewResolver() { 

ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); 
    viewResolver.setTemplateEngine(templateEngine()); 
viewResolver.setOrder(1); 
viewResolver.setViewNames(new String[]{"*"}); 
viewResolver.setCache(false); 
    return viewResolver; 
} 

@Bean(name = "labelSource") 
public MessageSource messageSource() { 

    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 
    messageSource.setBasenames("classpath:i18n/labels"); 
    // if true, the key of the message will be displayed if the key is not 
    // found, instead of throwing a NoSuchMessageException 
    messageSource.setUseCodeAsDefaultMessage(true); 
    messageSource.setDefaultEncoding("UTF-8"); 
    // # -1 : never reload, 0 always reload 
    messageSource.setCacheSeconds(0); 
    return messageSource; 
} 

} 

@Component 
public class ResourceManager { 

@Resource(name = "labelSource") 
private MessageSource messageSource; 

public String getLabel(String code) { 
    return messageSource.getMessage(code, null, Locale.getDefault()); 
} 
} 

回答

0

我已經解決了我的問題。我改變了getLabel函數。新代碼如下

public String getLabel(String code) { 
    return messageSource.getMessage(code, null, LocaleContextHolder.getLocale()); 
}