SpringBoot Web开发(5) 开发页面国际化+登录拦截

SpringBoot Web开发(5) 开发页面国际化+登录拦截

一、页面国际化

页面国际化目的:根据浏览器语言设置的信息对页面信息进行切换,或者用户点击链接自行对页面语言信息进行切换。

**效果演示:**当浏览器语言设置为英文优先时,或者用户点击页面“English”选项时,页面如下图所示:

kbHXrD.png

当浏览器语言设置为中文优先时,或者用户点击页面“中文”选项时,页面如下图所示:

kbHjqe.png

下面说说具体的实现步骤及实现原理:

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

在resources资源文件夹下创建“i18n”国际化文件夹,在其中编写国际化配置文件。

kbHb26.png

二、SpringBoot自动配置好了管理国际化资源文件的组件,部分源码如下:

@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
   
    private static final Resource[] NO_RESOURCES = new Resource[0];

    public MessageSourceAutoConfiguration() {
   
    }

    @Bean
    @ConfigurationProperties(
        prefix = "spring.messages"
    )
    
    .....
 @Bean
    public MessageSource messageSource(MessageSourceProperties properties) {
   
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        if (StringUtils.hasText(properties.getBasename())) {
   
            //设置国际化资源文件的基础名(去掉语言国家代码的) 
  messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
        }

        if (properties.getEncoding() != null) {
   
            messageSource.setDefaultEncoding(properties.getEncoding().name());
        }

        messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
        Duration cacheDuration = properties.getCacheDuration();
        if (cacheDuration != null) {
   
            messageSource.setCacheMillis(cacheDuration.toMillis());
        }

        messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
        messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
        return messageSource;
    }
}

三、在application.properties中配置国际化文件夹的路径

spring.messages.basename=i18n.login

四、在页面上获取国际化的值

<!DOCTYPE html>
 <!--引入Thymeleaf模板名称空间-->
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<link href="favicon.ico" rel="shortcut icon">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
		<meta name="description" content="">
		<meta name="author" content=""
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值