1、配置web.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>
<context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/application-context.xml, /WEB-INF/application-security.xml </param-value> </context-param>
2、application-security.xml 的配置
(1)、web安全服务是使用<http>
元素配置
<http auto-config="true">
//对站点下的login.jsp不进行拦截过滤
<intercept-url pattern="/login.jsp*" filters="none"/>
//保护应用程序中的所有URL,只有拥有ROLE_USER
角色的用户才能访问
<intercept-url pattern="/*" access="ROLE_USER" />
<form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" />
<logout logout-success-url="/login.jsp" />
</http>
(2)、<authentication-provider>配置
固定用户方式:
<authentication-provider> <user-service> <user name="admin" password="admin123" authorities="ROLE_USER" /> </user-service>
读取配置文件
<authentication-provider> <user-service id="userDetailsService" properties="users.properties"/> </authentication-provider>
jdbc读取数据库
<authentication-provider> <jdbc-user-service data-source-ref="dataSource" users-by-username-query="select id,password,enabled from users where username=?" authorities-by-username-query="select userid,authority from user_authorities where userid=?" /> </authentication-provider>
3、login.jsp页面
<table width="400" align="center"><tr><td height="60"> <c:if test="${not empty param.error}"> <font color="red"> 用户名密码错误,请重试。 </font> </c:if> </td></tr></table> <table width="400" align="center" ><tr><td> <div class="grid" align="center"> <form action="<c:url value="/j_spring_security_check"/>" method="post"> <table class="gridbody" width="360" cellpadding="1" cellspacing="0" rules="all"> <tr class="griditem"><td height="180" align="center"> <table> <tr class="griditem"> <td ><img src="images/loginexit.png" /></td> <td><B>用户登陆</B></td></tr> <tr class="griditem"> <td width="50" ><label for="username">用户名:</label></td> <td><input type="text" id="username" name="j_username" value="<c:out value="${SPRING_SECURITY_LAST_USERNAME}"/>" size="20"/></td> </tr> <tr class="griditem"> <td width="50"><label for="password">密 码:</label></td> <td><input type="password" id="password" name="j_password" value="" size="21"/></td> </tr> <tr><td></td></tr> <tr> <td></td> <td><input type="image" name="submit" alt="登陆" src="images/loginbtn.png" onclick="submit()" ></input></td> </tr></table> </td></tr> </table> </form> </div> </td></tr></table>