栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Security - 10 使用内置的国际化配置

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Security - 10 使用内置的国际化配置

文章目录

环境项目结构默认的国际化配置使用内置的国际化配置测试参考

环境

操作系统:

Windows 10 x64

集成开发环境:

Spring Tool Suite 4 
Version: 4.12.1.RELEASE
Build Id: 202110260750

浏览器(客户端):

Google Chrome
版本 97.0.4692.71(正式版本) (64 位)
项目结构

参考:Spring Security - 07 在内存中认证(添加用户到内存中)

默认的国际化配置

Spring Security 默认使用的国际化配置是 spring-security-core-x.x.x.jar 中的 org.springframework.security.messages.properties 文件:

当我们使用不存在的用户名或错误的密码进行身份验证,返回的是“Bad credentials”:

使用内置的国际化配置

为了方便当地用户,我们应该返回适用于当地用户的语言。

在 spring-security-core-x.x.x.jar 的 org.springframework.security 包中,内置了许多消息配置文件。其中,messages_zh_CN.properties 文件适用于中国大陆环境:

要使用 Spring Security 内置的消息配置文件,我们可以提供一个 ReloadableResourceBundleMessageSource。

新建 ReloadableResourceConfiguration 配置类,提供一个 ReloadableResourceBundleMessageSource:

package com.mk.security.config.annotation.web.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

@Configuration
public class ReloadableResourceConfiguration {
    
    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setbasename("classpath:org/springframework/security/messages_zh_CN");
        
        return messageSource;
    }
}

修改 application.yaml 配置文件:

spring:
  thymeleaf:
    cache: false
测试

完成之后,启动应用。打开浏览器,访问 http://localhost:8080/login,让我们使用不存在的用户名或错误的密码进行身份验证,看看效果:

参考

Spring Security / Servlet Applications / Integrations / Localization

定制 Spring Security 错误提示信息

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/754443.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号