正应了某人的话,java就这副德行,用了框架以后,代码是减少了,却多出一大堆比代码还复杂的配置。由于spring security3的配置繁多,所以用起来也不是太容易上手,整整研究了5,6天,才勉强把登录的验证做好。大概配置如下:
1.配置web.xml,这一步相对简单,只需要把应该加入的包加上,并且在xml文件中配上过滤器即可:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.配置applicationContext-security.xml,如下:
<!-- access DB for validation username and password -->
<beans:bean id="authFilter"
class="com.security.OXAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="rememberMeServices" ref="rememberMeServices"></beans:property>
<beans:property name="loginService" ref="loginService" />
<beans:property name="authenticationSuccessHandler"
ref="successHandler" />
<beans:property name="authenticationFailureHandler"
ref="failureHandler" />
<beans:property name="filterProcessesUrl" value="/j_spring_security_check"></beans:property>
</beans:bean>
<beans:bean id="successHandler"
class="com.security.OXAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/login" />
</beans:bean>
<beans:bean id="failureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<beans:property name="defaultFailureUrl" value="/login.jsp" />
</beans:bean>
这里我们是将OXAuthenticationFilter类作为过滤用的类,故在其property属性中加上了loginService,用以判断用户名密码是否存在并进入下一步的页面。successHandler这个bean,就是负责将验证成功后的路径导入/login;如果验证不成功,则通过failureHandler将页面弹回/login.jsp,并且根据页面的设定而提示用户,配置如下:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
<span id="loginError" style="color:red;">UserName or Password error! </span>
</c:if>
这样下来,spring security3配置登录验证就完成了。