1、新建一个Web工程,将以下Jar包导进工程:acegi-security-1.0.3.jar、commons-codec-1.3.jar、commons-logging-1.0.4.jar、mysql-connector-java-5.0.3-bin.jar和spring.jar。
2、在MySql中执行以下SQL语句:
Drop TABLE IF EXISTS `test`.`student`; Create TABLE `test`.`student` ( `name` varchar(40) NOT NULL, `psw` varchar(10) NOT NULL, `enabled` boolean ); insert into student values("lanp","lanpiao",true); insert into student values("ph","ph",true); insert into student values("wxh","wxh",true); Drop TABLE IF EXISTS `test`.`user_privileges`; Create TABLE `test`.`user_privileges` ( `name` varchar(40) NOT NULL, `privilege` varchar(40) NOT NULL ); insert into user_privileges values("lanp","ROLE_PRESIDENT"); insert into user_privileges values("ph","ROLE_SUPERVISOR"); insert into user_privileges values("wxh","ROLE_USER");
3、web.xml配置信息如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>MyAcegiProj</display-name> <!-- context-param --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/applicationContext-acegi-security.xml </param-value> </context-param> <!--acegi 的filter链代理--> <filter> <filter-name>MyAcegiProjFilterChainProxy</filter-name> <filter-class> org.acegisecurity.util.FilterToBeanProxy </filter-class> <init-param> <param-name>targetClass</param-name> <param-value> org.acegisecurity.util.FilterChainProxy </param-value> </init-param> </filter> <filter-mapping> <filter-name>MyAcegiProjFilterChainProxy</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 装载应用软件的Spring上下文 要由WebapplicationContextUtils.getWebApplicationnContext(servletContext)得到. --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
4、applicationContext-acegi-security.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd" default-autowire="byName" default-lazy-init="true"> <!-- ================================数据源配置===================================== --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://127.0.0.1:3306/test</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>157891</value> </property> </bean> <!-- ======================== FILTER CHAIN ======================= --> <bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy" > <property name="filterInvocationDefinitionSource" > <value > CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON PATTERN_TYPE_APACHE_ANT /** =authenticationProcessingFilter,logoutFilter,rememberMeProcessingFilter,exceptionTranslationFilter </value> </property> </bean> <!-- ======================== 认证filter ======================= --> <!-- 表单认证处理filter --> <bean id="authenticationProcessingFilter" class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter"> <property name="authenticationManager" ref="authenticationManager"/> <property name="authenticationFailureUrl" value="/acegilogin.jsp?login_error=1"/> <property name="defaultTargetUrl" value="/userinfo.jsp"/> <property name="filterProcessesUrl" value="/j_acegi_security_check"/> </bean> <!-- 利用cookie自动登陆filter --> <bean id="rememberMeProcessingFilter" class="org.acegisecurity.ui.rememberme.RememberMeProcessingFilter"> <property name="authenticationManager" ref="authenticationManager"/> <property name="rememberMeServices" ref="rememberMeServices"/> </bean> <bean id="rememberMeServices" class="org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices"> <property name="userDetailsService" ref="jdbcDaoImpl"/> <property name="key" value="javargb"/> </bean> <bean id="rememberMeAuthenticationProvider" class="org.acegisecurity.providers.rememberme.RememberMeAuthenticationProvider"> <property name="key" value="javargb"/> </bean> <!-- 注销处理filter --> <bean id="logoutFilter" class="org.acegisecurity.ui.logout.LogoutFilter"> <constructor-arg value="/acegilogin.jsp"/> <!-- URL redirected to after logout --> <constructor-arg> <list> <ref bean="rememberMeServices"/> <bean class="org.acegisecurity.ui.logout.SecurityContextLogoutHandler"/> </list> </constructor-arg> </bean> <!-- 认证管理器 --> <bean id="authenticationManager" class="org.acegisecurity.providers.ProviderManager"> <property name="providers"><!-- 可有多个认证提供器,其中一个证通过就可以了 --> <list> <ref local="daoAuthenticationProvider"/> <ref local="rememberMeAuthenticationProvider"/> </list> </property> </bean> <bean id="daoAuthenticationProvider" class="org.acegisecurity.providers.dao.DaoAuthenticationProvider"> <property name="userDetailsService" ref="jdbcDaoImpl"/> </bean> <bean id="jdbcDaoImpl" class="org.acegisecurity.userdetails.jdbc.JdbcDaoImpl"> <property name="dataSource"><ref bean="dataSource"/></property> <property name="usersByUsernameQuery"> <value>SELECT name, psw, enabled FROM student WHERE name=?</value> </property> <property name="authoritiesByUsernameQuery"> <value>SELECT name, privilege FROM user_privileges where name=?</value> </property> </bean> <!-- 异常处理filter --> <bean id="exceptionTranslationFilter" class="org.acegisecurity.ui.ExceptionTranslationFilter"> <property name="authenticationEntryPoint"> <bean class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint"> <property name="loginFormUrl" value="/acegilogin.jsp"/> <property name="forceHttps" value="false"/> </bean> </property> <property name="accessDeniedHandler"> <bean class="org.acegisecurity.ui.AccessDeniedHandlerImpl"> <property name="errorPage" value="/accessDenied.jsp"/> </bean> </property> </bean> </beans>
5、index.jsp页面代码如下:
<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <META HTTP-EQUIV="Refresh" CONTENT="0;URL=userinfo.jsp"> </head> <body> <p>Loading ...</p> </body> </html>
6、acegilogin.jsp登陆页面信息如下:
<%@ page language="java" pageEncoding="UTF-8"%> <%@ page import="org.acegisecurity.ui.AbstractProcessingFilter" %> <%@ page import="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter" %> <%@ page import="org.acegisecurity.AuthenticationException" %> <html> <head> <title>Login Page</title> </head> <body> <h1>Login</h1> <% String strError = request.getParameter("login_error"); if (null != strError){ %> <font color="red"> 你的登陆失败,请重试。<BR><BR> 原因: <%= ((AuthenticationException) session.getAttribute(AbstractProcessingFilter.ACEGI_SECURITY_LAST_EXCEPTION_KEY)).getMessage() %> </font> <% }//end if %> <form action="j_acegi_security_check" method="POST"> <table> <tr><td>User:</td><td><input type='text' name='j_username' value='<%= session.getAttribute(AuthenticationProcessingFilter.ACEGI_SECURITY_LAST_USERNAME_KEY) %>'></td></tr> <tr><td>Password:</td><td><input type='password' name='j_password'></td></tr> <tr><td><input type="checkbox" name="_acegi_security_remember_me"></td><td>2周内自动登录</td></tr> <tr><td colspan='2'><input name="submit" type="submit"></td></tr> <tr><td colspan='2'><input name="reset" type="reset"></td></tr> </table> </form> </body> </html>
7、userinfo.jsp用户信息页面代码如下:
<%@ page language="java" pageEncoding="UTF-8"%> <%@ page import="org.acegisecurity.context.SecurityContextHolder"%> <%@ page import="org.acegisecurity.userdetails.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>User Info Page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> 当前用户: <% Object obj = SecurityContextHolder.getContext().getAuthentication(); if (null != obj){ Object userDetail = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = ""; if (userDetail instanceof UserDetails) { username = ((UserDetails) userDetail).getUsername(); } else { username = userDetail.toString(); } out.print(username); out.print("<br><a href=\"j_acegi_logout\">注销</a>"); }else{ out.print("当前没有有效的用户"); out.print("<br><a href=\"acegilogin.jsp\">登陆</a>"); } %> </body> </html>
OK,3Q!
其中借鉴了一些别人的东西