Spring Boot国际化的实现

一、编写配置文件,前台页面显示的信息(IDEA工具)

1.创建目录及文件

2.配置文件的内容

默认配置文件login.properties

login.username=用户名~

英语配置文件login_en_US.properties

login.username=username~

中文配置文件login_zh_CN.properties

login.username=用户名~

二、SpringBoot自动配置好了管理国际化资源文件的组件

1.源码参考如下
@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;
    
    @Bean
	public MessageSource messageSource() {
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		if (StringUtils.hasText(this.basename)) {
            //设置国际化资源文件的基础名(去掉语言国家代码的)
			messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
					StringUtils.trimAllWhitespace(this.basename)));
		}
		if (this.encoding != null) {
			messageSource.setDefaultEncoding(this.encoding.name());
		}
		messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
		messageSource.setCacheSeconds(this.cacheSeconds);
		messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
		return messageSource;
	}
2.配置文件中配置读取我们自己配置的信息

application.properties

#国际化:包名+前缀名
spring.messages.basename=i18n.login

三、前台页面获取国际化的值(thymeleaf模板引擎为例)

<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" placeholder="Username" th:placeholder="#{login.username}" required="">
四、初步效果:此时可以启动项目

1. 更换浏览器的语言设置(以火狐为例,chrome一样),自动读取本地Locale显示对应的信息,确定,F5刷新前台就能看到效果了



五、点击前台链接自动切换中英文

1.1、前台链接代码如下:携带了参数给后台如:l=en_US
    //发送的url:http://localhost:8080/index.html?l=en_US
    
    <a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
    <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
1.2、后台实现 LocaleResolver接口
public class MyLocalResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String len = request.getParameter("l");
        //System.out.printf("len:-----"+len);
        Locale locale = Locale.getDefault();
        if(!StringUtils.isEmpty(len)){
            String[] str = len.split("_");
            locale = new Locale(str[0],str[1]);

        }

        return locale;

    }

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

    }
}
1.3、光实现是没有用的,配置视图映射,而且要注册到容器中
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("sjxy").setViewName("test");

    }
    //配置视图映射
    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
            WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
                @Override
                public void addViewControllers(ViewControllerRegistry registry) {
                    //super.addViewControllers(registry);
                    registry.addViewController("/").setViewName("login");
                    registry.addViewController("/index.html").setViewName("login");
                }

            };
            return  adapter;
    }
    //注册localResolver
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocalResolver();
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值