环境项目结构默认的国际化配置使用内置的国际化配置测试参考
环境操作系统:
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 错误提示信息



