SpringBoot 页面国际化转化

1.实现的效果:默认按照操作系统的语言进行页面字体语言,点击中文字体为中文,点击English 字体为英文

 

 

 

 

 2.实现的思路:

1)、编写国际化配置文件;

2)、使用ResourceBundleMessageSource管理国际化资源文件

3)、在页面使用thymeleaf取出国际化内容

 

3.具体实现

1)编写国际化配置文件,抽取页面需要显示的国际化消息

   在resources建立properties文件  idea帮我们自动生成了对应的资源目录

    ***解决thymeleaf取内容乱码问题

 

 

 

    在国际文件properties编辑对应的信息

 

 

 

  2)、SpringBoot自动配置好了管理国际化资源文件的组件;MessageSourceAutoConfiguration

 

 

     我们只需在配置文件配置国际资源文件的路径  包名+识别名

spring.messages.basename=internationalization.login  

 

 

3)去页面获取国际化的值;thymeleaf用#{}取出国际值

 

 

 

 这样默认的就是根据请求头带来的区域信息获取Locale进行国际化

 

 

4)点击链接切换国际化

 

 

 如果没有配置区域信息解析器,springboot帮我们创建了区域信息解析器默认用的是请求头的区域信息,有就用我们自己配置的

配置自己的区域信息解析器

package com.example.springbootdemo.Assembly;

import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class MylocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String l = httpServletRequest.getParameter("l");//获取地址信息
        System.out.println("____"+l);
        Locale locale=Locale.getDefault();//默认操作系统最带的区域信息
        if(!StringUtils.isEmpty(l)){//判断是否为空
            String[] s = l.split("_");//按照“_”分割
            System.out.println(s[0]+"_______"+s[1]);
            locale= new Locale(s[0],s[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

 在springmvc配置类声明我们的区域信息解析器

  //添加自己的LocaleResolver
//方法名必须是这个
    @Bean
    public LocaleResolver localeResolver(){
        return new MylocaleResolver();
    }

 

 

4.总结

1.springboot为我们自动配置的两个组件

  国际化资源管理器:MessageSourceAutoConfiguration

  区域信息解析器:在WebMvcAutoConfiguration里面配置

 

 

 

 

 

  

   

 

   

 

posted @ 2020-07-11 15:35  熬夜秃头选拨赛冠军  阅读(177)  评论(0编辑  收藏  举报