79-java-springboot(5)-国际化

三.国际化
1、编写国际化配置文件,抽取页面需要显示的国际化消息
在这里插入图片描述

说明:
1.新建一个文件xxx.properties
2.新建一个文件xxx_en_US.properties
上面两步完成之后,springboot会扫描出我们是要做国际化,会自动生成国际化视图.
3.添加其他语言的properties文件
4.分别给所有的文件,对应的属性设值.

2、SpringBoot自动配置好了管理国际化资源文件的组件;
MessageSourceAutoConfiguration #springboot默认注入的组件

@Configuration
@ConditionalOnMissingBean(value = MessageSource.class, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {

	private static final Resource[] NO_RESOURCES = {};

	@Bean
	@ConfigurationProperties(prefix = "spring.messages")
	public MessageSourceProperties messageSourceProperties() {
		return new MessageSourceProperties();
	}
	//读取配置文件的基本路劲
	private Resource[] getResources(ClassLoader classLoader, String name) {
			String target = name.replace('.', '/');
			try {
				return new PathMatchingResourcePatternResolver(classLoader)
						.getResources("classpath*:" + target + ".properties");
			}
			catch (Exception ex) {
				return NO_RESOURCES;
			}
		}
		//默认读取的配置文件
		@Override
		public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
			String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages");
			ConditionOutcome outcome = cache.get(basename);
			if (outcome == null) {
				outcome = getMatchOutcomeForBasename(context, basename);
				cache.put(basename, outcome);
			}
			return outcome;
		}	

说明:

  • 默认读取的配置文件是跟路劲下的 messages.properties
  • 如果要指定读取自定义的配置文件
# 国际化配置文件(包名.基础名)
spring.messages.basename=i18n.login

3、去页面获取国际化的值;
th:text="# {login.btn}"

<button class="btn btn‐lg btn‐primary btn‐block" type="submit" th:text="# {login.btn}">Sign in</button>

效果:根据浏览器语言设置的信息切换了国际化;

原理: 国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象);

如果要实现点击按钮实现国际化语言切换,则需要自定义LocaleResolver.

/**
 * 可以在连接上携带区域信息
 */
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) {

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值