Springboot国际化

背景:适应多语言环境,springboot国际化语言处理:

一、在static下新建i18n目录(静态文件夹下,位置随意)创建:

1 messages.properties(必须要有,可以为空);

2 messages_zh_CN.properties(中文对应);

内容:

user.name="用户姓名"
user.password=密码
good=商品

3 messgaes_en_US.properties(英文对应)。

内容:

user.name=username
user.password=password
good=good

4  application.properties配置文件

server.port=8090
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.messages.basename=static/i18n/messages

二、配置i18n配置文件:

@Configuration
public class I18nConfiguration  extends WebMvcConfigurerAdapter {

    @Bean
    public LocaleResolver localeResolver(){//解析器
        SessionLocaleResolver sessionLocaleResolver=new SessionLocaleResolver();
        sessionLocaleResolver.setDefaultLocale(Locale.ENGLISH);
        return sessionLocaleResolver;
    }

 @Bean
 public LocaleChangeInterceptor localeChangeInterceptor(){//设置lang参数,对应版本参数
     LocaleChangeInterceptor localeChangeInterceptor=new LocaleChangeInterceptor();
     localeChangeInterceptor.setParamName("lang");
     return localeChangeInterceptor;
  }

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

}

三、创建前端界面:index.html

<!DOCTYPE html>
<html  lang="en">
<head>
    <body>
     <h3 th:text="#{user.name}">xingming</h3>
    </body>
</head>
</html>

四、输入http://localhost:8090/index?lang=zh_CN 和http://localhost:8090/index?lang=en_US分别对应中文和英文版本

五、对于控制层返回的中文处理:

1 编写一个工具类,通过id取出对应的中文和英文值 MessageUtil:

@Component
public class MessageUtil {
    @Autowired
    private MessageSource  messageSource;
    public String getMessage(String str){
        return messageSource.getMessage(str,null, LocaleContextHolder.getLocale());
    }
}

2 之前控制层代码为:(通过访问/pro/{id},返回商品id的一个接口),在英文版就不该出现中文,所以可以按步骤3处理:

    @RequestMapping(value="/pro/{id}",method = RequestMethod.GET)
    public String  getPro(@PathVariable String id){
         return  "商品id:"+id;
    }

3 国际化处理之后:

    @RequestMapping(value="/pro/{id}",method = RequestMethod.GET)
    public String  getPro(@PathVariable String id){
         return   messageUtil.getMessage("good")+"id:"+id;//这里当lang=zh_CN时返回对应中文值,当lang=en_US时返回对应英文值
    }

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值