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 (講的比較細,夠基礎,好理解)





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章