springboot国际化

springboot国际化

最近在看B站的springboot学习视频,讲的挺好的,源码分析的部分也不少,不过目前比较菜,先学会怎么用就好了

html页面

在这里插入图片描述

想实现的效果

点击中文显示这样,English显示英文输入

具体步骤

  • 编写国际化配置文件
    在这里插入图片描述
    在这里插入图片描述

  • 使用ResourceBundleMessageSource管理国际化资源文件
    在springboot中,已经自动配置好了国际化组件,

```@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
    
    /**
  * Comma-separated list of basenames (essentially a fully-qualified classpath
  * location), each following the ResourceBundle convention with relaxed support for
  * slash based locations. If it doesn't contain a package qualifier (such as
  * "org.mypackage"), it will be resolved from the classpath root.
  */
 private String basename = "messages";  
    //我们的配置文件可以直接放在类路径下叫messages.properties

所以我们更改默认设置在application.properties中

在这里插入图片描述

  • 为了防止乱码,将setting 里面的 file encoding设置为
    在这里插入图片描述
    即可

  • 实现按钮切换国际化,使用thymeleaf模板,在原生html加入如下链接,点击会发http://localhost:8080/?l=zh_CN请求
    在这里插入图片描述

  • 捕获请求,生成locale对象,然后加入容器中

 */
public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if(!StringUtils.isEmpty(l)){
            String[] split = l.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}
@Configuration

public class MyMvcConfig implements WebMvcConfigurer {

  @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值