Internationalization in Spring boot and Thymeleaf

This is the structure of the Project:

Add some languages properties in src/main/resources/messages_****.properties. Spring default base name starts with 'messages'. You can find out the evidence from org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration class. Add a couple of messages to each file, and we’ll use them to change the labels on our sample application's based on the client's locale.

/src/main/resources/messages_en_US.properties

user.name=Name
user.email=Email

/src/main/resources/messages_zh_CN.properties

user.name = \u59D3\u540D
user.email = \u7535\u5B50\u90AE\u4EF6

Let's Application class extends WebMvcConfigurerAdapter and configure a LocaleResolver.

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter{  
    public static void main(String[] args) {
    	SpringApplication.run(Application.class, args);
    }

    @Bean
    public LocaleResolver localeResolver() {
        return new CookieLocaleResolver();
    }
}

update view page like this.

<th th:text="#{user.name}">Name</th>
<th th:text="#{user.email}">Email</th>

Run Application class,  you can get different locale based on your browser language.

If you want to set these messages properties into a foler in src/main/resources, please do a configuration in application.properties file.

spring.messages.basename=i18n/messages
spring.messages.encoding=UTF-8

If you want to get locale like this: http://localhost:8080/users?lang=en , please do below setting.

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter{  
    public static void main(String[] args) {
    	SpringApplication.run(Application.class, args);
    }
    
    @Bean
    public LocaleResolver localeResolver() {
    	return new CookieLocaleResolver();
    }
    
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }


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

Configure a LocaleChangeInterceptor. You can switch language with param lang.

转载于:https://my.oschina.net/ayyao/blog/840630

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值