使用Spring Security实现权限管理

1、技术目标

 

 

  • 了解并创建Security框架所需数据表
  • 为项目添加Spring Security框架
  • 掌握Security框架配置
  • 应用Security框架为项目的CRUD操作绑定权限

 

 

注意:本文所用项目为"影片管理",参看

http://hotstrong.iteye.com/blog/1156785

 

2、权限管理需求描述

 

  • 为系统中的每个操作定义权限,如定义4个权限:  1)超级权限,可以使用所有操作  2)添加影片权限  3)修改影片权限  4)删除影片权限
  • 为系统设置管理员帐号、密码
  • 为系统创建权限组,每个权限组可以配置多个操作权限,如创建2个权限组:  1)"Administrator"权限组,具有超级权限  2)"影片维护"权限组,具有添加影片、修改影片权限
  • 可将管理员加入权限组,管理员登录后具备权限组所对应操作权限
  • 管理员可不属于某权限组,可为管理员直接分配权限

 

 

3、使用准备

 

3.1)在数据库中创建6张表

 

t_admin        管理员帐号表

t_role权限表

t_group        权限组表

t_group_role权限组对应权限表

t_group_user管理员所属权限组表

t_user_role管理员对应权限表

 

建表SQL语句如下:

 

 

Sql代码 复制代码 收藏代码
  1. SET FOREIGN_KEY_CHECKS=0;  
  2.     ------------------------------  
  3.     -- 创建管理员帐号表t_admin  
  4.     -- ----------------------------  
  5.     CREATE TABLE `t_admin` (  
  6.       `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,  
  7.       `passwd` varchar(12) NOT NULL DEFAULT '' COMMENT '用户密码',  
  8.       `nickname` varchar(20) NOT NULL DEFAULT '' COMMENT '用户名字',  
  9.       `phoneno` varchar(32) NOT NULL DEFAULT '' COMMENT '电话号码',  
  10.       PRIMARY KEY (`id`)  
  11.     ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;  
  12.   
  13.     -- ----------------------------  
  14.     -- 添加3个管理帐号   
  15.     -- ----------------------------  
  16.     INSERT INTO `t_admin` VALUES ('1', 'admin', 'admin', '');  
  17.     INSERT INTO `t_admin` VALUES ('4', '123456', 'test', '');  
  18.     INSERT INTO `t_admin` VALUES ('5', '111111', '111111', '');  
  19.       
  20.     -- ----------------------------  
  21.     -- 创建权限表t_role  
  22.     -- ----------------------------  
  23.     CREATE TABLE `t_role` (  
  24.       `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,  
  25.       `role` varchar(40) NOT NULL DEFAULT '',  
  26.       `descpt` varchar(40) NOT NULL DEFAULT '' COMMENT '角色描述',  
  27.       `category` varchar(40) NOT NULL DEFAULT '' COMMENT '分类',  
  28.       PRIMARY KEY (`id`)  
  29.     ) ENGINE=InnoDB AUTO_INCREMENT=60 DEFAULT CHARSET=utf8;  
  30.   
  31.     -- ----------------------------  
  32.     -- 加入4个操作权限  
  33.     -- ----------------------------  
  34.     INSERT INTO `t_role` VALUES ('1', 'ROLE_ADMIN', '系统管理员', '系统管理员');  
  35.     INSERT INTO `t_role` VALUES ('2', 'ROLE_UPDATE_FILM', '修改', '影片管理');  
  36.     INSERT INTO `t_role` VALUES ('3', 'ROLE_DELETE_FILM', '删除', '影片管理');  
  37.     INSERT INTO `t_role` VALUES ('4', 'ROLE_ADD_FILM', '添加', '影片管理');  
  38.   
  39.     -- ----------------------------  
  40.     -- 创建权限组表  
  41.     -- ----------------------------  
  42.     CREATE TABLE `t_group` (  
  43.       `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,  
  44.       `groupname` varchar(50) NOT NULL DEFAULT '',  
  45.       PRIMARY KEY (`id`)  
  46.     ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;  
  47.   
  48.     -- ----------------------------  
  49.     -- 添加2个权限组  
  50.     -- ----------------------------  
  51.     INSERT INTO `t_group` VALUES ('1', 'Administrator');  
  52.     INSERT INTO `t_group` VALUES ('2', '影片维护');  
  53.   
  54.     -- ----------------------------  
  55.     -- 创建权限组对应权限表t_group_role  
  56.     -- ----------------------------  
  57.     CREATE TABLE `t_group_role` (  
  58.       `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,  
  59.       `groupid` bigint(20) unsigned NOT NULL,  
  60.       `roleid` bigint(20) unsigned NOT NULL,  
  61.       PRIMARY KEY (`id`),  
  62.       UNIQUE KEY `groupid2` (`groupid`,`roleid`),  
  63.       KEY `roleid` (`roleid`),  
  64.       CONSTRAINT `t_group_role_ibfk_1` FOREIGN KEY (`groupid`) REFERENCES `t_group` (`id`),  
  65.       CONSTRAINT `t_group_role_ibfk_2` FOREIGN KEY (`roleid`) REFERENCES `t_role` (`id`)  
  66.     ) ENGINE=InnoDB AUTO_INCREMENT=83 DEFAULT CHARSET=utf8;  
  67.   
  68.     -- ----------------------------  
  69.     -- 加入权限组与权限的对应关系  
  70.     -- ----------------------------  
  71.     INSERT INTO `t_group_role` VALUES ('1', '1', '1');  
  72.     INSERT INTO `t_group_role` VALUES ('2', '2', '2');  
  73.     INSERT INTO `t_group_role` VALUES ('4', '2', '4');  
  74.   
  75.     -- ----------------------------  
  76.     -- 创建管理员所属权限组表t_group_user  
  77.     -- ----------------------------  
  78.     CREATE TABLE `t_group_user` (  
  79.       `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,  
  80.       `userid` bigint(20) unsigned NOT NULL,  
  81.       `groupid` bigint(20) unsigned NOT NULL,  
  82.       PRIMARY KEY (`id`),  
  83.       KEY `userid` (`userid`),  
  84.       KEY `groupid` (`groupid`),  
  85.       CONSTRAINT `t_group_user_ibfk_2` FOREIGN KEY (`groupid`) REFERENCES `t_group` (`id`),  
  86.       CONSTRAINT `t_group_user_ibfk_3` FOREIGN KEY (`userid`) REFERENCES `t_admin` (`id`)  
  87.     ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;  
  88.   
  89.     -- ----------------------------  
  90.     -- 将管理员加入权限组  
  91.     -- ----------------------------  
  92.     INSERT INTO `t_group_user` VALUES ('1', '1', '1');  
  93.     INSERT INTO `t_group_user` VALUES ('2', '4', '2');  
  94.   
  95.     -- ----------------------------  
  96.     -- 创建管理员对应权限表t_user_role  
  97.     -- 设置该表可跳过权限组,为管理员直接分配权限  
  98.     -- ----------------------------  
  99.     CREATE TABLE `t_user_role` (  
  100.       `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,  
  101.       `userid` bigint(20) unsigned NOT NULL,  
  102.       `roleid` bigint(20) unsigned NOT NULL,  
  103.       PRIMARY KEY (`id`),  
  104.       KEY `userid` (`userid`),  
  105.       KEY `roleid` (`roleid`),  
  106.       CONSTRAINT `t_user_role_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `t_admin` (`id`),  
  107.       CONSTRAINT `t_user_role_ibfk_2` FOREIGN KEY (`roleid`) REFERENCES `t_role` (`id`)  
  108.     ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;  
  109.       
SET FOREIGN_KEY_CHECKS=0;
	------------------------------
	-- 创建管理员帐号表t_admin
	-- ----------------------------
	CREATE TABLE `t_admin` (
	  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
	  `passwd` varchar(12) NOT NULL DEFAULT '' COMMENT '用户密码',
	  `nickname` varchar(20) NOT NULL DEFAULT '' COMMENT '用户名字',
	  `phoneno` varchar(32) NOT NULL DEFAULT '' COMMENT '电话号码',
	  PRIMARY KEY (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

	-- ----------------------------
	-- 添加3个管理帐号 
	-- ----------------------------
	INSERT INTO `t_admin` VALUES ('1', 'admin', 'admin', '');
	INSERT INTO `t_admin` VALUES ('4', '123456', 'test', '');
	INSERT INTO `t_admin` VALUES ('5', '111111', '111111', '');
	
	-- ----------------------------
	-- 创建权限表t_role
	-- ----------------------------
	CREATE TABLE `t_role` (
	  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
	  `role` varchar(40) NOT NULL DEFAULT '',
	  `descpt` varchar(40) NOT NULL DEFAULT '' COMMENT '角色描述',
	  `category` varchar(40) NOT NULL DEFAULT '' COMMENT '分类',
	  PRIMARY KEY (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=60 DEFAULT CHARSET=utf8;

	-- ----------------------------
	-- 加入4个操作权限
	-- ----------------------------
	INSERT INTO `t_role` VALUES ('1', 'ROLE_ADMIN', '系统管理员', '系统管理员');
	INSERT INTO `t_role` VALUES ('2', 'ROLE_UPDATE_FILM', '修改', '影片管理');
	INSERT INTO `t_role` VALUES ('3', 'ROLE_DELETE_FILM', '删除', '影片管理');
	INSERT INTO `t_role` VALUES ('4', 'ROLE_ADD_FILM', '添加', '影片管理');

	-- ----------------------------
	-- 创建权限组表
	-- ----------------------------
	CREATE TABLE `t_group` (
	  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
	  `groupname` varchar(50) NOT NULL DEFAULT '',
	  PRIMARY KEY (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

	-- ----------------------------
	-- 添加2个权限组
	-- ----------------------------
	INSERT INTO `t_group` VALUES ('1', 'Administrator');
	INSERT INTO `t_group` VALUES ('2', '影片维护');

	-- ----------------------------
	-- 创建权限组对应权限表t_group_role
	-- ----------------------------
	CREATE TABLE `t_group_role` (
	  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
	  `groupid` bigint(20) unsigned NOT NULL,
	  `roleid` bigint(20) unsigned NOT NULL,
	  PRIMARY KEY (`id`),
	  UNIQUE KEY `groupid2` (`groupid`,`roleid`),
	  KEY `roleid` (`roleid`),
	  CONSTRAINT `t_group_role_ibfk_1` FOREIGN KEY (`groupid`) REFERENCES `t_group` (`id`),
	  CONSTRAINT `t_group_role_ibfk_2` FOREIGN KEY (`roleid`) REFERENCES `t_role` (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=83 DEFAULT CHARSET=utf8;

	-- ----------------------------
	-- 加入权限组与权限的对应关系
	-- ----------------------------
	INSERT INTO `t_group_role` VALUES ('1', '1', '1');
	INSERT INTO `t_group_role` VALUES ('2', '2', '2');
	INSERT INTO `t_group_role` VALUES ('4', '2', '4');

	-- ----------------------------
	-- 创建管理员所属权限组表t_group_user
	-- ----------------------------
	CREATE TABLE `t_group_user` (
	  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
	  `userid` bigint(20) unsigned NOT NULL,
	  `groupid` bigint(20) unsigned NOT NULL,
	  PRIMARY KEY (`id`),
	  KEY `userid` (`userid`),
	  KEY `groupid` (`groupid`),
	  CONSTRAINT `t_group_user_ibfk_2` FOREIGN KEY (`groupid`) REFERENCES `t_group` (`id`),
	  CONSTRAINT `t_group_user_ibfk_3` FOREIGN KEY (`userid`) REFERENCES `t_admin` (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

	-- ----------------------------
	-- 将管理员加入权限组
	-- ----------------------------
	INSERT INTO `t_group_user` VALUES ('1', '1', '1');
	INSERT INTO `t_group_user` VALUES ('2', '4', '2');

	-- ----------------------------
	-- 创建管理员对应权限表t_user_role
	-- 设置该表可跳过权限组,为管理员直接分配权限
	-- ----------------------------
	CREATE TABLE `t_user_role` (
	  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
	  `userid` bigint(20) unsigned NOT NULL,
	  `roleid` bigint(20) unsigned NOT NULL,
	  PRIMARY KEY (`id`),
	  KEY `userid` (`userid`),
	  KEY `roleid` (`roleid`),
	  CONSTRAINT `t_user_role_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `t_admin` (`id`),
	  CONSTRAINT `t_user_role_ibfk_2` FOREIGN KEY (`roleid`) REFERENCES `t_role` (`id`)
	) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
	

 

3.2)在项目中新增如下jar包(security框架所需jar包):

 

    注意:以下jar包本文已提供下载

 

spring-security-config-3.1.0.RC2.jar

spring-security-core-3.1.0.RC2.jar

spring-security-taglibs-3.1.0.RC2.jar

spring-security-web-3.1.0.RC2.jar

 

3.3)创建如下包,放置登录验证过滤器代码:

 

com.xxx.security

 

3.4)在src下创建Spring配置文件applicationContext-security.xml,内容如下:

 

 

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3.     <beans:beans xmlns="http://www.springframework.org/schema/security"  
  4.         xmlns:b="http://www.springframework.org/schema/beans" xmlns:beans="http://www.springframework.org/schema/beans"  
  5.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.                             http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">  
  8.       
  9.     <!-- 这里进行配置 -->  
  10.       
  11. </beans:beans>  
<?xml version="1.0" encoding="UTF-8"?>

	<beans:beans xmlns="http://www.springframework.org/schema/security"
		xmlns:b="http://www.springframework.org/schema/beans" xmlns:beans="http://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
	
	<!-- 这里进行配置 -->
	
</beans:beans>

 

3.5)在web.xml中加入security配置,如下:

 

 

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.     <web-app version="2.5"   
  3.         xmlns="http://java.sun.com/xml/ns/javaee"   
  4.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.         http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.       <welcome-file-list>  
  8.         <welcome-file>index.jsp</welcome-file>  
  9.       </welcome-file-list>  
  10.         
  11.         <context-param>  
  12.             <param-name>contextConfigLocation</param-name>  
  13.             <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>  
  14.         </context-param>  
  15.           
  16.         <!-- 配置Spring Security -->  
  17.         <filter>  
  18.             <filter-name>springSecurityFilterChain</filter-name>  
  19.             <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  20.         </filter>  
  21.         <filter-mapping>  
  22.             <filter-name>springSecurityFilterChain</filter-name>  
  23.             <url-pattern>/*</url-pattern>  
  24.         </filter-mapping>  
  25.           
  26.         <filter>  
  27.             <filter-name>struts2</filter-name>  
  28.             <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  29.         </filter>  
  30.         <filter-mapping>  
  31.             <filter-name>struts2</filter-name>  
  32.             <url-pattern>/*</url-pattern>  
  33.         </filter-mapping>  
  34.         <listener>  
  35.             <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  36.         </listener>  
  37.     </web-app>  
<?xml version="1.0" encoding="UTF-8"?>
	<web-app version="2.5" 
		xmlns="http://java.sun.com/xml/ns/javaee" 
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
		http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	  <welcome-file-list>
	    <welcome-file>index.jsp</welcome-file>
	  </welcome-file-list>
	  
	  	<context-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>
		</context-param>
		
		<!-- 配置Spring Security -->
		<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>
		
		<filter>
			<filter-name>struts2</filter-name>
			<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
		</filter>
		<filter-mapping>
			<filter-name>struts2</filter-name>
			<url-pattern>/*</url-pattern>
		</filter-mapping>
		<listener>
			<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
		</listener>
	</web-app>

 

 

4、站点根路径下创建登录页面login.jsp,代码如下:

 

 

Html代码 复制代码 收藏代码
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ taglib prefix="s" uri="/struts-tags"%>  
  4. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  5. <%   
  6. String path = request.getContextPath();  
  7. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;   
  8. %>  
  9. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  10. <html xmlns="http://www.w3.org/1999/xhtml">  
  11. <head>  
  12. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  13. <title>后台登录</title>  
  14. </head>  
  15. <body onload="document.loginForm.j_username.focus();">  
  16.     <!-- 登录表单 -->  
  17.     <form name="loginForm" action="<c:url value='/j_spring_security_check'/>" method="post">  
  18.         <!-- 登录失败后,显示之前的登录名 -->  
  19.         用户名:<input type='text' name='j_username' class="txtinput"  
  20.         value='<c:if test="${not empty param.login_error}" >  
  21.         <c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>' />  
  22.         <br />  
  23.         密码:<input type='password' name='j_password' class="txtinput" />  
  24.         <br />  
  25.           
  26.         <input type="checkbox" name="_spring_security_remember_me" />  
  27.         &nbsp;保存登录信息  
  28.         <input name="submit" type="submit" value="提交" />  
  29.         <input name="reset" type="reset" value="重置" />  
  30.           
  31.     </form>  
  32.     <br />  
  33.     <!-- 显示登录失败原因 -->  
  34.     <c:if test="${not empty param.error}">  
  35.         <font color="red"> 登录失败<br />  
  36.         <br />  
  37.         原因: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />. </font>  
  38.     </c:if>  
  39. </body>  
  40. </html>  
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% 
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>后台登录</title>
</head>
<body onload="document.loginForm.j_username.focus();">
	<!-- 登录表单 -->
	<form name="loginForm" action="<c:url value='/j_spring_security_check'/>" method="post">
		<!-- 登录失败后,显示之前的登录名 -->
		用户名:<input type='text' name='j_username' class="txtinput"
		value='<c:if test="${not empty param.login_error}" >
		<c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>' />
		<br />
		密码:<input type='password' name='j_password' class="txtinput" />
		<br />
		
		<input type="checkbox" name="_spring_security_remember_me" />
		&nbsp;保存登录信息
		<input name="submit" type="submit" value="提交" />
		<input name="reset" type="reset" value="重置" />
		
	</form>
	<br />
	<!-- 显示登录失败原因 -->
	<c:if test="${not empty param.error}">
		<font color="red"> 登录失败<br />
		<br />
		原因: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />. </font>
	</c:if>
</body>
</html>

 

 

5、站点根路径下创建注销页面loggedout.jsp,代码如下:

 

 

Html代码 复制代码 收藏代码
  1. <%@page session="false" %>  
  2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3. <%@ page pageEncoding="UTF-8"%>  
  4. <%   
  5. String path = request.getContextPath();  
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;   
  7. %>  
  8. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  9. <html xmlns="http://www.w3.org/1999/xhtml">  
  10.   <head>  
  11.       <meta http-equiv="content-type" content="text/html; charset=UTF-8" />  
  12.       <title>登出</title>  
  13.   </head>  
  14. <body>  
  15. 你已经退出。   
  16. <href="<c:url value='/login.jsp'/>">点击这里登录</a>  
  17. </body>  
  18. </html>  
<%@page session="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page pageEncoding="UTF-8"%>
<% 
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
      <title>登出</title>
  </head>
<body>
你已经退出。 
<a href="<c:url value='/login.jsp'/>">点击这里登录</a>
</body>
</html>

 

 

6、站点根路径下创建HttpSession超时提示页面timeout.jsp,代码如下:

 

 

Html代码 复制代码 收藏代码
  1. <%@page session="false" %>  
  2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3. <%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>  
  4. <%  
  5. String path = request.getContextPath();  
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;   
  7. %>  
  8. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  9. <html xmlns="http://www.w3.org/1999/xhtml">  
  10.   <head>  
  11.       <title>用户失效</title>  
  12.   </head>  
  13. <body>  
  14. 你的登录已经失效,请重新登录。   
  15. <br />  
  16. <href="<c:url value='/login.jsp'/>" >  
  17. 点击这里登录</a>  
  18. </body>  
  19. </html>  
<%@page session="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
      <title>用户失效</title>
  </head>
<body>
你的登录已经失效,请重新登录。 
<br />
<a href="<c:url value='/login.jsp'/>" >
点击这里登录</a>
</body>
</html>

 

 

7、在com.xxx.security包下创建登录验证过滤器,该过滤器可用于在管理员登录时进行日志记录等相关操作,包括两个类:

 

 

  • LoginUsernamePasswordAuthenticationFilter
  • LoginSuccessHandler

 

7.1)LoginUsernamePasswordAuthenticationFilter代码如下:

 

 

Java代码 复制代码 收藏代码
  1. package com.xxx.security;  
  2. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;  
  3.   
  4. public class LoginUsernamePasswordAuthenticationFilter extends  
  5.         UsernamePasswordAuthenticationFilter {  
  6.       
  7. }  
package com.xxx.security;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class LoginUsernamePasswordAuthenticationFilter extends
		UsernamePasswordAuthenticationFilter {
	
}

 

7.2)LoginSuccessHandler代码如下:

 

 

Java代码 复制代码 收藏代码
  1. package com.xxx.security;  
  2.   
  3. import java.io.IOException;  
  4. import javax.servlet.ServletException;  
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7. import org.springframework.security.core.Authentication;  
  8. import org.springframework.security.core.userdetails.UserDetails;  
  9. import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;  
  10.   
  11. /** 
  12.  * 处理管理员登录日志 
  13.  * 
  14.  */  
  15. public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{  
  16.       
  17.     @Override  
  18.     public void onAuthenticationSuccess(HttpServletRequest request,  
  19.             HttpServletResponse response, Authentication authentication) throws IOException,  
  20.             ServletException {  
  21.           
  22.         UserDetails userDetails = (UserDetails)authentication.getPrincipal();  
  23.           
  24.         //输出登录提示信息  
  25.         System.out.println("管理员 " + userDetails.getUsername() + " 登录");  
  26.               
  27.         super.onAuthenticationSuccess(request, response, authentication);  
  28.     }  
  29.       
  30. }  
package com.xxx.security;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

/**
 * 处理管理员登录日志
 *
 */
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication) throws IOException,
			ServletException {
		
		UserDetails userDetails = (UserDetails)authentication.getPrincipal();
		
		//输出登录提示信息
		System.out.println("管理员 " + userDetails.getUsername() + " 登录");
			
		super.onAuthenticationSuccess(request, response, authentication);
	}
	
}

 

 

8、在applicationContext-security.xml中加入权限管理配置,如下:

 

 

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans:beans xmlns="http://www.springframework.org/schema/security"  
  4.     xmlns:b="http://www.springframework.org/schema/beans" xmlns:beans="http://www.springframework.org/schema/beans"  
  5.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.                         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">  
  8.   
  9.     <http >  
  10.         <!-- 不拦截login.jsp -->  
  11.         <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY" />  
  12.         <!--仅拦截到manager下面的内容,具备access对应权限的-->  
  13.         <intercept-url pattern="/manager/**" access="ROLE_ADMIN,ROLE_UPDATE_FILM,ROLE_DELETE_FILM,ROLE_ADD_FILM" />  
  14.         <!-- 设置登录过滤器 -->  
  15.         <custom-filter before="FORM_LOGIN_FILTER" ref="authenticationProcessingFilter" />  
  16.         <!-- 登录表单设置 -->  
  17.         <form-login login-page="/login.jsp"  
  18.             default-target-url="/manager/films.jsp"  
  19.             authentication-failure-url="/login.jsp?error=true" />  
  20.           
  21.         <!-- 登出操作后跳转到该页面 -->  
  22.         <logout logout-success-url="/loggedout.jsp"  
  23.             delete-cookies="JSESSIONID" />  
  24.         <remember-me />  
  25.           
  26.         <!-- SESSION超时后跳转到该页面 -->  
  27.         <session-management invalid-session-url="/timeout.jsp">  
  28.         </session-management>  
  29.     </http>  
  30.       
  31.     <authentication-manager alias="authenticationManager">  
  32.         <authentication-provider>  
  33.             <!--   
  34.                 直接使用SQL语句查询登录帐号对应权限,  
  35.                 users-by-username-query:查询登录用户是否存在  
  36.                 authorities-by-username-query:查询登录用户权限(登录用户可以不属于任何组,从t_user_role表中获取权限)  
  37.                 group-authorities-by-username-query:查询登录用户所在组的权限  
  38.             -->  
  39.             <jdbc-user-service data-source-ref="dataSource"  
  40.             group-authorities-by-username-query="SELECT g.id,g.groupname,role.role  
  41.                              FROM t_group AS g   
  42.                              LEFT OUTER JOIN t_group_role AS grouprole ON (g.id = grouprole.groupid)  
  43.                              LEFT OUTER JOIN t_role AS role ON (role.id = grouprole.roleid)  
  44.                              LEFT OUTER JOIN t_group_user AS groupuser on (g.id = groupuser.groupid)  
  45.                              LEFT OUTER JOIN t_admin ON (t_admin.id = groupuser.userid)  
  46.                              WHERE t_admin.nickname = ?"  
  47.                 users-by-username-query="SELECT t_admin.nickname AS username,t_admin.passwd as password,'true' AS enabled  
  48.                              FROM t_admin  
  49.                              WHERE t_admin.nickname = ?"  
  50.                 authorities-by-username-query="SELECT t_admin.nickname AS username,role.role as authorities  
  51.                                FROM t_admin   
  52.                                LEFT OUTER JOIN t_user_role AS userrole ON(t_admin.id = userrole.userid)  
  53.                                LEFT OUTER JOIN t_role AS role ON (userrole.roleid = role.id)  
  54.                                WHERE t_admin.nickname = ?" />  
  55.         </authentication-provider>  
  56.     </authentication-manager>  
  57.       
  58.     <!-- 自定义消息 -->  
  59.     <b:bean id="messageSource"  
  60.         class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
  61.         <b:property name="basename"  
  62.             value="classpath:org/springframework/security/messages" />  
  63.     </b:bean>  
  64.       
  65.     <!-- 定制登录过滤器 -->  
  66.     <beans:bean id="loginSuccessHandler" class="com.xxx.security.LoginSuccessHandler">  
  67.         <b:property name="defaultTargetUrl">  
  68.             <!-- 登录成功后转发到该页面 -->  
  69.             <b:value>/manager/films.jsp</b:value>  
  70.         </b:property>  
  71.     </beans:bean>  
  72.     <beans:bean id="authenticationProcessingFilter" class="com.xxx.security.LoginUsernamePasswordAuthenticationFilter">    
  73.     <beans:property name="authenticationSuccessHandler" ref="loginSuccessHandler"></beans:property>    
  74.     <beans:property name="authenticationFailureHandler" ref="authenticationFailureHandler"></beans:property>    
  75.     <beans:property name="authenticationManager" ref="authenticationManager"></beans:property>    
  76.     </beans:bean>  
  77.     <beans:bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">    
  78.     <beans:property name="defaultFailureUrl">  
  79.         <!-- 登录失败后转发到该页面 -->  
  80.         <beans:value>/login.jsp?error=true</beans:value>    
  81.     </beans:property>  
  82.     </beans:bean>  
  83.       
  84. </beans:beans>  
<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:b="http://www.springframework.org/schema/beans" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

	<http >
		<!-- 不拦截login.jsp -->
		<intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
		<!--仅拦截到manager下面的内容,具备access对应权限的-->
		<intercept-url pattern="/manager/**" access="ROLE_ADMIN,ROLE_UPDATE_FILM,ROLE_DELETE_FILM,ROLE_ADD_FILM" />
		<!-- 设置登录过滤器 -->
		<custom-filter before="FORM_LOGIN_FILTER" ref="authenticationProcessingFilter" />
		<!-- 登录表单设置 -->
		<form-login login-page="/login.jsp"
			default-target-url="/manager/films.jsp"
			authentication-failure-url="/login.jsp?error=true" />
		
		<!-- 登出操作后跳转到该页面 -->
		<logout logout-success-url="/loggedout.jsp"
			delete-cookies="JSESSIONID" />
		<remember-me />
		
		<!-- SESSION超时后跳转到该页面 -->
		<session-management invalid-session-url="/timeout.jsp">
		</session-management>
	</http>
	
	<authentication-manager alias="authenticationManager">
		<authentication-provider>
			<!-- 
				直接使用SQL语句查询登录帐号对应权限,
				users-by-username-query:查询登录用户是否存在
				authorities-by-username-query:查询登录用户权限(登录用户可以不属于任何组,从t_user_role表中获取权限)
				group-authorities-by-username-query:查询登录用户所在组的权限
			-->
			<jdbc-user-service data-source-ref="dataSource"
			group-authorities-by-username-query="SELECT g.id,g.groupname,role.role
							 FROM t_group AS g 
							 LEFT OUTER JOIN t_group_role AS grouprole ON (g.id = grouprole.groupid)
							 LEFT OUTER JOIN t_role AS role ON (role.id = grouprole.roleid)
							 LEFT OUTER JOIN t_group_user AS groupuser on (g.id = groupuser.groupid)
							 LEFT OUTER JOIN t_admin ON (t_admin.id = groupuser.userid)
							 WHERE t_admin.nickname = ?"
				users-by-username-query="SELECT t_admin.nickname AS username,t_admin.passwd as password,'true' AS enabled
							 FROM t_admin
							 WHERE t_admin.nickname = ?"
				authorities-by-username-query="SELECT t_admin.nickname AS username,role.role as authorities
							   FROM t_admin 
							   LEFT OUTER JOIN t_user_role AS userrole ON(t_admin.id = userrole.userid)
							   LEFT OUTER JOIN t_role AS role ON (userrole.roleid = role.id)
							   WHERE t_admin.nickname = ?" />
		</authentication-provider>
	</authentication-manager>
	
	<!-- 自定义消息 -->
	<b:bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<b:property name="basename"
			value="classpath:org/springframework/security/messages" />
	</b:bean>
	
	<!-- 定制登录过滤器 -->
	<beans:bean id="loginSuccessHandler" class="com.xxx.security.LoginSuccessHandler">
		<b:property name="defaultTargetUrl">
			<!-- 登录成功后转发到该页面 -->
			<b:value>/manager/films.jsp</b:value>
		</b:property>
	</beans:bean>
	<beans:bean id="authenticationProcessingFilter" class="com.xxx.security.LoginUsernamePasswordAuthenticationFilter">  
	<beans:property name="authenticationSuccessHandler" ref="loginSuccessHandler"></beans:property>  
	<beans:property name="authenticationFailureHandler" ref="authenticationFailureHandler"></beans:property>  
	<beans:property name="authenticationManager" ref="authenticationManager"></beans:property>  
	</beans:bean>
	<beans:bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">  
	<beans:property name="defaultFailureUrl">
		<!-- 登录失败后转发到该页面 -->
		<beans:value>/login.jsp?error=true</beans:value>  
	</beans:property>
	</beans:bean>
	
</beans:beans>

 

 

9、为影片页面films.jsp定制操作权限,定制后,不同的帐号登录会看到不同的操作,

比如,帐号"admin"属于权限组"Administrator",具备权限"ROLE_ADMIN",登录后

可以看到所有操作,帐号"test"属于权限组"影片维护",具备权限"ROLE_UPDATE_FILM"

和"ROLE_ADD_FILM",登录后只能看到"添加影片信息"和"修改"操作

 

films.jsp页面权限分布图:

 

 

films.jsp代码如下:

 

 

Html代码 复制代码 收藏代码
  1. <%@ page language="java" contentType="text/html; charset=utf-8"  
  2. pageEncoding="utf-8" %>  
  3. <%@taglib uri="/struts-tags" prefix="s" %>  
  4. <%@ taglib prefix="security"  
  5.     uri="http://www.springframework.org/security/tags"%>  
  6. <%  
  7. String path = request.getContextPath();  
  8. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  9. %>  
  10. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  11. <html>  
  12.   <head>  
  13.     <title>信息操作</title>  
  14.   </head>  
  15.   <body>  
  16.     <s:form action="/film/findFilm" method="post">  
  17.         <s:submit value=" 获取所有影片信息 "></s:submit>  
  18.     </s:form>  
  19.     <!-- 添加影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_ADD_FILM权限可以执行 -->  
  20.     <security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_ADD_FILM">  
  21.     <href="<%=basePath %>manager/insertFilm.jsp">添加影片信息</a><br />   
  22.     </security:authorize>  
  23.       
  24.     <s:if test="filmList != null">  
  25.         <table border="1" width="40%">  
  26.     <tr>  
  27.         <th>序号</th><th>影片名</th><th>操作</th>  
  28.     </tr>   
  29.         <%-- 遍历影片信息 --%>  
  30.         <s:iterator var="film" value="filmList" status="st">  
  31.             <tr>  
  32.                 <td><s:property value="#st.index+1" /></td>  
  33.                 <td><s:property value="fname" /></td>  
  34.                 <td>  
  35.                       
  36.                     <!-- 修改影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_UPDATE_FILM权限可以执行 -->  
  37.                     <security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_UPDATE_FILM">  
  38.                         <s:url id="detailUrl" value="/film/detailFilm">  
  39.                                     <s:param name="id" value="%{id}"/>  
  40.                                     </s:url>  
  41.                         <s:a href="%{detailUrl}">[修改]</s:a>&nbsp;  
  42.                     </security:authorize>  
  43.                     <!-- 删除影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_DELETE_FILM权限可以执行 -->  
  44.                     <security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_DELETE_FILM">  
  45.                         <s:url id="deleteUrl" value="/film/deleteFilm">  
  46.                                     <s:param name="id" value="%{id}"/>  
  47.                                     </s:url>  
  48.                         <s:a href="%{deleteUrl}">[删除]</s:a>  
  49.                     </security:authorize>  
  50.             </td>  
  51.             </tr>  
  52.         </s:iterator>  
  53.     </table>  
  54.     </s:if>  
  55.   </body>  
  56. </html>  
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%@taglib uri="/struts-tags" prefix="s" %>
<%@ taglib prefix="security"
	uri="http://www.springframework.org/security/tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>信息操作</title>
  </head>
  <body>
    <s:form action="/film/findFilm" method="post">
    	<s:submit value=" 获取所有影片信息 "></s:submit>
    </s:form>
    <!-- 添加影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_ADD_FILM权限可以执行 -->
    <security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_ADD_FILM">
	<a href="<%=basePath %>manager/insertFilm.jsp">添加影片信息</a><br />	
    </security:authorize>
    
    <s:if test="filmList != null">
    	<table border="1" width="40%">
	<tr>
		<th>序号</th><th>影片名</th><th>操作</th>
	</tr>	
    	<%-- 遍历影片信息 --%>
    	<s:iterator var="film" value="filmList" status="st">
	    	<tr>
	    		<td><s:property value="#st.index+1" /></td>
	    		<td><s:property value="fname" /></td>
	    		<td>
	    			
	    			<!-- 修改影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_UPDATE_FILM权限可以执行 -->
	    			<security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_UPDATE_FILM">
		    			<s:url id="detailUrl" value="/film/detailFilm">
		                      		<s:param name="id" value="%{id}"/>
		                      		</s:url>
		    			<s:a href="%{detailUrl}">[修改]</s:a>&nbsp;
	    			</security:authorize>
			    	<!-- 删除影片操作,登录帐号具备ROLE_ADMIN权限或者ROLE_DELETE_FILM权限可以执行 -->
			    	<security:authorize ifAnyGranted="ROLE_ADMIN,ROLE_DELETE_FILM">
				    	<s:url id="deleteUrl" value="/film/deleteFilm">
		                      		<s:param name="id" value="%{id}"/>
		                      		</s:url>
				    	<s:a href="%{deleteUrl}">[删除]</s:a>
			    	</security:authorize>
			</td>
	    	</tr>
		</s:iterator>
	</table>
    </s:if>
  </body>
</html>

 

posted @ 2015-09-17 11:08  哥的头像很别致~  阅读(446)  评论(0编辑  收藏  举报