在自定义登录页面输入的帐号密码错误,页面中没有任何错误消息提示,所以需要将提示信息显示出来
Spring Security 框架将所有的错误信息都定义成了异常,并且提供了国际化的资源文件。这个资源文件在 spring-security-core-3.0.7.RELEASE.jar文件中
在spring配置文件applicationContext.xml中配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security/spring-security-3.0.xsd"
default-lazy-init="true">
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames" value="classpath:org/springframework/security/messages_zh_CN"></property>
</bean>
</beans>
在jsp页面上获取提示信息,由于Spring Security 框架将抛出的异常对象放到了 session 范围中,key 是: SPRING_SECURITY_LAST_EXCEPTION,取出的是异常对象,所以还要调用getMessage()方法取出真正的错误信息
${sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message }
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录页面</title>
</head>
<body>
${sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message }
<form name='f' action='/springSecurity/j_spring_security_check'
method='POST'>
<table>
<tr>
<td>用户名:</td>
<td><input type='text' name='j_username' value='user'></td>
</tr>
<tr>
<td>密码:</td>
<td><input type='password' name='j_password' /></td>
</tr>
<tr>
<td ><input name="submit" type="submit" value="登录"/></td>
<td ><input name="reset" type="reset" value="重置"/></td>
</tr>
</table>
</form>
</body>
</html>
查看messages_zh_CN.properties中
AbstractUserDetailsAuthenticationProvider.badCredentials=\u574F\u7684\u51ED\u8BC1对应的就是坏的凭证
我们可以自定义错误消息提示
创建一个messages_zh_CN.properties文件
重写里面AbstractUserDetailsAuthenticationProvider.badCredentials的值
修改applicationContext.xml配置文件
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames" value="classpath:message_zh_CN"></property>
</bean>
重新在登录,发现错误提示信息改变了