Spring Security3的搭建使用

最近接触项目,发现项目用到了很多新鲜东西,也不能说是新鲜,只能说自己没有接触过,于是闲的无聊一项一项学习学习,别人问到也说上个七七八八。

今天可算是把spring-security搭建了出来并且运行了起来,主要是自己太菜,其实最后看来也就那么回事。

1.数据库的设计和搭建
用户 、角色、权限、资源以及关联表 用户--角色、角色--权限、权限--资源 总共七张表。

用户表

create table SYS_USERS
(
  USER_ID       VARCHAR2(32) not null,
  USER_ACCOUNT  VARCHAR2(30),
  USER_NAME     VARCHAR2(40),
  USER_PASSWORD VARCHAR2(100),
  USER_DESC     VARCHAR2(100),
  ENABLED       NUMBER(1),
  ISSYS         NUMBER(1),
  USER_DEPT     VARCHAR2(20),
  USER_DUTY     VARCHAR2(10),
  SUB_SYSTEM    VARCHAR2(30)
 );
alter table SYS_USERS add constraint PK_PUB_USERS primary key (USER_ID);

角色表

create table SYS_ROLES
(
  ROLE_ID   VARCHAR2(32) not null,
  ROLE_NAME VARCHAR2(40),
  ROLE_DESC VARCHAR2(100),
  ENABLED   NUMBER(1),
  ISSYS     NUMBER(1),
  MODULE    VARCHAR2(4)
);
alter table SYS_ROLES add constraint PK_PUB_ROLES primary key (ROLE_ID);

权限表

create table SYS_AUTHORITIES
(
  AUTHORITY_ID   VARCHAR2(32) not null,
  AUTHORITY_NAME VARCHAR2(40),
  AUTHORITY_DESC VARCHAR2(100),
  ENABLED        NUMBER(1),
  ISSYS          NUMBER(1),
  MODULE         VARCHAR2(4)
);
alter table SYS_AUTHORITIES add constraint PK_PUB_AUTHORITIES primary key (AUTHORITY_ID);
资源表

create table SYS_RESOURCES
(
  RESOURCE_ID     VARCHAR2(32) not null,
  RESOURCE_NAME   VARCHAR2(100),
  RESOURCE_DESC   VARCHAR2(100),
  RESOURCE_TYPE   VARCHAR2(40),
  RESOURCE_STRING VARCHAR2(200),
  PRIORITY        NUMBER(1),
  ENABLED         NUMBER(1),
  ISSYS           NUMBER(1),
  MODULE          VARCHAR2(4)
);
alter table SYS_RESOURCES add constraint PK_PUB_RESOURCES primary key (RESOURCE_ID);

用户角色表

create table SYS_USERS_ROLES
(
  ID      NUMBER(13) not null,
  USER_ID VARCHAR2(32),
  ROLE_ID VARCHAR2(32),
  ENABLED NUMBER(1)
);
-- Create/Recreate primary, unique and foreign key constraints 
alter table SYS_USERS_ROLES  add constraint PK_PUB_USERS_ROLES primary key (ID);

alter table SYS_USERS_ROLES  add constraint FK_USERS_ROLES_ROLES foreign key (ROLE_ID)  references SYS_ROLES (ROLE_ID);
alter table SYS_USERS_ROLES  add constraint FK_USERS_ROLES_USERS foreign key (USER_ID)  references SYS_USERS (USER_ID);

角色权限表

create table SYS_ROLES_AUTHORITIES
(
  ID           NUMBER(13) not null,
  ROLE_ID      VARCHAR2(32),
  AUTHORITY_ID VARCHAR2(32),
  ENABLED      NUMBER(1)
);
-- Create/Recreate primary, unique and foreign key constraints 
alter table SYS_ROLES_AUTHORITIES  add constraint PK_PUB_ROLES_AUTHORITY primary key (ID);
alter table SYS_ROLES_AUTHORITIES  add constraint FK_PUB_ROLES_AUTHORITIES_AU foreign key (AUTHORITY_ID)  references SYS_AUTHORITIES (AUTHORITY_ID);
alter table SYS_ROLES_AUTHORITIES  add constraint FK_PUB_ROLES_AUTHORITIES_ROLES foreign key (ROLE_ID)  references SYS_ROLES (ROLE_ID);

权限资源表

create table SYS_AUTHORITIES_RESOURCES
(
  ID           NUMBER(13) not null,
  AUTHORITY_ID VARCHAR2(32),
  RESOURCE_ID  VARCHAR2(32),
  ENABLED      NUMBER(1)
);
-- Create/Recreate primary, unique and foreign key constraints 
alter table SYS_AUTHORITIES_RESOURCES  add constraint PK_PUB_AUTHORITIES_RE primary key (ID);
  
alter table SYS_AUTHORITIES_RESOURCES  add constraint FK_PUB_AUTHORITIES_RE_AU foreign key (AUTHORITY_ID)  references SYS_AUTHORITIES (AUTHORITY_ID);
alter table SYS_AUTHORITIES_RESOURCES  add constraint FK_PUB_AUTHORITIES_RE_RE foreign key (RESOURCE_ID)  references SYS_RESOURCES (RESOURCE_ID);

加入关联的数据就可以了

2.web数据库整合

2.1jar包的导入    我所用到的几个jar包

antlr-2.7.6.jar
aopalliance.jar
aspectjrt.jar
aspectjweaver.jar
backport-util-concurrent-3.1.jar
c3p0-0.9.1.2.jar
cglib-2.2.jar
cglib-nodep-2.1_3.jar
classes12.jar
common-annotations.jar
commons-collections-3.1.jar
commons-dbcp-1.3.jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-logging-1.0.4.jar
commons-pool.jar
dom4j-1.6.1.jar
ehcache-1.5.0.jar
freemarker-2.3.15.jar
hibernate-commons-annotations-3.2.0.Final.jar
hibernate-core-3.6.0.Final.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate3.jar
javassist-3.9.0.GA.jar
jta-1.1.jar
mysql-connector-java-5.0.0-beta-bin.jar
ognl-2.7.3.jar
slf4j-api-1.6.1.jar
slf4j-nop-1.6.1.jar
spring-aop-3.0.4.RELEASE.jar
spring-asm-3.0.4.RELEASE.jar
spring-beans-3.0.4.RELEASE.jar
spring-context-3.0.4.RELEASE.jar
spring-context-support-3.0.4.RELEASE.jar
spring-core-3.0.4.RELEASE.jar
spring-expression-3.0.4.RELEASE.jar
spring-jdbc-3.0.4.RELEASE.jar
spring-orm-3.0.4.RELEASE.jar
spring-security-acl-3.0.3.RELEASE.jar
spring-security-config-3.0.3.RELEASE.jar
spring-security-core-3.0.3.RELEASE.jar
spring-security-taglibs-3.0.3.RELEASE.jar
spring-security-web-3.0.3.RELEASE.jar
spring-test-3.0.4.RELEASE.jar
spring-tx-3.0.4.RELEASE.jar
spring-web-3.0.4.RELEASE.jar
spring-webmvc-3.0.4.RELEASE.jar
spring-webmvc-struts.jar
struts2-core-2.1.8.1.jar
struts2-spring-plugin-2.1.8.1.jar
xwork-core-2.1.6.jar

2.2创建实体类entity和映射文件xxx.hbm.xml(使用hibernate注解可以省略,下一阶段研究)

SysAuthorities.java

package org.joshua.ss.entity;

import java.io.Serializable;
import java.util.Set;

/**
 * 
 * @author Joshua
 *
 */
public class SysAuthorities implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6148281916911401715L;
	private String authorityId;
	private String authorityName;
	private String authorityDesc;
	private Boolean enabled;
	private Boolean issys;
	private String module;
	private Set<SysRolesAuthorities> sysRolesAuthoritieses;
	private Set<SysAuthoritiesResources> sysAuthoritiesResourceses;

	public SysAuthorities() {
	}

	public SysAuthorities(String authorityId) {
		this.authorityId = authorityId;
	}

	public SysAuthorities(String authorityId, String authorityName,
			String authorityDesc, Boolean enabled, Boolean issys, String module,
			Set<SysRolesAuthorities> sysRolesAuthoritieses, Set<SysAuthoritiesResources> sysAuthoritiesResourceses) {
		this.authorityId = authorityId;
		this.authorityName = authorityName;
		this.authorityDesc = authorityDesc;
		this.enabled = enabled;
		this.issys = issys;
		this.module = module;
		this.sysRolesAuthoritieses = sysRolesAuthoritieses;
		this.sysAuthoritiesResourceses = sysAuthoritiesResourceses;
	}

	public String getAuthorityId() {
		return this.authorityId;
	}

	public void setAuthorityId(String authorityId) {
		this.authorityId = authorityId;
	}

	public String getAuthorityName() {
		return this.authorityName;
	}

	public void setAuthorityName(String authorityName) {
		this.authorityName = authorityName;
	}

	public String getAuthorityDesc() {
		return this.authorityDesc;
	}

	public void setAuthorityDesc(String authorityDesc) {
		this.authorityDesc = authorityDesc;
	}

	public Boolean getEnabled() {
		return this.enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

	public Boolean getIssys() {
		return this.issys;
	}

	public void setIssys(Boolean issys) {
		this.issys = issys;
	}
	
	public String getModule() {
		return this.module;
	}

	public void setModule(String module) {
		this.module = module;
	}

	public Set<SysRolesAuthorities> getSysRolesAuthoritieses() {
		return sysRolesAuthoritieses;
	}

	public void setSysRolesAuthoritieses(
			Set<SysRolesAuthorities> sysRolesAuthoritieses) {
		this.sysRolesAuthoritieses = sysRolesAuthoritieses;
	}

	public Set<SysAuthoritiesResources> getSysAuthoritiesResourceses() {
		return sysAuthoritiesResourceses;
	}

	public void setSysAuthoritiesResourceses(
			Set<SysAuthoritiesResources> sysAuthoritiesResourceses) {
		this.sysAuthoritiesResourceses = sysAuthoritiesResourceses;
	}



}


SysAuthoritiesResources.java

package  org.joshua.ss.entity;

import java.io.Serializable;

/**
 * 
 * @author Joshua
 *
 */
public class SysAuthoritiesResources implements Serializable {


	/**
	 * 
	 */
	private static final long serialVersionUID = -2373269722400659636L;
	private long id;
	private SysAuthorities sysAuthorities;
	private SysResources sysResources;
	private Boolean enabled;

	public SysAuthoritiesResources() {
	}

	public SysAuthoritiesResources(long id) {
		this.id = id;
	}

	public SysAuthoritiesResources(long id, SysAuthorities sysAuthorities,
			SysResources sysResources, Boolean enabled) {
		this.id = id;
		this.sysAuthorities = sysAuthorities;
		this.sysResources = sysResources;
		this.enabled = enabled;
	}

	public long getId() {
		return this.id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public SysAuthorities getSysAuthorities() {
		return this.sysAuthorities;
	}

	public void setSysAuthorities(SysAuthorities sysAuthorities) {
		this.sysAuthorities = sysAuthorities;
	}

	public SysResources getSysResources() {
		return this.sysResources;
	}

	public void setSysResources(SysResources sysResources) {
		this.sysResources = sysResources;
	}

	public Boolean getEnabled() {
		return this.enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

}


SysResources.java

package org.joshua.ss.entity;

import java.io.Serializable;
import java.util.Set;

/**
 * 
 * @author Joshua
 *
 */
public class SysResources implements Serializable {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 6417157583753174159L;
	private String resourceId;
	private String resourceName;
	private String resourceDesc;
	private String resourceType;
	private String resourceString;
	private Boolean priority;
	
	//是否可用,0为不可用,1为可用。
	private Integer enabled;
	
	//是否是超级。0为不超级,1为超级。
	private Integer issys;
	
	private String module;
	private Set<SysAuthoritiesResources> sysAuthoritiesResourceses ;

	public SysResources() {
	}

	public SysResources(String resourceId) {
		this.resourceId = resourceId;
	}

	public SysResources(String resourceId, String resourceName,
			String resourceDesc, String resourceType, String resourceString,
			Boolean priority, Integer enabled, Integer issys, String module,
			Set<SysAuthoritiesResources> sysAuthoritiesResourceses) {
		this.resourceId = resourceId;
		this.resourceName = resourceName;
		this.resourceDesc = resourceDesc;
		this.resourceType = resourceType;
		this.resourceString = resourceString;
		this.priority = priority;
		this.enabled = enabled;
		this.issys = issys;
		this.module = module;
		this.sysAuthoritiesResourceses = sysAuthoritiesResourceses;
	}

	public String getResourceId() {
		return this.resourceId;
	}

	public void setResourceId(String resourceId) {
		this.resourceId = resourceId;
	}

	public String getResourceName() {
		return this.resourceName;
	}

	public void setResourceName(String resourceName) {
		this.resourceName = resourceName;
	}

	public String getResourceDesc() {
		return this.resourceDesc;
	}

	public void setResourceDesc(String resourceDesc) {
		this.resourceDesc = resourceDesc;
	}

	public String getResourceType() {
		return this.resourceType;
	}

	public void setResourceType(String resourceType) {
		this.resourceType = resourceType;
	}

	public String getResourceString() {
		return this.resourceString;
	}

	public void setResourceString(String resourceString) {
		this.resourceString = resourceString;
	}

	public Boolean getPriority() {
		return this.priority;
	}

	public void setPriority(Boolean priority) {
		this.priority = priority;
	}

	public Integer getEnabled() {
		return this.enabled;
	}

	public void setEnabled(Integer enabled) {
		this.enabled = enabled;
	}

	public Integer getIssys() {
		return this.issys;
	}

	public void setIssys(Integer issys) {
		this.issys = issys;
	}
	
	public String getModule() {
		return this.module;
	}

	public void setModule(String module) {
		this.module = module;
	}

	public Set<SysAuthoritiesResources> getSysAuthoritiesResourceses() {
		return sysAuthoritiesResourceses;
	}

	public void setSysAuthoritiesResourceses(
			Set<SysAuthoritiesResources> sysAuthoritiesResourceses) {
		this.sysAuthoritiesResourceses = sysAuthoritiesResourceses;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((enabled == null) ? 0 : enabled.hashCode());
		result = prime * result + ((issys == null) ? 0 : issys.hashCode());
		result = prime * result + ((module == null) ? 0 : module.hashCode());
		result = prime * result
				+ ((priority == null) ? 0 : priority.hashCode());
		result = prime * result
				+ ((resourceDesc == null) ? 0 : resourceDesc.hashCode());
		result = prime * result
				+ ((resourceId == null) ? 0 : resourceId.hashCode());
		result = prime * result
				+ ((resourceName == null) ? 0 : resourceName.hashCode());
		result = prime * result
				+ ((resourceString == null) ? 0 : resourceString.hashCode());
		result = prime * result
				+ ((resourceType == null) ? 0 : resourceType.hashCode());
		result = prime
				* result
				+ ((sysAuthoritiesResourceses == null) ? 0
						: sysAuthoritiesResourceses.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		SysResources other = (SysResources) obj;
		if (enabled == null) {
			if (other.enabled != null)
				return false;
		} else if (!enabled.equals(other.enabled))
			return false;
		if (issys == null) {
			if (other.issys != null)
				return false;
		} else if (!issys.equals(other.issys))
			return false;
		if (module == null) {
			if (other.module != null)
				return false;
		} else if (!module.equals(other.module))
			return false;
		if (priority == null) {
			if (other.priority != null)
				return false;
		} else if (!priority.equals(other.priority))
			return false;
		if (resourceDesc == null) {
			if (other.resourceDesc != null)
				return false;
		} else if (!resourceDesc.equals(other.resourceDesc))
			return false;
		if (resourceId == null) {
			if (other.resourceId != null)
				return false;
		} else if (!resourceId.equals(other.resourceId))
			return false;
		if (resourceName == null) {
			if (other.resourceName != null)
				return false;
		} else if (!resourceName.equals(other.resourceName))
			return false;
		if (resourceString == null) {
			if (other.resourceString != null)
				return false;
		} else if (!resourceString.equals(other.resourceString))
			return false;
		if (resourceType == null) {
			if (other.resourceType != null)
				return false;
		} else if (!resourceType.equals(other.resourceType))
			return false;
		if (sysAuthoritiesResourceses == null) {
			if (other.sysAuthoritiesResourceses != null)
				return false;
		} else if (!sysAuthoritiesResourceses
				.equals(other.sysAuthoritiesResourceses))
			return false;
		return true;
	}

}


SysRoles.java

package org.joshua.ss.entity;

import java.io.Serializable;
import java.util.Set;

import org.joshua.ss.dao.daoimpl.BaseDaoImpl;


public class SysRoles implements Serializable {


	/**
	 * 
	 */
	private static final long serialVersionUID = -243340671938105177L;
	private String roleId;
	private String roleName;
	private String roleDesc;
	private Boolean enabled;
	private Boolean issys;
	
	//平台中的子系统
	private String module;
	
	private Set<SysUsersRoles> sysUsersRoles;
	private Set<SysRolesAuthorities> sysRolesAuthorities;

	public SysRoles() {
	}

	public SysRoles(String roleId) {
		this.roleId = roleId;
	}
	
	public SysRoles(String roleId, String roleName, String roleDesc) {
		this.roleId = roleId;
		this.roleName = roleName;
		this.roleDesc = roleDesc;
	}
	
	public SysRoles(String roleId, String roleName, String roleDesc,
			Boolean enabled, Boolean issys, String module) {
		this.roleId = roleId;
		this.roleName = roleName;
		this.roleDesc = roleDesc;
		this.enabled = enabled;
		this.issys = issys;
		this.module = module;
	}

	public SysRoles(String roleId, String roleName, String roleDesc,
			Boolean enabled, Boolean issys, String module, Set<SysUsersRoles> sysUsersRoles,
			Set<SysRolesAuthorities> sysRolesAuthorities) {
		this.roleId = roleId;
		this.roleName = roleName;
		this.roleDesc = roleDesc;
		this.enabled = enabled;
		this.issys = issys;
		this.module = module;
		this.sysUsersRoles = sysUsersRoles;
		this.sysRolesAuthorities = sysRolesAuthorities;
	}

	public String getRoleId() {
		return this.roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}

	public String getRoleName() {
		return this.roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public String getRoleDesc() {
		return this.roleDesc;
	}

	public void setRoleDesc(String roleDesc) {
		this.roleDesc = roleDesc;
	}

	public Boolean getEnabled() {
		return this.enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

	public Boolean getIssys() {
		return this.issys;
	}

	public void setIssys(Boolean issys) {
		this.issys = issys;
	}
	
	
	public String getModule() {
		return this.module;
	}

	public void setModule(String module) {
		this.module = module;
	}

	public Set<SysUsersRoles> getSysUsersRoles() {
		return this.sysUsersRoles;
	}

	public void setSysUsersRoles(Set<SysUsersRoles> sysUsersRoles) {
		this.sysUsersRoles = sysUsersRoles;
	}

	public Set<SysRolesAuthorities> getSysRolesAuthorities() {
		return this.sysRolesAuthorities;
	}

	public void setSysRolesAuthorities(Set<SysRolesAuthorities> sysRolesAuthorities) {
		this.sysRolesAuthorities = sysRolesAuthorities;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((enabled == null) ? 0 : enabled.hashCode());
		result = prime * result + ((issys == null) ? 0 : issys.hashCode());
		result = prime * result + ((module == null) ? 0 : module.hashCode());
		result = prime * result
				+ ((roleDesc == null) ? 0 : roleDesc.hashCode());
		result = prime * result + ((roleId == null) ? 0 : roleId.hashCode());
		result = prime * result
				+ ((roleName == null) ? 0 : roleName.hashCode());
		result = prime
				* result
				+ ((sysRolesAuthorities == null) ? 0 : sysRolesAuthorities
						.hashCode());
		result = prime * result
				+ ((sysUsersRoles == null) ? 0 : sysUsersRoles.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		SysRoles other = (SysRoles) obj;
		if (enabled == null) {
			if (other.enabled != null)
				return false;
		} else if (!enabled.equals(other.enabled))
			return false;
		if (issys == null) {
			if (other.issys != null)
				return false;
		} else if (!issys.equals(other.issys))
			return false;
		if (module == null) {
			if (other.module != null)
				return false;
		} else if (!module.equals(other.module))
			return false;
		if (roleDesc == null) {
			if (other.roleDesc != null)
				return false;
		} else if (!roleDesc.equals(other.roleDesc))
			return false;
		if (roleId == null) {
			if (other.roleId != null)
				return false;
		} else if (!roleId.equals(other.roleId))
			return false;
		if (roleName == null) {
			if (other.roleName != null)
				return false;
		} else if (!roleName.equals(other.roleName))
			return false;
		if (sysRolesAuthorities == null) {
			if (other.sysRolesAuthorities != null)
				return false;
		} else if (!sysRolesAuthorities.equals(other.sysRolesAuthorities))
			return false;
		if (sysUsersRoles == null) {
			if (other.sysUsersRoles != null)
				return false;
		} else if (!sysUsersRoles.equals(other.sysUsersRoles))
			return false;
		return true;
	}

}


SysRolesAuthorities.java


package org.joshua.ss.entity;

import java.io.Serializable;


public class SysRolesAuthorities implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4270137978962070889L;
	private long id;
	private SysAuthorities sysAuthorities;
	private SysRoles sysRoles;
	private Boolean enabled;

	public SysRolesAuthorities() {
	}

	public SysRolesAuthorities(long id) {
		this.id = id;
	}

	public SysRolesAuthorities(long id, SysAuthorities sysAuthorities,
			SysRoles sysRoles, Boolean enabled) {
		this.id = id;
		this.sysAuthorities = sysAuthorities;
		this.sysRoles = sysRoles;
		this.enabled = enabled;
	}

	public long getId() {
		return this.id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public SysAuthorities getSysAuthorities() {
		return this.sysAuthorities;
	}

	public void setSysAuthorities(SysAuthorities sysAuthorities) {
		this.sysAuthorities = sysAuthorities;
	}

	public SysRoles getSysRoles() {
		return this.sysRoles;
	}

	public void setSysRoles(SysRoles sysRoles) {
		this.sysRoles = sysRoles;
	}

	public Boolean getEnabled() {
		return this.enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}
	
}


SysUsers.java

package org.joshua.ss.entity;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.joshua.ss.MyUserDetails;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;



/**
 * 
 * @author Joshua
 *
 */
public class SysUsers implements MyUserDetails,Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8680337263599302062L;

	//用户id
	private String userId;
	
	//用户账号 与 用户id相同,具有唯一性。
	private String userAccount;
	
	//中文用户名。
	private String userName;
	
	//密码原文 + 用户名作为盐值 的字串经过Md5加密后形成的密文。
	private String userPassword;
	
	//用户备注
	private String userDesc;
	
	//是否能用。
	private Boolean enabled;
	
	//是否是超级用户。
	private Boolean issys;
	
	//用户所在的单位。
	private String userDept;
	
	//用户的职位:比如主任、经理等。
	private String userDuty;
	
	//该用户所负责的子系统
	private String subSystem;
	
	//一个用户具有多个角色。
	private Set<SysUsersRoles> sysUsersRoleses =new HashSet(0);
	
	
	
	
	
	
	
	
	//实现了UserDetails之后的相关变量
    private  String password;
    private  String username;
    private  Set<GrantedAuthority> authorities;
    private  boolean accountNonExpired;
    private  boolean accountNonLocked;
    private  boolean credentialsNonExpired;	
    
    public SysUsers(){
    	
    }
		
	public SysUsers(String userId, String userAccount, String userName,
			String userPassword, String userDesc, Boolean enabled,
			Boolean issys, String userDept, String userDuty, String subSystem,
			Set<SysUsersRoles> sysUsersRoleses,boolean accountNonExpired, boolean accountNonLocked,
			boolean credentialsNonExpired,Collection<GrantedAuthority> authorities) {
		
		if (((userAccount == null) || "".equals(userAccount)) || (userPassword == null)) {
            throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
        }
		
		this.userId = userId;
		this.userAccount = userAccount;
		this.userName = userName;
		this.userPassword = userPassword;
		this.userDesc = userDesc;
		this.enabled = enabled;
		this.issys = issys;
		this.userDept = userDept;
		this.userDuty = userDuty;
		this.subSystem = subSystem;
		this.sysUsersRoleses = sysUsersRoleses;
		this.password = userPassword;
		this.username = userAccount;
		this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));
		this.accountNonExpired = accountNonExpired;
		this.accountNonLocked = accountNonLocked;
		this.credentialsNonExpired = credentialsNonExpired;
	}


    //~ Methods ========================================================================================================

    public boolean equals(Object rhs) {
        if (!(rhs instanceof SysUsers) || (rhs == null)) {
            return false;
        }

        SysUsers user = (SysUsers) rhs;

        //具有的权限。
        if (!authorities.equals(user.authorities)) {
            return false;
        }

        // 通过Spring Security构建一个用户时,用户名和密码不能为空。
        return (this.getPassword().equals(user.getPassword()) && this.getUsername().equals(user.getUsername())
                && (this.isAccountNonExpired() == user.isAccountNonExpired())
                && (this.isAccountNonLocked() == user.isAccountNonLocked())
                && (this.isCredentialsNonExpired() == user.isCredentialsNonExpired())
                && (this.isEnabled() == user.isEnabled()));
    }

	public String getUserId() {
		return this.userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getUserAccount() {
		return this.userAccount;
	}

	public void setUserAccount(String userAccount) {
		this.userAccount = userAccount;
	}

	public String getUserName() {
		return this.userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserPassword() {
		return this.userPassword;
	}

	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}

	public String getUserDesc() {
		return this.userDesc;
	}

	public void setUserDesc(String userDesc) {
		this.userDesc = userDesc;
	}

	public boolean getEnabled() {
		return this.enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

	public Boolean getIssys() {
		return this.issys;
	}

	public void setIssys(Boolean issys) {
		this.issys = issys;
	}
	
	public String getUserDept() {
		return this.userDept;
	}

	public void setUserDept(String userDept) {
		this.userDept = userDept;
	}
	
	public String getUserDuty() {
		return this.userDuty;
	}

	public void setUserDuty(String userDuty) {
		this.userDuty = userDuty;
	}	

	public String getSubSystem() {
		return this.subSystem;
	}

	public void setSubSystem(String subSystem) {
		this.subSystem = subSystem;
	}
	
	public Set<SysUsersRoles> getSysUsersRoleses() {
		return this.sysUsersRoleses;
	}

	public void setSysUsersRoleses(Set<SysUsersRoles> sysUsersRoleses) {
		this.sysUsersRoleses = sysUsersRoleses;
	}


	public String getPassword() {
		return password;
	}


	public String getUsername() {
		return username;
	}


	public Set<GrantedAuthority> getAuthorities() {
		return authorities;
	}


	public void setAuthorities(Set<GrantedAuthority> authorities) {
		this.authorities = authorities;
	}


	public boolean isAccountNonExpired() {
		return accountNonExpired;
	}

	public boolean isAccountNonLocked() {
		return accountNonLocked;
	}


	public boolean isCredentialsNonExpired() {
		return credentialsNonExpired;
	}

	public boolean isEnabled() {
		return enabled;
	}
	

    public int hashCode() {
        int code = 9792;

      //若该用户不是登录人员,则可以允许没有authorities。
		if (null != getUsername() && null != getAuthorities()) {
			for (GrantedAuthority authority : getAuthorities()) {

				code = code * (authority.hashCode() % 7);
			}
		}

        if (this.getPassword() != null) {
            code = code * (this.getPassword().hashCode() % 7);
        }

        if (this.getUsername() != null) {
            code = code * (this.getUsername().hashCode() % 7);
        }

        if (this.isAccountNonExpired()) {
            code = code * -2;
        }

        if (this.isAccountNonLocked()) {
            code = code * -3;
        }

        if (this.isCredentialsNonExpired()) {
            code = code * -5;
        }

        if (this.isEnabled()) {
            code = code * -7;
        }

        return code;
    }

	
    private static SortedSet<GrantedAuthority> sortAuthorities(Collection<GrantedAuthority> authorities) {
        Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");
        // Ensure array iteration order is predictable (as per UserDetails.getAuthorities() contract and SEC-717)
        SortedSet<GrantedAuthority> sortedAuthorities =
            new TreeSet<GrantedAuthority>(new AuthorityComparator());

        for (GrantedAuthority grantedAuthority : authorities) {
            Assert.notNull(grantedAuthority, "GrantedAuthority list cannot contain any null elements");
            sortedAuthorities.add(grantedAuthority);
        }

        return sortedAuthorities;
    }
   
    private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable {
        public int compare(GrantedAuthority g1, GrantedAuthority g2) {
            // Neither should ever be null as each entry is checked before adding it to the set.
            // If the authority is null, it is a custom authority and should precede others.
            if (g2.getAuthority() == null) {
                return -1;
            }

            if (g1.getAuthority() == null) {
                return 1;
            }
            return g1.getAuthority().compareTo(g2.getAuthority());
        }
    }
	
	
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(super.toString()).append(": ");
        sb.append("Username: ").append(this.username).append("; ");
        sb.append("" +
        		"" +
        		": [PROTECTED]; ");
        sb.append("UserAccount: ").append(this.userAccount).append("; ");
        sb.append("UserDept: ").append(this.userDept).append("; ");
        sb.append("UserDuty: ").append(this.userDuty).append("; ");
        sb.append("UserDesc: ").append(this.userDesc).append("; ");
        sb.append("UserSubSystem: ").append(this.subSystem).append("; ");
        sb.append("UserIsSys: ").append(this.issys).append("; ");
        sb.append("Enabled: ").append(this.enabled).append("; ");
        sb.append("AccountNonExpired: ").append(this.accountNonExpired).append("; ");
        sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired).append("; ");
        sb.append("AccountNonLocked: ").append(this.accountNonLocked).append("; ");

        if ( null !=authorities  && !authorities.isEmpty()) {
            sb.append("Granted Authorities: ");

            boolean first = true;
            for (GrantedAuthority auth : authorities) {
                if (!first) {
                    sb.append(",");
                }
                first = false;

                sb.append(auth);
            }
        } else {
            sb.append("Not granted any authorities");
        }

        return sb.toString();
    }

}


SysUsersRoles.java


package org.joshua.ss.entity;

import java.io.Serializable;

public class SysUsersRoles implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 393623940722220854L;
	private long id;
	private SysUsers pubUsers;
	private SysRoles pubRoles;
	private Boolean enabled;

	public SysUsersRoles() {
	}

	public SysUsersRoles(long id) {
		this.id = id;
	}

	public SysUsersRoles(long id, SysUsers pubUsers, SysRoles pubRoles,
			Boolean enabled) {
		this.id = id;
		this.pubUsers = pubUsers;
		this.pubRoles = pubRoles;
		this.enabled = enabled;
	}

	public long getId() {
		return this.id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public SysUsers getSysUsers() {
		return this.pubUsers;
	}

	public void setSysUsers(SysUsers pubUsers) {
		this.pubUsers = pubUsers;
	}

	public SysRoles getSysRoles() {
		return this.pubRoles;
	}

	public void setSysRoles(SysRoles pubRoles) {
		this.pubRoles = pubRoles;
	}

	public Boolean getEnabled() {
		return this.enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

}
2.2.2对应的映射文件xxx.hbm.xml

SysAuthorities.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2011-3-23 11:09:37 by Hibernate Tools 3.2.2.GA -->
<hibernate-mapping>
    <class name="org.joshua.ss.entity.SysAuthorities" table="SYS_AUTHORITIES">
        <id name="authorityId" type="string">
            <column name="AUTHORITY_ID" length="32" />
            <generator class="assigned" />
        </id>
        <property name="authorityName" type="string">
            <column name="AUTHORITY_NAME" length="40" />
        </property>
        <property name="authorityDesc" type="string">
            <column name="AUTHORITY_DESC" length="100" />
        </property>
        <property name="enabled" type="java.lang.Boolean">
            <column name="ENABLED" precision="1" scale="0" />
        </property>
        <property name="issys" type="java.lang.Boolean">
            <column name="ISSYS" precision="1" scale="0" />
        </property>
        <property name="module" type="string">
            <column name="MODULE" length="4" />
        </property>
        <set name="sysRolesAuthoritieses" inverse="true" cascade="all" lazy="false">
            <key>
                <column name="AUTHORITY_ID" length="32" />
            </key>
            <one-to-many class="org.joshua.ss.entity.SysRolesAuthorities" />
        </set>
        <set name="sysAuthoritiesResourceses" inverse="true" cascade="all" lazy="false">
            <key>
                <column name="AUTHORITY_ID" length="32" />
            </key>
            <one-to-many class="org.joshua.ss.entity.SysAuthoritiesResources" />
        </set>
    </class>
</hibernate-mapping>


SysAuthoritiesResources.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="org.joshua.ss.entity.SysAuthoritiesResources" table="SYS_AUTHORITIES_RESOURCES">
        <id name="id" type="long">
            <column name="ID" precision="13" scale="0" />
            <generator class="assigned" />
        </id>
        <many-to-one name="sysAuthorities" class="org.joshua.ss.entity.SysAuthorities" fetch="select" lazy="false">
            <column name="AUTHORITY_ID" length="32" />
        </many-to-one>
        <many-to-one name="sysResources" class="org.joshua.ss.entity.SysResources" fetch="select" lazy="false">
            <column name="RESOURCE_ID" length="32" />
        </many-to-one>
        <property name="enabled" type="java.lang.Boolean">
            <column name="ENABLED" precision="1" scale="0" />
        </property>
    </class>
</hibernate-mapping>


SysResources.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="org.joshua.ss.entity.SysResources" table="Sys_RESOURCES">
        <id name="resourceId" type="string">
            <column name="RESOURCE_ID" length="32" />
            <generator class="assigned" />
        </id>
        <property name="resourceName" type="string">
            <column name="RESOURCE_NAME" length="100" />
        </property>
        <property name="resourceDesc" type="string">
            <column name="RESOURCE_DESC" length="100" />
        </property>
        <property name="resourceType" type="string">
            <column name="RESOURCE_TYPE" length="40" />
        </property>
        <property name="resourceString" type="string">
            <column name="RESOURCE_STRING" length="200" />
        </property>
        <property name="priority" type="java.lang.Boolean">
            <column name="PRIORITY" precision="1" scale="0" />
        </property>
        <property name="enabled" type="java.lang.Integer">
            <column name="ENABLED" precision="1" scale="0" />
        </property>
        <property name="issys" type="java.lang.Integer">
            <column name="ISSYS" precision="1" scale="0" />
        </property>
        <property name="module" type="string">
            <column name="MODULE" length="4" />
        </property>
        <set name="sysAuthoritiesResourceses" inverse="true" lazy="false">
            <key>
                <column name="RESOURCE_ID" length="32" />
            </key>
            <one-to-many class="org.joshua.ss.entity.SysAuthoritiesResources" />
        </set>
    </class>
</hibernate-mapping>


SysRoles.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="org.joshua.ss.entity.SysRoles" table="SYS_ROLES">
        <id name="roleId" type="string">
            <column name="ROLE_ID" length="32" />
            <generator class="assigned" />
        </id>
        <property name="roleName" type="string">
            <column name="ROLE_NAME" length="40" />
        </property>
        <property name="roleDesc" type="string">
            <column name="ROLE_DESC" length="100" />
        </property>
        <property name="enabled" type="java.lang.Boolean">
            <column name="ENABLED" precision="1" scale="0" />
        </property>
        <property name="issys" type="java.lang.Boolean">
            <column name="ISSYS" precision="1" scale="0" />
        </property>
        <property name="module" type="string">
            <column name="MODULE" length="4" />
        </property>
        <set name="sysUsersRoles" inverse="true" cascade="all" lazy="false">
            <key>
                <column name="ROLE_ID" length="32" />
            </key>
            <one-to-many class="org.joshua.ss.entity.SysUsersRoles"/>
        </set>
        <set name="sysRolesAuthorities" inverse="true" cascade="all" lazy="false">
            <key>
                <column name="ROLE_ID" length="32" />
            </key>
            <one-to-many class="org.joshua.ss.entity.SysRolesAuthorities" />
        </set>
    </class>
</hibernate-mapping>


SysRolesAuthorities.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2011-3-23 11:09:37 by Hibernate Tools 3.2.2.GA -->
<hibernate-mapping>
    <class name="org.joshua.ss.entity.SysRolesAuthorities" table="SYS_ROLES_AUTHORITIES">
        <id name="id" type="long">
            <column name="ID" precision="13" scale="0" />
            <generator class="assigned" />
        </id>
        <many-to-one name="sysAuthorities" class="org.joshua.ss.entity.SysAuthorities" fetch="select" lazy="false">
            <column name="AUTHORITY_ID" length="32" />
        </many-to-one>
        <many-to-one name="sysRoles" class="org.joshua.ss.entity.SysRoles" fetch="select" lazy="false">
            <column name="ROLE_ID" length="32" />
        </many-to-one>
        <!--  
        <property name="authorityId" type="string">
            <column name="AUTHORITY_ID" length="32" />
        </property>
        <property name="roleId" type="string">
            <column name="ROLE_ID" length="32" />
        </property> -->
        <property name="enabled" type="java.lang.Boolean">
            <column name="ENABLED" precision="1" scale="0" />
        </property>
    </class>
</hibernate-mapping>


SysUsers.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="org.joshua.ss.entity.SysUsers" table="SYS_USERS">
        <id name="userId" type="string">
            <column name="USER_ID" length="32" />
            <generator class="assigned" />
        </id>
        <property name="userAccount" type="string">
            <column name="USER_ACCOUNT" length="30" />
        </property>
        <property name="userName" type="string">
            <column name="USER_NAME" length="40" />
        </property>
        <property name="userPassword" type="string">
            <column name="USER_PASSWORD" length="100" />
        </property>
        <property name="userDesc" type="string">
            <column name="USER_DESC" length="100" />
        </property>
        <property name="userDuty" type="string">
            <column name="USER_DUTY" length="10" />
        </property>
        <property name="userDept" type="string">
            <column name="USER_DEPT" length="20" />
        </property>
        <property name="subSystem" type="string">
            <column name="SUB_SYSTEM" length="30" />
        </property>
        <property name="enabled" type="java.lang.Boolean">
            <column name="ENABLED" precision="1" scale="0" />
        </property>
        <property name="issys" type="java.lang.Boolean">
            <column name="ISSYS" precision="1" scale="0" />
        </property>
        <set name="sysUsersRoleses" inverse="true" cascade="all" lazy="false">
            <key>
                <column name="USER_ID" length="32" />
            </key>
            <one-to-many class="org.joshua.ss.entity.SysUsersRoles" />
        </set>
    </class>
</hibernate-mapping>


SysUsersRoles.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="org.joshua.ss.entity.SysUsersRoles" table="SYS_USERS_ROLES">
        <id name="id" type="long">
            <column name="ID" precision="13" scale="0" />
            <generator class="assigned" />
        </id>
        <many-to-one name="sysUsers" class="org.joshua.ss.entity.SysUsers" fetch="select" lazy="false">
            <column name="USER_ID" length="32" />
        </many-to-one>
        <many-to-one name="sysRoles" class="org.joshua.ss.entity.SysRoles" fetch="select" lazy="false">
            <column name="ROLE_ID" length="32" />
        </many-to-one>
        <property name="enabled" type="java.lang.Boolean">
            <column name="ENABLED" precision="1" scale="0" />
        </property>
    </class>
</hibernate-mapping>

2.3DAO层和service层的创建

最近看到通用dao,模仿着写了一个在这里

BaseDao.java

package org.joshua.ss.dao;

import java.io.Serializable;
import java.util.List;

/**
 * 
 * @author Joshua
 *
 * @param <T>
 * 				DAO操作的对象类型
 * @param <PK>
 * 				主键类型
 */
public interface BaseDao<T,PK extends Serializable> {
	
	
	/**
	 * 按id获取对象.
	 * 
	 */
	T getById(PK id);
	
	/**
	 * 保存新增或修改的对象.
	 * 
	 */
	T save(T object);
	
	/** 
	 * 按id删除对象.
	 */
	void remove(PK id);
	
	/**
	 * 删除对象.
	 */
	void remove(final T object);
	
	/**
	 * 查询全部对象
	 */
	List<T> getAll();
	
	
}


SysAuthoritiesDao.java接口下同

package org.joshua.ss.dao;
/**
 *@author Joshua
 *@version 2011-12-15 上午11:06:22
 */
public interface SysAuthoritiesDao{

}

SysAuthoritiesResourcesDao.java
SysResourcesDao.java
SysRolesAuthoritiesDao.java
SysRolesDao.java
SysUsersDao.java
SysUsersRolesDao.java

dao层接口的实现类

BaseDaoImpl.java

package org.joshua.ss.dao.daoimpl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.Resource;

import org.joshua.ss.dao.BaseDao;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.util.Assert;

/**
 *@author Joshua
 *@version 2011-12-15 下午02:27:43
 */
/**
 * 可以在service层直接调用,也可以在DAO层扩展调用
 */
public class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK>{
	
	@Resource(name="hibernateTemplate")
	private HibernateTemplate hibernateTemplate;
	
	private Class<T> persistentClass;
	/**
     * 用于Dao层子类使用的构造函数. 通过子类的泛型定义取得对象类型
     */

	@SuppressWarnings("unchecked")
	public BaseDaoImpl(){
		//getClass() 返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的超类的 Class。
		this.persistentClass=(Class<T>)getSuperClassGenricType(getClass(), 0);
	}
	public List<T> getAll() {		
		return hibernateTemplate.loadAll(this.persistentClass);
	}

	public T getById(PK id) {
		Assert.notNull(id, "id 不可空");
		T entity =hibernateTemplate.get(this.persistentClass, id);
		return entity;
	}

	public void remove(PK id) {
		Assert.notNull(id, "id 不可空!");
		hibernateTemplate.delete(this.getById(id));		
	}

	public void remove(final T entity) {
		Assert.notNull(entity, "entity 不可空!");
		hibernateTemplate.delete(entity);
	}

	public T save(T entity) {
		Assert.notNull(entity, "entity 不可空!");		
		return hibernateTemplate.merge(entity);
	}
	/**
     * 通过反射, 获得定义Class时声明的父类的泛型参数的类型. 如无法找到, 返回Object.class.
     * 
     *@param clazz
     *            clazz The class to introspect
     * @param index
     *            the Index of the generic ddeclaration,start from 0.
     * @return the index generic declaration, or Object.class if cannot be
     *         determined
     */
    @SuppressWarnings("unchecked")
    public static Class<Object> getSuperClassGenricType(final Class clazz, final int index) {
    	
    	//返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。
        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {
           return Object.class;
        }
        //返回表示此类型实际类型参数的 Type 对象的数组。
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
                     return Object.class;
        }
        if (!(params[index] instanceof Class)) {
              return Object.class;
        }

        return (Class) params[index];
    }

}


SysAuthoritiesDaoImpl.java

package org.joshua.ss.dao.daoimpl;

import org.joshua.ss.dao.SysAuthoritiesDao;
import org.joshua.ss.entity.SysAuthorities;

/**
 *@author Joshua
 *@version 2011-12-15 上午11:06:22
 */
public class SysAuthoritiesDaoImpl extends BaseDaoImpl<SysAuthorities, Long> implements SysAuthoritiesDao {

}

下同,继承通用dao传递实体类型,也可自定义方法
SysAuthoritiesResourcesDaoImpl.java
SysResourcesDaoImpl.java
SysRolesAuthoritiesDaoImpl.java
SysRolesDaoImpl.java
SysUsersDaoImpl.java

package org.joshua.ss.dao.daoimpl;



import java.util.List;

import javax.annotation.Resource;

import org.joshua.ss.dao.SysUsersDao;


import org.joshua.ss.entity.SysUsers;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;

/**
 *@author Joshua
 *@version 2011-12-15 上午11:08:02
 */
@Service("sysUsersDaoImpl")
public class SysUsersDaoImpl extends BaseDaoImpl<SysUsersDao, Long> implements
		SysUsersDao {
	@Resource(name="hibernateTemplate")
	private HibernateTemplate hibernateTemplate;


	public SysUsers findByUserAccount(String userName) {
		try {
			SysUsers instance;
			List<SysUsers> instances = hibernateTemplate.find(
					"from SysUsers where userAccount='" + userName+"'");
			if ( null ==instances||instances.isEmpty()) {
				System.out.println("没有相匹配的SysUsers实例对象!");
				instance = new SysUsers();
			} else {
				instance=instances.get(0);
				System.out.println("相匹配的SysUsers实例对象被找到!");
				}
			return instance;
		} catch (RuntimeException re) {
			System.out.println("findByUserAccount() 错误!");
			throw re;
		}
	}

}


SysUsersRolesDaoImpl.java


service层的实现

AuthoritiesResourcesManager.java

package org.joshua.ss.service;

import org.joshua.ss.dao.daoimpl.BaseDaoImpl;
import org.joshua.ss.entity.SysAuthoritiesResources;
import org.springframework.stereotype.Service;

/**
 *@author Joshua
 *@version 2011-12-20 下午02:19:19
 */
@Service("authoritiesResourcesManager")
public class AuthoritiesResourcesManager extends BaseDaoImpl<SysAuthoritiesResources,Long>{

}

下同,

这里说明一下我没有去操作对应的dao层而直接去操作通用dao,如果对应到里没有自定义的方法,或者没有用到dao自定义的方法,可以直接继承通dao,这样也可省去dao层

这也是springside封装通用dao将dao彻底省略掉,将增删改查分页等功能都封装到通用dao中.

AuthorityManager.java
ResourceManager.java
RoleManager.java
RolesAuthoritiesManager.java
UserManager.java

这里用到dao自定义的方法,所以注入dao

package org.joshua.ss.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.joshua.ss.dao.daoimpl.BaseDaoImpl;
import org.joshua.ss.dao.daoimpl.SysUsersDaoImpl;
import org.joshua.ss.entity.SysRolesAuthorities;
import org.joshua.ss.entity.SysUsers;
import org.joshua.ss.entity.SysUsersRoles;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.stereotype.Service;

/**
 *@author Joshua
 *@version 2011-12-15 下午03:58:38
 * @param <SysUsers>
 */
@Service("userManager")
public class UserManager extends BaseDaoImpl<SysUsers,Long>{
	@Resource(name="hibernateTemplate")
	public HibernateTemplate  hibernateTemplate;
	
	@Resource(name="sysUsersDaoImpl")
	public SysUsersDaoImpl userDao;
	
	public SysUsersDaoImpl getUserDao() {
		return userDao;
	}
	public void setUserDao(SysUsersDaoImpl userDao) {
		this.userDao = userDao;
		
	}
	public SysUsers queryUnique(String id){
		return hibernateTemplate.get(SysUsers.class, id);
	}
	public List<GrantedAuthority> loadUserAuthoritiesByName(String username) {

		try {

			List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
			List<String> authorityNameList = loadUserAuthorities(username);

			for (String authorityName : authorityNameList) {
				//??
				System.out.println(getClass().getName()+authorityName);
				GrantedAuthorityImpl authority = new GrantedAuthorityImpl(authorityName);
				auths.add(authority);
			}

			return auths;

		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List<String> loadUserAuthorities(final String username) {
		try {

			List<String> authNameList = new ArrayList<String>();
			//根据用户名获得user
			SysUsers user = userDao.findByUserAccount(username);
			//根据user获得roles
			Set<SysUsersRoles> usersRoles =	user.getSysUsersRoleses();
			for(SysUsersRoles usersrole:usersRoles){
				//更据roles获得authenority 获得auth_name
				Set<SysRolesAuthorities>  rolesAuthorities = usersrole.getSysRoles().getSysRolesAuthorities();
				for(SysRolesAuthorities roleAuthoritiy:rolesAuthorities){
					String authName = roleAuthoritiy.getSysAuthorities().getAuthorityName();
					authNameList.add(authName);
				}			
			}
			return authNameList;
		} catch (RuntimeException re) {
			System.out.println("find by authorities by username failed."
					+ re.getMessage());
			throw re;
		}

	}


	
	
}


2.4配置容器的xxx.xml文件

web.xml

<?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">
	<!-- 配置ioc容器路径 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext*.xml</param-value>
	</context-param>
    <!-- 通过监听器加载ioc容器 -->
	<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
	
	
	<!-- 通过过滤器加载struts2框架 -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>
			org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
		</filter-class>
	</filter>
	<!-- Spring Secutiry-->
	<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>
	
	
	<!-- 解决Hibernate的延迟加载造成的Session提前关闭问题,设置该项使Session保持Request请求
                 完成才关闭Session。      -->
 	<filter>
        <filter-name>opensession</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>  

	<filter-mapping>
        <filter-name>opensession</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
	
	<!--
		使用Spring中的过滤器解决在请求和应答中的中文乱码问题(不是为了初始化每个jsp页面)
	-->
	<filter>
		<filter-name>characterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>gbk</param-value>
		</init-param>
		<init-param>
			<!--强制转换编码(request和response均适用) -->
			<param-name>ForceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	
	

	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- 避免乱码问题 -->
	<filter>
        <filter-name>struts-cleanup</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.ActionContextCleanUp
        </filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>struts-cleanup</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
	<!-- 通过注解完成对bean的管理 -->
	<context:component-scan base-package="org.joshua.ss" />
</beans>


applicationContext_db.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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- 加载属性文件 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:dbConfig.properties</value>
		</property>
	</bean>

	<!-- 配置数据源 -->

	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.user}" />
		<property name="password" value="${jdbc.pwd}" />
	</bean>
	<!-- 创建session 工厂 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 加载映射文件 -->
		<property name="mappingResources">
			<list>
				<value>org/joshua/ss/res/SysAuthorities.hbm.xml</value>
				<value>org/joshua/ss/res/SysAuthoritiesResources.hbm.xml</value>
				<value>org/joshua/ss/res/SysResources.hbm.xml</value>
				<value>org/joshua/ss/res/SysRoles.hbm.xml</value>
				<value>org/joshua/ss/res/SysRolesAuthorities.hbm.xml</value>
				<value>org/joshua/ss/res/SysUsers.hbm.xml</value>
				<value>org/joshua/ss/res/SysUsersRoles.hbm.xml</value>
			</list>
		</property>
		<!--
				通过扫描包路径加载
		--><!--<property name="annotatedPackages">
			<list>
				<value>org.joshua.ss.webapp.entity</value>
			</list>
		</property>
		--><!-- 配置session factory 的属性 -->
		<property name="hibernateProperties">
			<value>
				hibernate.dialect=org.hibernate.dialect.OracleDialect
				hibernate.show_sql=true
				<!-- 启用二级缓存 -->
				hibernate.cache.use_second_level_cache=true
				hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
			</value>
		</property>
	</bean>

	<!-- 配置事务管理器 -->
	<bean id="txManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- 启用注解管理事务 -->
	<tx:annotation-driven transaction-manager="txManager" />
	<!-- 获取HibernateTemplate 对象 -->
	<bean id="hibernateTemplate"
		class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
</beans>


applicationContext_security.xml

<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:b="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.0.xsd">
	<http auto-config="true" access-denied-page="/accessDenied.jsp">
		<!-- 不要过滤图片等静态资源  filters="none"-->
		<intercept-url pattern="/**/*.jpg" filters="none" />
		<intercept-url pattern="/**/*.png" filters="none" />
		<intercept-url pattern="/**/*.gif" filters="none" />
		<intercept-url pattern="/**/*.css" filters="none" />
		<intercept-url pattern="/**/*.js" filters="none" />
		
		<!-- 登陆页和忘记密码或注册等不需要过滤的页面 -->
		<intercept-url pattern="/login.jsp" filters="none" />
		<intercept-url pattern="/jsp/forgotpassword.jsp"
			filters="none" />

		<form-login login-page="/login.jsp"
			authentication-failure-url="/login.jsp?error=true"
			default-target-url="/index.jsp" />
		
		<logout logout-success-url="/login.jsp" />

		<!-- "记住我"功能,采用持久化策略(将用户的登录信息存放在数据库表中)需要创建一张persistent_logins 表 
		<remember-me data-source-ref="dataSource" />

		--><!-- 检测失效的sessionId,超时时定位到另外一个URL -->
		<session-management invalid-session-url="/sessionTimeout.jsp" />

		<!--
			增加一个自定义的filter,放在FILTER_SECURITY_INTERCEPTOR之前,实现用户、角色、权限、资源的数据库管理。
		-->
		<custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR" />
	</http>

	<!--
		一个自定义的filter
		必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性。
	-->
	<b:bean id="myFilter" class="org.joshua.ss.MyFilterSecurityInterceptor">
		<b:property name="authenticationManager" ref="authenticationManager" />
		<b:property name="accessDecisionManager" ref="myAccessDecisionManager" />
		<b:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
	</b:bean>

	<!-- 注意能够为authentication-manager 设置alias别名  -->
	<authentication-manager alias="authenticationManager">
		<authentication-provider user-service-ref="myUserDetailService"><!--
			 <password-encoder hash="md5" />
		--></authentication-provider>
	</authentication-manager>

	<b:bean id="myUserDetailService" class="org.joshua.ss.MyUserDetailService" />

	<!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源。11/3/23 -->
	<b:bean id="myAccessDecisionManager"
		class="org.joshua.ss.MyAccessDecisionManager">
	</b:bean>  

	<!-- 资源源数据定义,将所有的资源和权限对应关系建立起来,即定义某一资源可以被哪些角色去访问。11/3/23 -->
	<b:bean id="mySecurityMetadataSource"
		class="org.joshua.ss.MyInvocationSecurityMetadataSource">
	</b:bean> 

</b:beans>


dbConfig.properties

jdbc.user=scott
jdbc.pwd=snail
jdbc.url=jdbc\:oracle\:thin\:@localhost\:1521\:oracle
jdbc.driver=oracle.jdbc.driver.OracleDriver


ehcache.xml 没有深入的研究,暂且搁置

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache>
	<diskStore path="user.dir"></diskStore>
	<defaultCache 
	maxElementsInMemory="10000"
	eternal="false"
	timeToIdleSeconds="120"
	timeToLiveSeconds="120"
	overflowToDisk="true" />
</ehcache>


struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<!--  常量  -->
	<constant name="struts.il8n.encoding" value="UTF-8"/>
	<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
	<constant name="struts.action.extension" value="do"/>
	<!-- 表示struts2中action 来自于spring的ioc容器 -->
	<constant name="struts.objectFactory" value="spring"/>
	<package name="user" namespace="" extends="struts-default">
		<action name="*" class="loginAction" method="{1}">
			<result name="success">/success.jsp</result>
			<result name="error">/error.jsp</result>
		</action>
	</package>
</struts>

spring security 中最重要的核心

MyAccessDecisionManager.java
MyFilterSecurityInterceptor.java
MyInvocationSecurityMetadataSource.java
MyUserDetails.java(自定义的SysUsers实现的接口,可以省掉,使用框架提供的User,

org.springframework.security.core.userdetails.User
)
MyUserDetailService.java



MyAccessDecisionManager.java

package org.joshua.ss;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
/**
 *AccessdecisionManager在Spring security中是很重要的。
 *
 *在验证部分简略提过了,所有的Authentication实现需要保存在一个GrantedAuthority对象数组中。 
 *这就是赋予给主体的权限。 GrantedAuthority对象通过AuthenticationManager
 *保存到 Authentication对象里,然后从AccessDecisionManager读出来,进行授权判断。 
 *
 *Spring Security提供了一些拦截器,来控制对安全对象的访问权限,例如方法调用或web请求。 
 *一个是否允许执行调用的预调用决定,是由AccessDecisionManager实现的。 
 *这个 AccessDecisionManager 被AbstractSecurityInterceptor调用,
 *它用来作最终访问控制的决定。 这个AccessDecisionManager接口包含三个方法: 
 *
 void decide(Authentication authentication, Object secureObject,
 List<ConfigAttributeDefinition> config) throws AccessDeniedException;
 boolean supports(ConfigAttribute attribute);
 boolean supports(Class clazz);
 
  从第一个方法可以看出来,AccessDecisionManager使用方法参数传递所有信息,这好像在认证评估时进行决定。 
  特别是,在真实的安全方法期望调用的时候,传递安全Object启用那些参数。 
  比如,让我们假设安全对象是一个MethodInvocation。 
  很容易为任何Customer参数查询MethodInvocation,
  然后在AccessDecisionManager里实现一些有序的安全逻辑,来确认主体是否允许在那个客户上操作。 
  如果访问被拒绝,实现将抛出一个AccessDeniedException异常。

  这个 supports(ConfigAttribute) 方法在启动的时候被
  AbstractSecurityInterceptor调用,来决定AccessDecisionManager
  是否可以执行传递ConfigAttribute。 
  supports(Class)方法被安全拦截器实现调用,
  包含安全拦截器将显示的AccessDecisionManager支持安全对象的类型。
 * @author Joshua
 *
 */

public class MyAccessDecisionManager implements AccessDecisionManager {
	// In this method, need to compare authentication with configAttributes.
	// 1, A object is a URL, a filter was find permission configuration by this
	// URL, and pass to here.
	// 2, Check authentication has attribute in permission configuration
	// (configAttributes)
	// 3, If not match corresponding authentication, throw a
	// AccessDeniedException.

	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		if (configAttributes == null) {
			return;
		}
		// object is a URL.
		Iterator<ConfigAttribute> ite = configAttributes.iterator();
	
		while (ite.hasNext()) {
			ConfigAttribute ca = ite.next();
			String needRole = ((SecurityConfig) ca).getAttribute();
			
			//ga 为用户所被赋予的权限。 needRole 为访问相应的资源应该具有的权限。
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				if (needRole.trim().equals(ga.getAuthority().trim())) { 
					return;
				}
			}
		}
		//
		throw new AccessDeniedException("no right!");
	}

	public boolean supports(ConfigAttribute arg0) {
	
		return true;
	}

	public boolean supports(Class<?> clazz) {
	
		return true;
	}

}


MyFilterSecurityInterceptor.java

package org.joshua.ss;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

/**
 * 该过滤器的主要作用就是通过spring的IoC生成securityMetadataSource。
 * securityMetadataSource相当于本包中自定义的MyInvocationSecurityMetadataSource。
 * 该MyInvocationSecurityMetadataSource的作用提从数据库提取权限和资源,装配到HashMap中, 供Spring
 * Security使用,用于权限校验。
 * 
 * @author Joshua
 * 
 */
public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor
		implements Filter {
	private FilterInvocationSecurityMetadataSource securityMetadataSource;

	@Override
	public Class<? extends Object> getSecureObjectClass() {
		return FilterInvocation.class;
	}

	public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
		return securityMetadataSource;
	}

	public void setSecurityMetadataSource(
			FilterInvocationSecurityMetadataSource securityMetadataSource) {
		this.securityMetadataSource = securityMetadataSource;
	}

	@Override
	public SecurityMetadataSource obtainSecurityMetadataSource() {
		return this.securityMetadataSource;
	}

	public void invoke(FilterInvocation fi) throws IOException,
			ServletException {

		InterceptorStatusToken token = super.beforeInvocation(fi);

		try {
			fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
		} finally {
			super.afterInvocation(token, null);
		}

	}

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		FilterInvocation fi = new FilterInvocation(request, response, chain);
		invoke(fi);
	}

	public void init(FilterConfig arg0) throws ServletException {

	}

}


MyInvocationSecurityMetadataSource.java

package org.joshua.ss;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.joshua.ss.entity.SysAuthorities;
import org.joshua.ss.entity.SysAuthoritiesResources;
import org.joshua.ss.service.AuthorityManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; //import org.springframework.security.web.access.intercept.RequestKey;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;

/**
 * 最核心的地方,就是提供某个资源对应的权限定义,即getAttributes方法返回的结果。 此类在初始化时,应该取到所有资源及其对应角色的定义。
 * 
 * @author Joshua
 * 
 */
public class MyInvocationSecurityMetadataSource implements
		FilterInvocationSecurityMetadataSource {

	private UrlMatcher urlMatcher = new AntUrlPathMatcher();

	private static Map<String, Collection<ConfigAttribute>> resourceMap=null;

	public MyInvocationSecurityMetadataSource() {
		loadResourceDefine();
	}

	private void loadResourceDefine() {

		resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
		// Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
		// 获取所有的authority_name的List
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "applicationContext.xml",
						"applicationContext_db.xml" });
		// 获取业务层对象
		AuthorityManager authorityManager = (AuthorityManager) context
				.getBean("authorityManager");
		List<SysAuthorities> authoritiesList = new ArrayList<SysAuthorities>();
		authoritiesList = authorityManager.getAll();
		// 获得为authority_name 对应的 resource_string的 放入resourceMap
		for (SysAuthorities auth : authoritiesList) {
			ConfigAttribute ca = new SecurityConfig(auth.getAuthorityName());

			Set<SysAuthoritiesResources> authoritiesResources = auth
					.getSysAuthoritiesResourceses();
			for (SysAuthoritiesResources authorityResource : authoritiesResources) {
				// resourceList.add(authorityResource.getSysResources());
				String url = authorityResource.getSysResources()
						.getResourceString();
				
				if (resourceMap.containsKey(url)) {
					Collection<ConfigAttribute> value = resourceMap.get(url);
					value.add(ca);
					resourceMap.put(url, value);
				} else {
					Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
					atts.add(ca);
					resourceMap.put(url, atts);
					
				}

			}
		}
		
	}

	// According to a URL, Find out permission configuration of this URL.
	public Collection<ConfigAttribute> getAllConfigAttributes() {

		return null;
	}

	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		// object 是一个URL,被用户请求的url。
		String url = ((FilterInvocation) object).getRequestUrl();
		//??
		System.out.println(getClass().getName() + "~~~~~~~~~" + url);

		int firstQuestionMarkIndex = url.indexOf("?");

		if (firstQuestionMarkIndex != -1) {
			url = url.substring(0, firstQuestionMarkIndex);
		}

		Iterator<String> ite = resourceMap.keySet().iterator();
		while (ite.hasNext()) {
			String resURL = ite.next();
			if (urlMatcher.pathMatchesUrl(url, resURL)) {

				return resourceMap.get(resURL);

			}

		}

		return null;
	}

	public boolean supports(Class<?> arg0) {

		return true;
	}

}


MyUserDetails.java

package org.joshua.ss;

import java.util.Set;

import org.springframework.security.core.userdetails.UserDetails;

/**
 *@author Joshua
 *@version 2011-12-27 上午11:14:46
 */
public interface MyUserDetails extends UserDetails{
	//用户id
	public String getUserId();
	//用户账户
	public String getUserAccount();
	//用户名
	public String getUserName();
	//用户密码
	public String getUserPassword();
	//用户描述或简介
	public String getUserDesc();
	//用户是否能用
	public boolean getEnabled();
	//是否超级用户
	public Boolean getIssys();	
	//所属的单位
	public String getUserDept();
	//用户职位
	public String getUserDuty();
	//用户分管的子系统
	public String getSubSystem();	
	//用户相对应的角色集
	public Set getSysUsersRoleses();
}


MyUserDetailService.java

package org.joshua.ss;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

import javax.annotation.Resource;

import org.joshua.ss.entity.SysUsers;
import org.joshua.ss.service.UserManager;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class MyUserDetailService implements UserDetailsService {
	@Resource(name = "userManager")
	private UserManager userManager;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		if (null == userManager) {
			userManager = new UserManager();
		}

		// 得到用户的权限
		auths = userManager.loadUserAuthoritiesByName(username);
		// 根据用户名取得一个SysUsers对象,以获取该用户的其他信息。
		
		SysUsers user = userManager.userDao.findByUserAccount(username);
		
		System.out.println("user.getUserId() "+user.getUserId()+" user.getUserName()"+user.getUserName()+" user.getUserPassword()"+user.getUserPassword());

		return new SysUsers(
				user.getUserId(),
				user.getUserAccount(), 
				user.getUserName(), 
				user.getUserPassword(), 
				user.getUserDesc(),
				user.getEnabled(),
				user.getIssys(), 
				user.getUserDuty(), 
				user.getUserDept(), 
				user.getSubSystem(), 
				new HashSet(0), 
				true, 
				true, 
				true,
				auths);
		/*return new User(username, user.getUserPassword(), true, true, true, true, auths);
*/
	}

}

参考:http://www.blogjava.net/SpartaYew/archive/2011/06/15/350630.html

http://wenku.baidu.com/view/4ec7e324ccbff121dd368364.html

Spring+Security+安全权限管理手册  family168 (讲的比较细,够基础,好理解)





你可能感兴趣的:(spring,String,Security,null,Authentication,Class)