springboot 2.*(spring mvc 5) thymeleaf i18n(internationalization) 国际化问题

    文章目的:使用SpringBoot 2.*(其实就是Spring MVC 5) 加 Thymeleaf 实现国际化。

    其实很简单的问题,但由于网上SpringBoot 教程大多在 1.5.3.RELEASE ,没有实际能解决的。

    看Thymeleaf官方 、SpringBoot 官方、Spring MVC 5 官方文档。所以解决这个问题用了我2天...我还是太菜了。


    进入主题:

    首先是pom.xml依赖加上Thymeleaf。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

    然后创建一个配置类:

@Configuration
@ComponentScan
public class MyConfiguration implements WebMvcConfigurer {


/* @Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("classpath:i18n/messages");//设置默认的国际化资源文件路径
messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
}*/

@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:i18n/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}

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

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

然后创建国际化资源文件(properties):

我的工程目录结构:

    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值