Spring Security3的搭建使用

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

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

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

用户表

[sql] view plain copy
  1. create table SYS_USERS  
  2. (  
  3.   USER_ID       VARCHAR2(32) not null,  
  4.   USER_ACCOUNT  VARCHAR2(30),  
  5.   USER_NAME     VARCHAR2(40),  
  6.   USER_PASSWORD VARCHAR2(100),  
  7.   USER_DESC     VARCHAR2(100),  
  8.   ENABLED       NUMBER(1),  
  9.   ISSYS         NUMBER(1),  
  10.   USER_DEPT     VARCHAR2(20),  
  11.   USER_DUTY     VARCHAR2(10),  
  12.   SUB_SYSTEM    VARCHAR2(30)  
  13.  );  
  14. alter table SYS_USERS add constraint PK_PUB_USERS primary key (USER_ID);  

角色表
[sql] view plain copy
  1. create table SYS_ROLES  
  2. (  
  3.   ROLE_ID   VARCHAR2(32) not null,  
  4.   ROLE_NAME VARCHAR2(40),  
  5.   ROLE_DESC VARCHAR2(100),  
  6.   ENABLED   NUMBER(1),  
  7.   ISSYS     NUMBER(1),  
  8.   MODULE    VARCHAR2(4)  
  9. );  
  10. alter table SYS_ROLES add constraint PK_PUB_ROLES primary key (ROLE_ID);  

权限表
[sql] view plain copy
  1. create table SYS_AUTHORITIES  
  2. (  
  3.   AUTHORITY_ID   VARCHAR2(32) not null,  
  4.   AUTHORITY_NAME VARCHAR2(40),  
  5.   AUTHORITY_DESC VARCHAR2(100),  
  6.   ENABLED        NUMBER(1),  
  7.   ISSYS          NUMBER(1),  
  8.   MODULE         VARCHAR2(4)  
  9. );  
  10. alter table SYS_AUTHORITIES add constraint PK_PUB_AUTHORITIES primary key (AUTHORITY_ID);  
资源表
[sql] view plain copy
  1. create table SYS_RESOURCES  
  2. (  
  3.   RESOURCE_ID     VARCHAR2(32) not null,  
  4.   RESOURCE_NAME   VARCHAR2(100),  
  5.   RESOURCE_DESC   VARCHAR2(100),  
  6.   RESOURCE_TYPE   VARCHAR2(40),  
  7.   RESOURCE_STRING VARCHAR2(200),  
  8.   PRIORITY        NUMBER(1),  
  9.   ENABLED         NUMBER(1),  
  10.   ISSYS           NUMBER(1),  
  11.   MODULE          VARCHAR2(4)  
  12. );  
  13. alter table SYS_RESOURCES add constraint PK_PUB_RESOURCES primary key (RESOURCE_ID);  

用户角色表
[sql] view plain copy
  1. create table SYS_USERS_ROLES  
  2. (  
  3.   ID      NUMBER(13) not null,  
  4.   USER_ID VARCHAR2(32),  
  5.   ROLE_ID VARCHAR2(32),  
  6.   ENABLED NUMBER(1)  
  7. );  
  8. -- Create/Recreate primary, unique and foreign key constraints   
  9. alter table SYS_USERS_ROLES  add constraint PK_PUB_USERS_ROLES primary key (ID);  
  10.   
  11. alter table SYS_USERS_ROLES  add constraint FK_USERS_ROLES_ROLES foreign key (ROLE_ID)  references SYS_ROLES (ROLE_ID);  
  12. alter table SYS_USERS_ROLES  add constraint FK_USERS_ROLES_USERS foreign key (USER_ID)  references SYS_USERS (USER_ID);  

角色权限表
[sql] view plain copy
  1. create table SYS_ROLES_AUTHORITIES  
  2. (  
  3.   ID           NUMBER(13) not null,  
  4.   ROLE_ID      VARCHAR2(32),  
  5.   AUTHORITY_ID VARCHAR2(32),  
  6.   ENABLED      NUMBER(1)  
  7. );  
  8. -- Create/Recreate primary, unique and foreign key constraints   
  9. alter table SYS_ROLES_AUTHORITIES  add constraint PK_PUB_ROLES_AUTHORITY primary key (ID);  
  10. alter table SYS_ROLES_AUTHORITIES  add constraint FK_PUB_ROLES_AUTHORITIES_AU foreign key (AUTHORITY_ID)  references SYS_AUTHORITIES (AUTHORITY_ID);  
  11. alter table SYS_ROLES_AUTHORITIES  add constraint FK_PUB_ROLES_AUTHORITIES_ROLES foreign key (ROLE_ID)  references SYS_ROLES (ROLE_ID);  

权限资源表
[sql] view plain copy
  1. create table SYS_AUTHORITIES_RESOURCES  
  2. (  
  3.   ID           NUMBER(13) not null,  
  4.   AUTHORITY_ID VARCHAR2(32),  
  5.   RESOURCE_ID  VARCHAR2(32),  
  6.   ENABLED      NUMBER(1)  
  7. );  
  8. -- Create/Recreate primary, unique and foreign key constraints   
  9. alter table SYS_AUTHORITIES_RESOURCES  add constraint PK_PUB_AUTHORITIES_RE primary key (ID);  
  10.     
  11. alter table SYS_AUTHORITIES_RESOURCES  add constraint FK_PUB_AUTHORITIES_RE_AU foreign key (AUTHORITY_ID)  references SYS_AUTHORITIES (AUTHORITY_ID);  
  12. 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包

[java] view plain copy
  1. antlr-2.7.6.jar  
  2. aopalliance.jar  
  3. aspectjrt.jar  
  4. aspectjweaver.jar  
  5. backport-util-concurrent-3.1.jar  
  6. c3p0-0.9.1.2.jar  
  7. cglib-2.2.jar  
  8. cglib-nodep-2.1_3.jar  
  9. classes12.jar  
  10. common-annotations.jar  
  11. commons-collections-3.1.jar  
  12. commons-dbcp-1.3.jar  
  13. commons-fileupload-1.2.1.jar  
  14. commons-io-1.3.2.jar  
  15. commons-logging-1.0.4.jar  
  16. commons-pool.jar  
  17. dom4j-1.6.1.jar  
  18. ehcache-1.5.0.jar  
  19. freemarker-2.3.15.jar  
  20. hibernate-commons-annotations-3.2.0.Final.jar  
  21. hibernate-core-3.6.0.Final.jar  
  22. hibernate-jpa-2.0-api-1.0.0.Final.jar  
  23. hibernate3.jar  
  24. javassist-3.9.0.GA.jar  
  25. jta-1.1.jar  
  26. mysql-connector-java-5.0.0-beta-bin.jar  
  27. ognl-2.7.3.jar  
  28. slf4j-api-1.6.1.jar  
  29. slf4j-nop-1.6.1.jar  
  30. spring-aop-3.0.4.RELEASE.jar  
  31. spring-asm-3.0.4.RELEASE.jar  
  32. spring-beans-3.0.4.RELEASE.jar  
  33. spring-context-3.0.4.RELEASE.jar  
  34. spring-context-support-3.0.4.RELEASE.jar  
  35. spring-core-3.0.4.RELEASE.jar  
  36. spring-expression-3.0.4.RELEASE.jar  
  37. spring-jdbc-3.0.4.RELEASE.jar  
  38. spring-orm-3.0.4.RELEASE.jar  
  39. spring-security-acl-3.0.3.RELEASE.jar  
  40. spring-security-config-3.0.3.RELEASE.jar  
  41. spring-security-core-3.0.3.RELEASE.jar  
  42. spring-security-taglibs-3.0.3.RELEASE.jar  
  43. spring-security-web-3.0.3.RELEASE.jar  
  44. spring-test-3.0.4.RELEASE.jar  
  45. spring-tx-3.0.4.RELEASE.jar  
  46. spring-web-3.0.4.RELEASE.jar  
  47. spring-webmvc-3.0.4.RELEASE.jar  
  48. spring-webmvc-struts.jar  
  49. struts2-core-2.1.8.1.jar  
  50. struts2-spring-plugin-2.1.8.1.jar  
  51. xwork-core-2.1.6.jar  

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

SysAuthorities.java

[java] view plain copy
  1. package org.joshua.ss.entity;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Set;  
  5.   
  6. /** 
  7.  *  
  8.  * @author Joshua 
  9.  * 
  10.  */  
  11. public class SysAuthorities implements Serializable {  
  12.   
  13.     /** 
  14.      *  
  15.      */  
  16.     private static final long serialVersionUID = 6148281916911401715L;  
  17.     private String authorityId;  
  18.     private String authorityName;  
  19.     private String authorityDesc;  
  20.     private Boolean enabled;  
  21.     private Boolean issys;  
  22.     private String module;  
  23.     private Set<SysRolesAuthorities> sysRolesAuthoritieses;  
  24.     private Set<SysAuthoritiesResources> sysAuthoritiesResourceses;  
  25.   
  26.     public SysAuthorities() {  
  27.     }  
  28.   
  29.     public SysAuthorities(String authorityId) {  
  30.         this.authorityId = authorityId;  
  31.     }  
  32.   
  33.     public SysAuthorities(String authorityId, String authorityName,  
  34.             String authorityDesc, Boolean enabled, Boolean issys, String module,  
  35.             Set<SysRolesAuthorities> sysRolesAuthoritieses, Set<SysAuthoritiesResources> sysAuthoritiesResourceses) {  
  36.         this.authorityId = authorityId;  
  37.         this.authorityName = authorityName;  
  38.         this.authorityDesc = authorityDesc;  
  39.         this.enabled = enabled;  
  40.         this.issys = issys;  
  41.         this.module = module;  
  42.         this.sysRolesAuthoritieses = sysRolesAuthoritieses;  
  43.         this.sysAuthoritiesResourceses = sysAuthoritiesResourceses;  
  44.     }  
  45.   
  46.     public String getAuthorityId() {  
  47.         return this.authorityId;  
  48.     }  
  49.   
  50.     public void setAuthorityId(String authorityId) {  
  51.         this.authorityId = authorityId;  
  52.     }  
  53.   
  54.     public String getAuthorityName() {  
  55.         return this.authorityName;  
  56.     }  
  57.   
  58.     public void setAuthorityName(String authorityName) {  
  59.         this.authorityName = authorityName;  
  60.     }  
  61.   
  62.     public String getAuthorityDesc() {  
  63.         return this.authorityDesc;  
  64.     }  
  65.   
  66.     public void setAuthorityDesc(String authorityDesc) {  
  67.         this.authorityDesc = authorityDesc;  
  68.     }  
  69.   
  70.     public Boolean getEnabled() {  
  71.         return this.enabled;  
  72.     }  
  73.   
  74.     public void setEnabled(Boolean enabled) {  
  75.         this.enabled = enabled;  
  76.     }  
  77.   
  78.     public Boolean getIssys() {  
  79.         return this.issys;  
  80.     }  
  81.   
  82.     public void setIssys(Boolean issys) {  
  83.         this.issys = issys;  
  84.     }  
  85.       
  86.     public String getModule() {  
  87.         return this.module;  
  88.     }  
  89.   
  90.     public void setModule(String module) {  
  91.         this.module = module;  
  92.     }  
  93.   
  94.     public Set<SysRolesAuthorities> getSysRolesAuthoritieses() {  
  95.         return sysRolesAuthoritieses;  
  96.     }  
  97.   
  98.     public void setSysRolesAuthoritieses(  
  99.             Set<SysRolesAuthorities> sysRolesAuthoritieses) {  
  100.         this.sysRolesAuthoritieses = sysRolesAuthoritieses;  
  101.     }  
  102.   
  103.     public Set<SysAuthoritiesResources> getSysAuthoritiesResourceses() {  
  104.         return sysAuthoritiesResourceses;  
  105.     }  
  106.   
  107.     public void setSysAuthoritiesResourceses(  
  108.             Set<SysAuthoritiesResources> sysAuthoritiesResourceses) {  
  109.         this.sysAuthoritiesResourceses = sysAuthoritiesResourceses;  
  110.     }  
  111.   
  112.   
  113.   
  114. }  


SysAuthoritiesResources.java
[java] view plain copy
  1. package  org.joshua.ss.entity;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. /** 
  6.  *  
  7.  * @author Joshua 
  8.  * 
  9.  */  
  10. public class SysAuthoritiesResources implements Serializable {  
  11.   
  12.   
  13.     /** 
  14.      *  
  15.      */  
  16.     private static final long serialVersionUID = -2373269722400659636L;  
  17.     private long id;  
  18.     private SysAuthorities sysAuthorities;  
  19.     private SysResources sysResources;  
  20.     private Boolean enabled;  
  21.   
  22.     public SysAuthoritiesResources() {  
  23.     }  
  24.   
  25.     public SysAuthoritiesResources(long id) {  
  26.         this.id = id;  
  27.     }  
  28.   
  29.     public SysAuthoritiesResources(long id, SysAuthorities sysAuthorities,  
  30.             SysResources sysResources, Boolean enabled) {  
  31.         this.id = id;  
  32.         this.sysAuthorities = sysAuthorities;  
  33.         this.sysResources = sysResources;  
  34.         this.enabled = enabled;  
  35.     }  
  36.   
  37.     public long getId() {  
  38.         return this.id;  
  39.     }  
  40.   
  41.     public void setId(long id) {  
  42.         this.id = id;  
  43.     }  
  44.   
  45.     public SysAuthorities getSysAuthorities() {  
  46.         return this.sysAuthorities;  
  47.     }  
  48.   
  49.     public void setSysAuthorities(SysAuthorities sysAuthorities) {  
  50.         this.sysAuthorities = sysAuthorities;  
  51.     }  
  52.   
  53.     public SysResources getSysResources() {  
  54.         return this.sysResources;  
  55.     }  
  56.   
  57.     public void setSysResources(SysResources sysResources) {  
  58.         this.sysResources = sysResources;  
  59.     }  
  60.   
  61.     public Boolean getEnabled() {  
  62.         return this.enabled;  
  63.     }  
  64.   
  65.     public void setEnabled(Boolean enabled) {  
  66.         this.enabled = enabled;  
  67.     }  
  68.   
  69. }  


SysResources.java
[java] view plain copy
  1. package org.joshua.ss.entity;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Set;  
  5.   
  6. /** 
  7.  *  
  8.  * @author Joshua 
  9.  * 
  10.  */  
  11. public class SysResources implements Serializable {  
  12.   
  13.       
  14.     /** 
  15.      *  
  16.      */  
  17.     private static final long serialVersionUID = 6417157583753174159L;  
  18.     private String resourceId;  
  19.     private String resourceName;  
  20.     private String resourceDesc;  
  21.     private String resourceType;  
  22.     private String resourceString;  
  23.     private Boolean priority;  
  24.       
  25.     //是否可用,0为不可用,1为可用。  
  26.     private Integer enabled;  
  27.       
  28.     //是否是超级。0为不超级,1为超级。  
  29.     private Integer issys;  
  30.       
  31.     private String module;  
  32.     private Set<SysAuthoritiesResources> sysAuthoritiesResourceses ;  
  33.   
  34.     public SysResources() {  
  35.     }  
  36.   
  37.     public SysResources(String resourceId) {  
  38.         this.resourceId = resourceId;  
  39.     }  
  40.   
  41.     public SysResources(String resourceId, String resourceName,  
  42.             String resourceDesc, String resourceType, String resourceString,  
  43.             Boolean priority, Integer enabled, Integer issys, String module,  
  44.             Set<SysAuthoritiesResources> sysAuthoritiesResourceses) {  
  45.         this.resourceId = resourceId;  
  46.         this.resourceName = resourceName;  
  47.         this.resourceDesc = resourceDesc;  
  48.         this.resourceType = resourceType;  
  49.         this.resourceString = resourceString;  
  50.         this.priority = priority;  
  51.         this.enabled = enabled;  
  52.         this.issys = issys;  
  53.         this.module = module;  
  54.         this.sysAuthoritiesResourceses = sysAuthoritiesResourceses;  
  55.     }  
  56.   
  57.     public String getResourceId() {  
  58.         return this.resourceId;  
  59.     }  
  60.   
  61.     public void setResourceId(String resourceId) {  
  62.         this.resourceId = resourceId;  
  63.     }  
  64.   
  65.     public String getResourceName() {  
  66.         return this.resourceName;  
  67.     }  
  68.   
  69.     public void setResourceName(String resourceName) {  
  70.         this.resourceName = resourceName;  
  71.     }  
  72.   
  73.     public String getResourceDesc() {  
  74.         return this.resourceDesc;  
  75.     }  
  76.   
  77.     public void setResourceDesc(String resourceDesc) {  
  78.         this.resourceDesc = resourceDesc;  
  79.     }  
  80.   
  81.     public String getResourceType() {  
  82.         return this.resourceType;  
  83.     }  
  84.   
  85.     public void setResourceType(String resourceType) {  
  86.         this.resourceType = resourceType;  
  87.     }  
  88.   
  89.     public String getResourceString() {  
  90.         return this.resourceString;  
  91.     }  
  92.   
  93.     public void setResourceString(String resourceString) {  
  94.         this.resourceString = resourceString;  
  95.     }  
  96.   
  97.     public Boolean getPriority() {  
  98.         return this.priority;  
  99.     }  
  100.   
  101.     public void setPriority(Boolean priority) {  
  102.         this.priority = priority;  
  103.     }  
  104.   
  105.     public Integer getEnabled() {  
  106.         return this.enabled;  
  107.     }  
  108.   
  109.     public void setEnabled(Integer enabled) {  
  110.         this.enabled = enabled;  
  111.     }  
  112.   
  113.     public Integer getIssys() {  
  114.         return this.issys;  
  115.     }  
  116.   
  117.     public void setIssys(Integer issys) {  
  118.         this.issys = issys;  
  119.     }  
  120.       
  121.     public String getModule() {  
  122.         return this.module;  
  123.     }  
  124.   
  125.     public void setModule(String module) {  
  126.         this.module = module;  
  127.     }  
  128.   
  129.     public Set<SysAuthoritiesResources> getSysAuthoritiesResourceses() {  
  130.         return sysAuthoritiesResourceses;  
  131.     }  
  132.   
  133.     public void setSysAuthoritiesResourceses(  
  134.             Set<SysAuthoritiesResources> sysAuthoritiesResourceses) {  
  135.         this.sysAuthoritiesResourceses = sysAuthoritiesResourceses;  
  136.     }  
  137.   
  138.     @Override  
  139.     public int hashCode() {  
  140.         final int prime = 31;  
  141.         int result = 1;  
  142.         result = prime * result + ((enabled == null) ? 0 : enabled.hashCode());  
  143.         result = prime * result + ((issys == null) ? 0 : issys.hashCode());  
  144.         result = prime * result + ((module == null) ? 0 : module.hashCode());  
  145.         result = prime * result  
  146.                 + ((priority == null) ? 0 : priority.hashCode());  
  147.         result = prime * result  
  148.                 + ((resourceDesc == null) ? 0 : resourceDesc.hashCode());  
  149.         result = prime * result  
  150.                 + ((resourceId == null) ? 0 : resourceId.hashCode());  
  151.         result = prime * result  
  152.                 + ((resourceName == null) ? 0 : resourceName.hashCode());  
  153.         result = prime * result  
  154.                 + ((resourceString == null) ? 0 : resourceString.hashCode());  
  155.         result = prime * result  
  156.                 + ((resourceType == null) ? 0 : resourceType.hashCode());  
  157.         result = prime  
  158.                 * result  
  159.                 + ((sysAuthoritiesResourceses == null) ? 0  
  160.                         : sysAuthoritiesResourceses.hashCode());  
  161.         return result;  
  162.     }  
  163.   
  164.     @Override  
  165.     public boolean equals(Object obj) {  
  166.         if (this == obj)  
  167.             return true;  
  168.         if (obj == null)  
  169.             return false;  
  170.         if (getClass() != obj.getClass())  
  171.             return false;  
  172.         SysResources other = (SysResources) obj;  
  173.         if (enabled == null) {  
  174.             if (other.enabled != null)  
  175.                 return false;  
  176.         } else if (!enabled.equals(other.enabled))  
  177.             return false;  
  178.         if (issys == null) {  
  179.             if (other.issys != null)  
  180.                 return false;  
  181.         } else if (!issys.equals(other.issys))  
  182.             return false;  
  183.         if (module == null) {  
  184.             if (other.module != null)  
  185.                 return false;  
  186.         } else if (!module.equals(other.module))  
  187.             return false;  
  188.         if (priority == null) {  
  189.             if (other.priority != null)  
  190.                 return false;  
  191.         } else if (!priority.equals(other.priority))  
  192.             return false;  
  193.         if (resourceDesc == null) {  
  194.             if (other.resourceDesc != null)  
  195.                 return false;  
  196.         } else if (!resourceDesc.equals(other.resourceDesc))  
  197.             return false;  
  198.         if (resourceId == null) {  
  199.             if (other.resourceId != null)  
  200.                 return false;  
  201.         } else if (!resourceId.equals(other.resourceId))  
  202.             return false;  
  203.         if (resourceName == null) {  
  204.             if (other.resourceName != null)  
  205.                 return false;  
  206.         } else if (!resourceName.equals(other.resourceName))  
  207.             return false;  
  208.         if (resourceString == null) {  
  209.             if (other.resourceString != null)  
  210.                 return false;  
  211.         } else if (!resourceString.equals(other.resourceString))  
  212.             return false;  
  213.         if (resourceType == null) {  
  214.             if (other.resourceType != null)  
  215.                 return false;  
  216.         } else if (!resourceType.equals(other.resourceType))  
  217.             return false;  
  218.         if (sysAuthoritiesResourceses == null) {  
  219.             if (other.sysAuthoritiesResourceses != null)  
  220.                 return false;  
  221.         } else if (!sysAuthoritiesResourceses  
  222.                 .equals(other.sysAuthoritiesResourceses))  
  223.             return false;  
  224.         return true;  
  225.     }  
  226.   
  227. }  


SysRoles.java
[java] view plain copy
  1. package org.joshua.ss.entity;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Set;  
  5.   
  6. import org.joshua.ss.dao.daoimpl.BaseDaoImpl;  
  7.   
  8.   
  9. public class SysRoles implements Serializable {  
  10.   
  11.   
  12.     /** 
  13.      *  
  14.      */  
  15.     private static final long serialVersionUID = -243340671938105177L;  
  16.     private String roleId;  
  17.     private String roleName;  
  18.     private String roleDesc;  
  19.     private Boolean enabled;  
  20.     private Boolean issys;  
  21.       
  22.     //平台中的子系统  
  23.     private String module;  
  24.       
  25.     private Set<SysUsersRoles> sysUsersRoles;  
  26.     private Set<SysRolesAuthorities> sysRolesAuthorities;  
  27.   
  28.     public SysRoles() {  
  29.     }  
  30.   
  31.     public SysRoles(String roleId) {  
  32.         this.roleId = roleId;  
  33.     }  
  34.       
  35.     public SysRoles(String roleId, String roleName, String roleDesc) {  
  36.         this.roleId = roleId;  
  37.         this.roleName = roleName;  
  38.         this.roleDesc = roleDesc;  
  39.     }  
  40.       
  41.     public SysRoles(String roleId, String roleName, String roleDesc,  
  42.             Boolean enabled, Boolean issys, String module) {  
  43.         this.roleId = roleId;  
  44.         this.roleName = roleName;  
  45.         this.roleDesc = roleDesc;  
  46.         this.enabled = enabled;  
  47.         this.issys = issys;  
  48.         this.module = module;  
  49.     }  
  50.   
  51.     public SysRoles(String roleId, String roleName, String roleDesc,  
  52.             Boolean enabled, Boolean issys, String module, Set<SysUsersRoles> sysUsersRoles,  
  53.             Set<SysRolesAuthorities> sysRolesAuthorities) {  
  54.         this.roleId = roleId;  
  55.         this.roleName = roleName;  
  56.         this.roleDesc = roleDesc;  
  57.         this.enabled = enabled;  
  58.         this.issys = issys;  
  59.         this.module = module;  
  60.         this.sysUsersRoles = sysUsersRoles;  
  61.         this.sysRolesAuthorities = sysRolesAuthorities;  
  62.     }  
  63.   
  64.     public String getRoleId() {  
  65.         return this.roleId;  
  66.     }  
  67.   
  68.     public void setRoleId(String roleId) {  
  69.         this.roleId = roleId;  
  70.     }  
  71.   
  72.     public String getRoleName() {  
  73.         return this.roleName;  
  74.     }  
  75.   
  76.     public void setRoleName(String roleName) {  
  77.         this.roleName = roleName;  
  78.     }  
  79.   
  80.     public String getRoleDesc() {  
  81.         return this.roleDesc;  
  82.     }  
  83.   
  84.     public void setRoleDesc(String roleDesc) {  
  85.         this.roleDesc = roleDesc;  
  86.     }  
  87.   
  88.     public Boolean getEnabled() {  
  89.         return this.enabled;  
  90.     }  
  91.   
  92.     public void setEnabled(Boolean enabled) {  
  93.         this.enabled = enabled;  
  94.     }  
  95.   
  96.     public Boolean getIssys() {  
  97.         return this.issys;  
  98.     }  
  99.   
  100.     public void setIssys(Boolean issys) {  
  101.         this.issys = issys;  
  102.     }  
  103.       
  104.       
  105.     public String getModule() {  
  106.         return this.module;  
  107.     }  
  108.   
  109.     public void setModule(String module) {  
  110.         this.module = module;  
  111.     }  
  112.   
  113.     public Set<SysUsersRoles> getSysUsersRoles() {  
  114.         return this.sysUsersRoles;  
  115.     }  
  116.   
  117.     public void setSysUsersRoles(Set<SysUsersRoles> sysUsersRoles) {  
  118.         this.sysUsersRoles = sysUsersRoles;  
  119.     }  
  120.   
  121.     public Set<SysRolesAuthorities> getSysRolesAuthorities() {  
  122.         return this.sysRolesAuthorities;  
  123.     }  
  124.   
  125.     public void setSysRolesAuthorities(Set<SysRolesAuthorities> sysRolesAuthorities) {  
  126.         this.sysRolesAuthorities = sysRolesAuthorities;  
  127.     }  
  128.   
  129.     @Override  
  130.     public int hashCode() {  
  131.         final int prime = 31;  
  132.         int result = 1;  
  133.         result = prime * result + ((enabled == null) ? 0 : enabled.hashCode());  
  134.         result = prime * result + ((issys == null) ? 0 : issys.hashCode());  
  135.         result = prime * result + ((module == null) ? 0 : module.hashCode());  
  136.         result = prime * result  
  137.                 + ((roleDesc == null) ? 0 : roleDesc.hashCode());  
  138.         result = prime * result + ((roleId == null) ? 0 : roleId.hashCode());  
  139.         result = prime * result  
  140.                 + ((roleName == null) ? 0 : roleName.hashCode());  
  141.         result = prime  
  142.                 * result  
  143.                 + ((sysRolesAuthorities == null) ? 0 : sysRolesAuthorities  
  144.                         .hashCode());  
  145.         result = prime * result  
  146.                 + ((sysUsersRoles == null) ? 0 : sysUsersRoles.hashCode());  
  147.         return result;  
  148.     }  
  149.   
  150.     @Override  
  151.     public boolean equals(Object obj) {  
  152.         if (this == obj)  
  153.             return true;  
  154.         if (obj == null)  
  155.             return false;  
  156.         if (getClass() != obj.getClass())  
  157.             return false;  
  158.         SysRoles other = (SysRoles) obj;  
  159.         if (enabled == null) {  
  160.             if (other.enabled != null)  
  161.                 return false;  
  162.         } else if (!enabled.equals(other.enabled))  
  163.             return false;  
  164.         if (issys == null) {  
  165.             if (other.issys != null)  
  166.                 return false;  
  167.         } else if (!issys.equals(other.issys))  
  168.             return false;  
  169.         if (module == null) {  
  170.             if (other.module != null)  
  171.                 return false;  
  172.         } else if (!module.equals(other.module))  
  173.             return false;  
  174.         if (roleDesc == null) {  
  175.             if (other.roleDesc != null)  
  176.                 return false;  
  177.         } else if (!roleDesc.equals(other.roleDesc))  
  178.             return false;  
  179.         if (roleId == null) {  
  180.             if (other.roleId != null)  
  181.                 return false;  
  182.         } else if (!roleId.equals(other.roleId))  
  183.             return false;  
  184.         if (roleName == null) {  
  185.             if (other.roleName != null)  
  186.                 return false;  
  187.         } else if (!roleName.equals(other.roleName))  
  188.             return false;  
  189.         if (sysRolesAuthorities == null) {  
  190.             if (other.sysRolesAuthorities != null)  
  191.                 return false;  
  192.         } else if (!sysRolesAuthorities.equals(other.sysRolesAuthorities))  
  193.             return false;  
  194.         if (sysUsersRoles == null) {  
  195.             if (other.sysUsersRoles != null)  
  196.                 return false;  
  197.         } else if (!sysUsersRoles.equals(other.sysUsersRoles))  
  198.             return false;  
  199.         return true;  
  200.     }  
  201.   
  202. }  


SysRolesAuthorities.java


[java] view plain copy
  1. package org.joshua.ss.entity;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5.   
  6. public class SysRolesAuthorities implements Serializable {  
  7.   
  8.     /** 
  9.      *  
  10.      */  
  11.     private static final long serialVersionUID = -4270137978962070889L;  
  12.     private long id;  
  13.     private SysAuthorities sysAuthorities;  
  14.     private SysRoles sysRoles;  
  15.     private Boolean enabled;  
  16.   
  17.     public SysRolesAuthorities() {  
  18.     }  
  19.   
  20.     public SysRolesAuthorities(long id) {  
  21.         this.id = id;  
  22.     }  
  23.   
  24.     public SysRolesAuthorities(long id, SysAuthorities sysAuthorities,  
  25.             SysRoles sysRoles, Boolean enabled) {  
  26.         this.id = id;  
  27.         this.sysAuthorities = sysAuthorities;  
  28.         this.sysRoles = sysRoles;  
  29.         this.enabled = enabled;  
  30.     }  
  31.   
  32.     public long getId() {  
  33.         return this.id;  
  34.     }  
  35.   
  36.     public void setId(long id) {  
  37.         this.id = id;  
  38.     }  
  39.   
  40.     public SysAuthorities getSysAuthorities() {  
  41.         return this.sysAuthorities;  
  42.     }  
  43.   
  44.     public void setSysAuthorities(SysAuthorities sysAuthorities) {  
  45.         this.sysAuthorities = sysAuthorities;  
  46.     }  
  47.   
  48.     public SysRoles getSysRoles() {  
  49.         return this.sysRoles;  
  50.     }  
  51.   
  52.     public void setSysRoles(SysRoles sysRoles) {  
  53.         this.sysRoles = sysRoles;  
  54.     }  
  55.   
  56.     public Boolean getEnabled() {  
  57.         return this.enabled;  
  58.     }  
  59.   
  60.     public void setEnabled(Boolean enabled) {  
  61.         this.enabled = enabled;  
  62.     }  
  63.       
  64. }  


SysUsers.java
[java] view plain copy
  1. package org.joshua.ss.entity;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Collection;  
  5. import java.util.Collections;  
  6. import java.util.Comparator;  
  7. import java.util.HashSet;  
  8. import java.util.Set;  
  9. import java.util.SortedSet;  
  10. import java.util.TreeSet;  
  11.   
  12. import org.joshua.ss.MyUserDetails;  
  13. import org.springframework.security.core.GrantedAuthority;  
  14. import org.springframework.util.Assert;  
  15.   
  16.   
  17.   
  18. /** 
  19.  *  
  20.  * @author Joshua 
  21.  * 
  22.  */  
  23. public class SysUsers implements MyUserDetails,Serializable {  
  24.   
  25.     /** 
  26.      *  
  27.      */  
  28.     private static final long serialVersionUID = -8680337263599302062L;  
  29.   
  30.     //用户id  
  31.     private String userId;  
  32.       
  33.     //用户账号 与 用户id相同,具有唯一性。  
  34.     private String userAccount;  
  35.       
  36.     //中文用户名。  
  37.     private String userName;  
  38.       
  39.     //密码原文 + 用户名作为盐值 的字串经过Md5加密后形成的密文。  
  40.     private String userPassword;  
  41.       
  42.     //用户备注  
  43.     private String userDesc;  
  44.       
  45.     //是否能用。  
  46.     private Boolean enabled;  
  47.       
  48.     //是否是超级用户。  
  49.     private Boolean issys;  
  50.       
  51.     //用户所在的单位。  
  52.     private String userDept;  
  53.       
  54.     //用户的职位:比如主任、经理等。  
  55.     private String userDuty;  
  56.       
  57.     //该用户所负责的子系统  
  58.     private String subSystem;  
  59.       
  60.     //一个用户具有多个角色。  
  61.     private Set<SysUsersRoles> sysUsersRoleses =new HashSet(0);  
  62.       
  63.       
  64.       
  65.       
  66.       
  67.       
  68.       
  69.       
  70.     //实现了UserDetails之后的相关变量  
  71.     private  String password;  
  72.     private  String username;  
  73.     private  Set<GrantedAuthority> authorities;  
  74.     private  boolean accountNonExpired;  
  75.     private  boolean accountNonLocked;  
  76.     private  boolean credentialsNonExpired;   
  77.       
  78.     public SysUsers(){  
  79.           
  80.     }  
  81.           
  82.     public SysUsers(String userId, String userAccount, String userName,  
  83.             String userPassword, String userDesc, Boolean enabled,  
  84.             Boolean issys, String userDept, String userDuty, String subSystem,  
  85.             Set<SysUsersRoles> sysUsersRoleses,boolean accountNonExpired, boolean accountNonLocked,  
  86.             boolean credentialsNonExpired,Collection<GrantedAuthority> authorities) {  
  87.           
  88.         if (((userAccount == null) || "".equals(userAccount)) || (userPassword == null)) {  
  89.             throw new IllegalArgumentException("Cannot pass null or empty values to constructor");  
  90.         }  
  91.           
  92.         this.userId = userId;  
  93.         this.userAccount = userAccount;  
  94.         this.userName = userName;  
  95.         this.userPassword = userPassword;  
  96.         this.userDesc = userDesc;  
  97.         this.enabled = enabled;  
  98.         this.issys = issys;  
  99.         this.userDept = userDept;  
  100.         this.userDuty = userDuty;  
  101.         this.subSystem = subSystem;  
  102.         this.sysUsersRoleses = sysUsersRoleses;  
  103.         this.password = userPassword;  
  104.         this.username = userAccount;  
  105.         this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));  
  106.         this.accountNonExpired = accountNonExpired;  
  107.         this.accountNonLocked = accountNonLocked;  
  108.         this.credentialsNonExpired = credentialsNonExpired;  
  109.     }  
  110.   
  111.   
  112.     //~ Methods ========================================================================================================  
  113.   
  114.     public boolean equals(Object rhs) {  
  115.         if (!(rhs instanceof SysUsers) || (rhs == null)) {  
  116.             return false;  
  117.         }  
  118.   
  119.         SysUsers user = (SysUsers) rhs;  
  120.   
  121.         //具有的权限。  
  122.         if (!authorities.equals(user.authorities)) {  
  123.             return false;  
  124.         }  
  125.   
  126.         // 通过Spring Security构建一个用户时,用户名和密码不能为空。  
  127.         return (this.getPassword().equals(user.getPassword()) && this.getUsername().equals(user.getUsername())  
  128.                 && (this.isAccountNonExpired() == user.isAccountNonExpired())  
  129.                 && (this.isAccountNonLocked() == user.isAccountNonLocked())  
  130.                 && (this.isCredentialsNonExpired() == user.isCredentialsNonExpired())  
  131.                 && (this.isEnabled() == user.isEnabled()));  
  132.     }  
  133.   
  134.     public String getUserId() {  
  135.         return this.userId;  
  136.     }  
  137.   
  138.     public void setUserId(String userId) {  
  139.         this.userId = userId;  
  140.     }  
  141.   
  142.     public String getUserAccount() {  
  143.         return this.userAccount;  
  144.     }  
  145.   
  146.     public void setUserAccount(String userAccount) {  
  147.         this.userAccount = userAccount;  
  148.     }  
  149.   
  150.     public String getUserName() {  
  151.         return this.userName;  
  152.     }  
  153.   
  154.     public void setUserName(String userName) {  
  155.         this.userName = userName;  
  156.     }  
  157.   
  158.     public String getUserPassword() {  
  159.         return this.userPassword;  
  160.     }  
  161.   
  162.     public void setUserPassword(String userPassword) {  
  163.         this.userPassword = userPassword;  
  164.     }  
  165.   
  166.     public String getUserDesc() {  
  167.         return this.userDesc;  
  168.     }  
  169.   
  170.     public void setUserDesc(String userDesc) {  
  171.         this.userDesc = userDesc;  
  172.     }  
  173.   
  174.     public boolean getEnabled() {  
  175.         return this.enabled;  
  176.     }  
  177.   
  178.     public void setEnabled(Boolean enabled) {  
  179.         this.enabled = enabled;  
  180.     }  
  181.   
  182.     public Boolean getIssys() {  
  183.         return this.issys;  
  184.     }  
  185.   
  186.     public void setIssys(Boolean issys) {  
  187.         this.issys = issys;  
  188.     }  
  189.       
  190.     public String getUserDept() {  
  191.         return this.userDept;  
  192.     }  
  193.   
  194.     public void setUserDept(String userDept) {  
  195.         this.userDept = userDept;  
  196.     }  
  197.       
  198.     public String getUserDuty() {  
  199.         return this.userDuty;  
  200.     }  
  201.   
  202.     public void setUserDuty(String userDuty) {  
  203.         this.userDuty = userDuty;  
  204.     }     
  205.   
  206.     public String getSubSystem() {  
  207.         return this.subSystem;  
  208.     }  
  209.   
  210.     public void setSubSystem(String subSystem) {  
  211.         this.subSystem = subSystem;  
  212.     }  
  213.       
  214.     public Set<SysUsersRoles> getSysUsersRoleses() {  
  215.         return this.sysUsersRoleses;  
  216.     }  
  217.   
  218.     public void setSysUsersRoleses(Set<SysUsersRoles> sysUsersRoleses) {  
  219.         this.sysUsersRoleses = sysUsersRoleses;  
  220.     }  
  221.   
  222.   
  223.     public String getPassword() {  
  224.         return password;  
  225.     }  
  226.   
  227.   
  228.     public String getUsername() {  
  229.         return username;  
  230.     }  
  231.   
  232.   
  233.     public Set<GrantedAuthority> getAuthorities() {  
  234.         return authorities;  
  235.     }  
  236.   
  237.   
  238.     public void setAuthorities(Set<GrantedAuthority> authorities) {  
  239.         this.authorities = authorities;  
  240.     }  
  241.   
  242.   
  243.     public boolean isAccountNonExpired() {  
  244.         return accountNonExpired;  
  245.     }  
  246.   
  247.     public boolean isAccountNonLocked() {  
  248.         return accountNonLocked;  
  249.     }  
  250.   
  251.   
  252.     public boolean isCredentialsNonExpired() {  
  253.         return credentialsNonExpired;  
  254.     }  
  255.   
  256.     public boolean isEnabled() {  
  257.         return enabled;  
  258.     }  
  259.       
  260.   
  261.     public int hashCode() {  
  262.         int code = 9792;  
  263.   
  264.       //若该用户不是登录人员,则可以允许没有authorities。  
  265.         if (null != getUsername() && null != getAuthorities()) {  
  266.             for (GrantedAuthority authority : getAuthorities()) {  
  267.   
  268.                 code = code * (authority.hashCode() % 7);  
  269.             }  
  270.         }  
  271.   
  272.         if (this.getPassword() != null) {  
  273.             code = code * (this.getPassword().hashCode() % 7);  
  274.         }  
  275.   
  276.         if (this.getUsername() != null) {  
  277.             code = code * (this.getUsername().hashCode() % 7);  
  278.         }  
  279.   
  280.         if (this.isAccountNonExpired()) {  
  281.             code = code * -2;  
  282.         }  
  283.   
  284.         if (this.isAccountNonLocked()) {  
  285.             code = code * -3;  
  286.         }  
  287.   
  288.         if (this.isCredentialsNonExpired()) {  
  289.             code = code * -5;  
  290.         }  
  291.   
  292.         if (this.isEnabled()) {  
  293.             code = code * -7;  
  294.         }  
  295.   
  296.         return code;  
  297.     }  
  298.   
  299.       
  300.     private static SortedSet<GrantedAuthority> sortAuthorities(Collection<GrantedAuthority> authorities) {  
  301.         Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");  
  302.         // Ensure array iteration order is predictable (as per UserDetails.getAuthorities() contract and SEC-717)  
  303.         SortedSet<GrantedAuthority> sortedAuthorities =  
  304.             new TreeSet<GrantedAuthority>(new AuthorityComparator());  
  305.   
  306.         for (GrantedAuthority grantedAuthority : authorities) {  
  307.             Assert.notNull(grantedAuthority, "GrantedAuthority list cannot contain any null elements");  
  308.             sortedAuthorities.add(grantedAuthority);  
  309.         }  
  310.   
  311.         return sortedAuthorities;  
  312.     }  
  313.      
  314.     private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable {  
  315.         public int compare(GrantedAuthority g1, GrantedAuthority g2) {  
  316.             // Neither should ever be null as each entry is checked before adding it to the set.  
  317.             // If the authority is null, it is a custom authority and should precede others.  
  318.             if (g2.getAuthority() == null) {  
  319.                 return -1;  
  320.             }  
  321.   
  322.             if (g1.getAuthority() == null) {  
  323.                 return 1;  
  324.             }  
  325.             return g1.getAuthority().compareTo(g2.getAuthority());  
  326.         }  
  327.     }  
  328.       
  329.       
  330.     public String toString() {  
  331.         StringBuilder sb = new StringBuilder();  
  332.         sb.append(super.toString()).append(": ");  
  333.         sb.append("Username: ").append(this.username).append("; ");  
  334.         sb.append("" +  
  335.                 "" +  
  336.                 ": [PROTECTED]; ");  
  337.         sb.append("UserAccount: ").append(this.userAccount).append("; ");  
  338.         sb.append("UserDept: ").append(this.userDept).append("; ");  
  339.         sb.append("UserDuty: ").append(this.userDuty).append("; ");  
  340.         sb.append("UserDesc: ").append(this.userDesc).append("; ");  
  341.         sb.append("UserSubSystem: ").append(this.subSystem).append("; ");  
  342.         sb.append("UserIsSys: ").append(this.issys).append("; ");  
  343.         sb.append("Enabled: ").append(this.enabled).append("; ");  
  344.         sb.append("AccountNonExpired: ").append(this.accountNonExpired).append("; ");  
  345.         sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired).append("; ");  
  346.         sb.append("AccountNonLocked: ").append(this.accountNonLocked).append("; ");  
  347.   
  348.         if ( null !=authorities  && !authorities.isEmpty()) {  
  349.             sb.append("Granted Authorities: ");  
  350.   
  351.             boolean first = true;  
  352.             for (GrantedAuthority auth : authorities) {  
  353.                 if (!first) {  
  354.                     sb.append(",");  
  355.                 }  
  356.                 first = false;  
  357.   
  358.                 sb.append(auth);  
  359.             }  
  360.         } else {  
  361.             sb.append("Not granted any authorities");  
  362.         }  
  363.   
  364.         return sb.toString();  
  365.     }  
  366.   
  367. }  


SysUsersRoles.java


[java] view plain copy
  1. package org.joshua.ss.entity;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class SysUsersRoles implements Serializable {  
  6.   
  7.     /** 
  8.      *  
  9.      */  
  10.     private static final long serialVersionUID = 393623940722220854L;  
  11.     private long id;  
  12.     private SysUsers pubUsers;  
  13.     private SysRoles pubRoles;  
  14.     private Boolean enabled;  
  15.   
  16.     public SysUsersRoles() {  
  17.     }  
  18.   
  19.     public SysUsersRoles(long id) {  
  20.         this.id = id;  
  21.     }  
  22.   
  23.     public SysUsersRoles(long id, SysUsers pubUsers, SysRoles pubRoles,  
  24.             Boolean enabled) {  
  25.         this.id = id;  
  26.         this.pubUsers = pubUsers;  
  27.         this.pubRoles = pubRoles;  
  28.         this.enabled = enabled;  
  29.     }  
  30.   
  31.     public long getId() {  
  32.         return this.id;  
  33.     }  
  34.   
  35.     public void setId(long id) {  
  36.         this.id = id;  
  37.     }  
  38.   
  39.     public SysUsers getSysUsers() {  
  40.         return this.pubUsers;  
  41.     }  
  42.   
  43.     public void setSysUsers(SysUsers pubUsers) {  
  44.         this.pubUsers = pubUsers;  
  45.     }  
  46.   
  47.     public SysRoles getSysRoles() {  
  48.         return this.pubRoles;  
  49.     }  
  50.   
  51.     public void setSysRoles(SysRoles pubRoles) {  
  52.         this.pubRoles = pubRoles;  
  53.     }  
  54.   
  55.     public Boolean getEnabled() {  
  56.         return this.enabled;  
  57.     }  
  58.   
  59.     public void setEnabled(Boolean enabled) {  
  60.         this.enabled = enabled;  
  61.     }  
  62.   
  63. }  
2.2.2对应的映射文件xxx.hbm.xml

SysAuthorities.hbm.xml

[html] view plain copy
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!-- Generated 2011-3-23 11:09:37 by Hibernate Tools 3.2.2.GA -->  
  5. <hibernate-mapping>  
  6.     <class name="org.joshua.ss.entity.SysAuthorities" table="SYS_AUTHORITIES">  
  7.         <id name="authorityId" type="string">  
  8.             <column name="AUTHORITY_ID" length="32" />  
  9.             <generator class="assigned" />  
  10.         </id>  
  11.         <property name="authorityName" type="string">  
  12.             <column name="AUTHORITY_NAME" length="40" />  
  13.         </property>  
  14.         <property name="authorityDesc" type="string">  
  15.             <column name="AUTHORITY_DESC" length="100" />  
  16.         </property>  
  17.         <property name="enabled" type="java.lang.Boolean">  
  18.             <column name="ENABLED" precision="1" scale="0" />  
  19.         </property>  
  20.         <property name="issys" type="java.lang.Boolean">  
  21.             <column name="ISSYS" precision="1" scale="0" />  
  22.         </property>  
  23.         <property name="module" type="string">  
  24.             <column name="MODULE" length="4" />  
  25.         </property>  
  26.         <set name="sysRolesAuthoritieses" inverse="true" cascade="all" lazy="false">  
  27.             <key>  
  28.                 <column name="AUTHORITY_ID" length="32" />  
  29.             </key>  
  30.             <one-to-many class="org.joshua.ss.entity.SysRolesAuthorities" />  
  31.         </set>  
  32.         <set name="sysAuthoritiesResourceses" inverse="true" cascade="all" lazy="false">  
  33.             <key>  
  34.                 <column name="AUTHORITY_ID" length="32" />  
  35.             </key>  
  36.             <one-to-many class="org.joshua.ss.entity.SysAuthoritiesResources" />  
  37.         </set>  
  38.     </class>  
  39. </hibernate-mapping>  


SysAuthoritiesResources.hbm.xml


[html] view plain copy
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <hibernate-mapping>  
  5.     <class name="org.joshua.ss.entity.SysAuthoritiesResources" table="SYS_AUTHORITIES_RESOURCES">  
  6.         <id name="id" type="long">  
  7.             <column name="ID" precision="13" scale="0" />  
  8.             <generator class="assigned" />  
  9.         </id>  
  10.         <many-to-one name="sysAuthorities" class="org.joshua.ss.entity.SysAuthorities" fetch="select" lazy="false">  
  11.             <column name="AUTHORITY_ID" length="32" />  
  12.         </many-to-one>  
  13.         <many-to-one name="sysResources" class="org.joshua.ss.entity.SysResources" fetch="select" lazy="false">  
  14.             <column name="RESOURCE_ID" length="32" />  
  15.         </many-to-one>  
  16.         <property name="enabled" type="java.lang.Boolean">  
  17.             <column name="ENABLED" precision="1" scale="0" />  
  18.         </property>  
  19.     </class>  
  20. </hibernate-mapping>  


SysResources.hbm.xml


[html] view plain copy
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <hibernate-mapping>  
  5.     <class name="org.joshua.ss.entity.SysResources" table="Sys_RESOURCES">  
  6.         <id name="resourceId" type="string">  
  7.             <column name="RESOURCE_ID" length="32" />  
  8.             <generator class="assigned" />  
  9.         </id>  
  10.         <property name="resourceName" type="string">  
  11.             <column name="RESOURCE_NAME" length="100" />  
  12.         </property>  
  13.         <property name="resourceDesc" type="string">  
  14.             <column name="RESOURCE_DESC" length="100" />  
  15.         </property>  
  16.         <property name="resourceType" type="string">  
  17.             <column name="RESOURCE_TYPE" length="40" />  
  18.         </property>  
  19.         <property name="resourceString" type="string">  
  20.             <column name="RESOURCE_STRING" length="200" />  
  21.         </property>  
  22.         <property name="priority" type="java.lang.Boolean">  
  23.             <column name="PRIORITY" precision="1" scale="0" />  
  24.         </property>  
  25.         <property name="enabled" type="java.lang.Integer">  
  26.             <column name="ENABLED" precision="1" scale="0" />  
  27.         </property>  
  28.         <property name="issys" type="java.lang.Integer">  
  29.             <column name="ISSYS" precision="1" scale="0" />  
  30.         </property>  
  31.         <property name="module" type="string">  
  32.             <column name="MODULE" length="4" />  
  33.         </property>  
  34.         <set name="sysAuthoritiesResourceses" inverse="true" lazy="false">  
  35.             <key>  
  36.                 <column name="RESOURCE_ID" length="32" />  
  37.             </key>  
  38.             <one-to-many class="org.joshua.ss.entity.SysAuthoritiesResources" />  
  39.         </set>  
  40.     </class>  
  41. </hibernate-mapping>  


SysRoles.hbm.xml


[html] view plain copy
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <hibernate-mapping>  
  5.     <class name="org.joshua.ss.entity.SysRoles" table="SYS_ROLES">  
  6.         <id name="roleId" type="string">  
  7.             <column name="ROLE_ID" length="32" />  
  8.             <generator class="assigned" />  
  9.         </id>  
  10.         <property name="roleName" type="string">  
  11.             <column name="ROLE_NAME" length="40" />  
  12.         </property>  
  13.         <property name="roleDesc" type="string">  
  14.             <column name="ROLE_DESC" length="100" />  
  15.         </property>  
  16.         <property name="enabled" type="java.lang.Boolean">  
  17.             <column name="ENABLED" precision="1" scale="0" />  
  18.         </property>  
  19.         <property name="issys" type="java.lang.Boolean">  
  20.             <column name="ISSYS" precision="1" scale="0" />  
  21.         </property>  
  22.         <property name="module" type="string">  
  23.             <column name="MODULE" length="4" />  
  24.         </property>  
  25.         <set name="sysUsersRoles" inverse="true" cascade="all" lazy="false">  
  26.             <key>  
  27.                 <column name="ROLE_ID" length="32" />  
  28.             </key>  
  29.             <one-to-many class="org.joshua.ss.entity.SysUsersRoles"/>  
  30.         </set>  
  31.         <set name="sysRolesAuthorities" inverse="true" cascade="all" lazy="false">  
  32.             <key>  
  33.                 <column name="ROLE_ID" length="32" />  
  34.             </key>  
  35.             <one-to-many class="org.joshua.ss.entity.SysRolesAuthorities" />  
  36.         </set>  
  37.     </class>  
  38. </hibernate-mapping>  


SysRolesAuthorities.hbm.xml


[html] view plain copy
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!-- Generated 2011-3-23 11:09:37 by Hibernate Tools 3.2.2.GA -->  
  5. <hibernate-mapping>  
  6.     <class name="org.joshua.ss.entity.SysRolesAuthorities" table="SYS_ROLES_AUTHORITIES">  
  7.         <id name="id" type="long">  
  8.             <column name="ID" precision="13" scale="0" />  
  9.             <generator class="assigned" />  
  10.         </id>  
  11.         <many-to-one name="sysAuthorities" class="org.joshua.ss.entity.SysAuthorities" fetch="select" lazy="false">  
  12.             <column name="AUTHORITY_ID" length="32" />  
  13.         </many-to-one>  
  14.         <many-to-one name="sysRoles" class="org.joshua.ss.entity.SysRoles" fetch="select" lazy="false">  
  15.             <column name="ROLE_ID" length="32" />  
  16.         </many-to-one>  
  17.         <!--    
  18.         <property name="authorityId" type="string">  
  19.             <column name="AUTHORITY_ID" length="32" />  
  20.         </property>  
  21.         <property name="roleId" type="string">  
  22.             <column name="ROLE_ID" length="32" />  
  23.         </property> -->  
  24.         <property name="enabled" type="java.lang.Boolean">  
  25.             <column name="ENABLED" precision="1" scale="0" />  
  26.         </property>  
  27.     </class>  
  28. </hibernate-mapping>  


SysUsers.hbm.xml


[html] view plain copy
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <hibernate-mapping>  
  5.     <class name="org.joshua.ss.entity.SysUsers" table="SYS_USERS">  
  6.         <id name="userId" type="string">  
  7.             <column name="USER_ID" length="32" />  
  8.             <generator class="assigned" />  
  9.         </id>  
  10.         <property name="userAccount" type="string">  
  11.             <column name="USER_ACCOUNT" length="30" />  
  12.         </property>  
  13.         <property name="userName" type="string">  
  14.             <column name="USER_NAME" length="40" />  
  15.         </property>  
  16.         <property name="userPassword" type="string">  
  17.             <column name="USER_PASSWORD" length="100" />  
  18.         </property>  
  19.         <property name="userDesc" type="string">  
  20.             <column name="USER_DESC" length="100" />  
  21.         </property>  
  22.         <property name="userDuty" type="string">  
  23.             <column name="USER_DUTY" length="10" />  
  24.         </property>  
  25.         <property name="userDept" type="string">  
  26.             <column name="USER_DEPT" length="20" />  
  27.         </property>  
  28.         <property name="subSystem" type="string">  
  29.             <column name="SUB_SYSTEM" length="30" />  
  30.         </property>  
  31.         <property name="enabled" type="java.lang.Boolean">  
  32.             <column name="ENABLED" precision="1" scale="0" />  
  33.         </property>  
  34.         <property name="issys" type="java.lang.Boolean">  
  35.             <column name="ISSYS" precision="1" scale="0" />  
  36.         </property>  
  37.         <set name="sysUsersRoleses" inverse="true" cascade="all" lazy="false">  
  38.             <key>  
  39.                 <column name="USER_ID" length="32" />  
  40.             </key>  
  41.             <one-to-many class="org.joshua.ss.entity.SysUsersRoles" />  
  42.         </set>  
  43.     </class>  
  44. </hibernate-mapping>  


SysUsersRoles.hbm.xml
[html] view plain copy
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <hibernate-mapping>  
  5.     <class name="org.joshua.ss.entity.SysUsersRoles" table="SYS_USERS_ROLES">  
  6.         <id name="id" type="long">  
  7.             <column name="ID" precision="13" scale="0" />  
  8.             <generator class="assigned" />  
  9.         </id>  
  10.         <many-to-one name="sysUsers" class="org.joshua.ss.entity.SysUsers" fetch="select" lazy="false">  
  11.             <column name="USER_ID" length="32" />  
  12.         </many-to-one>  
  13.         <many-to-one name="sysRoles" class="org.joshua.ss.entity.SysRoles" fetch="select" lazy="false">  
  14.             <column name="ROLE_ID" length="32" />  
  15.         </many-to-one>  
  16.         <property name="enabled" type="java.lang.Boolean">  
  17.             <column name="ENABLED" precision="1" scale="0" />  
  18.         </property>  
  19.     </class>  
  20. </hibernate-mapping>  

2.3DAO层和service层的创建

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

BaseDao.java

[java] view plain copy
  1. package org.joshua.ss.dao;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.List;  
  5.   
  6. /** 
  7.  *  
  8.  * @author Joshua 
  9.  * 
  10.  * @param <T> 
  11.  *              DAO操作的对象类型 
  12.  * @param <PK> 
  13.  *              主键类型 
  14.  */  
  15. public interface BaseDao<T,PK extends Serializable> {  
  16.       
  17.       
  18.     /** 
  19.      * 按id获取对象. 
  20.      *  
  21.      */  
  22.     T getById(PK id);  
  23.       
  24.     /** 
  25.      * 保存新增或修改的对象. 
  26.      *  
  27.      */  
  28.     T save(T object);  
  29.       
  30.     /**  
  31.      * 按id删除对象. 
  32.      */  
  33.     void remove(PK id);  
  34.       
  35.     /** 
  36.      * 删除对象. 
  37.      */  
  38.     void remove(final T object);  
  39.       
  40.     /** 
  41.      * 查询全部对象 
  42.      */  
  43.     List<T> getAll();  
  44.       
  45.       
  46. }  


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

[java] view plain copy
  1. package org.joshua.ss.dao.daoimpl;  
  2.   
  3. import java.io.Serializable;  
  4. import java.lang.reflect.ParameterizedType;  
  5. import java.lang.reflect.Type;  
  6. import java.util.List;  
  7.   
  8. import javax.annotation.Resource;  
  9.   
  10. import org.joshua.ss.dao.BaseDao;  
  11. import org.springframework.orm.hibernate3.HibernateTemplate;  
  12. import org.springframework.util.Assert;  
  13.   
  14. /** 
  15.  *@author Joshua 
  16.  *@version 2011-12-15 下午02:27:43 
  17.  */  
  18. /** 
  19.  * 可以在service层直接调用,也可以在DAO层扩展调用 
  20.  */  
  21. public class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK>{  
  22.       
  23.     @Resource(name="hibernateTemplate")  
  24.     private HibernateTemplate hibernateTemplate;  
  25.       
  26.     private Class<T> persistentClass;  
  27.     /** 
  28.      * 用于Dao层子类使用的构造函数. 通过子类的泛型定义取得对象类型 
  29.      */  
  30.   
  31.     @SuppressWarnings("unchecked")  
  32.     public BaseDaoImpl(){  
  33.         //getClass() 返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的超类的 Class。  
  34.         this.persistentClass=(Class<T>)getSuperClassGenricType(getClass(), 0);  
  35.     }  
  36.     public List<T> getAll() {       
  37.         return hibernateTemplate.loadAll(this.persistentClass);  
  38.     }  
  39.   
  40.     public T getById(PK id) {  
  41.         Assert.notNull(id, "id 不可空");  
  42.         T entity =hibernateTemplate.get(this.persistentClass, id);  
  43.         return entity;  
  44.     }  
  45.   
  46.     public void remove(PK id) {  
  47.         Assert.notNull(id, "id 不可空!");  
  48.         hibernateTemplate.delete(this.getById(id));       
  49.     }  
  50.   
  51.     public void remove(final T entity) {  
  52.         Assert.notNull(entity, "entity 不可空!");  
  53.         hibernateTemplate.delete(entity);  
  54.     }  
  55.   
  56.     public T save(T entity) {  
  57.         Assert.notNull(entity, "entity 不可空!");        
  58.         return hibernateTemplate.merge(entity);  
  59.     }  
  60.     /** 
  61.      * 通过反射, 获得定义Class时声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. 
  62.      *  
  63.      *@param clazz 
  64.      *            clazz The class to introspect 
  65.      * @param index 
  66.      *            the Index of the generic ddeclaration,start from 0. 
  67.      * @return the index generic declaration, or Object.class if cannot be 
  68.      *         determined 
  69.      */  
  70.     @SuppressWarnings("unchecked")  
  71.     public static Class<Object> getSuperClassGenricType(final Class clazz, final int index) {  
  72.           
  73.         //返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。  
  74.         Type genType = clazz.getGenericSuperclass();  
  75.   
  76.         if (!(genType instanceof ParameterizedType)) {  
  77.            return Object.class;  
  78.         }  
  79.         //返回表示此类型实际类型参数的 Type 对象的数组。  
  80.         Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
  81.   
  82.         if (index >= params.length || index < 0) {  
  83.                      return Object.class;  
  84.         }  
  85.         if (!(params[index] instanceof Class)) {  
  86.               return Object.class;  
  87.         }  
  88.   
  89.         return (Class) params[index];  
  90.     }  
  91.   
  92. }  


SysAuthoritiesDaoImpl.java
[java] view plain copy
  1. package org.joshua.ss.dao.daoimpl;  
  2.   
  3. import org.joshua.ss.dao.SysAuthoritiesDao;  
  4. import org.joshua.ss.entity.SysAuthorities;  
  5.   
  6. /** 
  7.  *@author Joshua 
  8.  *@version 2011-12-15 上午11:06:22 
  9.  */  
  10. public class SysAuthoritiesDaoImpl extends BaseDaoImpl<SysAuthorities, Long> implements SysAuthoritiesDao {  
  11.   
  12. }  

下同,继承通用dao传递实体类型,也可自定义方法
SysAuthoritiesResourcesDaoImpl.java
SysResourcesDaoImpl.java
SysRolesAuthoritiesDaoImpl.java
SysRolesDaoImpl.java
SysUsersDaoImpl.java
[java] view plain copy
  1. package org.joshua.ss.dao.daoimpl;  
  2.   
  3.   
  4.   
  5. import java.util.List;  
  6.   
  7. import javax.annotation.Resource;  
  8.   
  9. import org.joshua.ss.dao.SysUsersDao;  
  10.   
  11.   
  12. import org.joshua.ss.entity.SysUsers;  
  13. import org.springframework.orm.hibernate3.HibernateTemplate;  
  14. import org.springframework.stereotype.Service;  
  15.   
  16. /** 
  17.  *@author Joshua 
  18.  *@version 2011-12-15 上午11:08:02 
  19.  */  
  20. @Service("sysUsersDaoImpl")  
  21. public class SysUsersDaoImpl extends BaseDaoImpl<SysUsersDao, Long> implements  
  22.         SysUsersDao {  
  23.     @Resource(name="hibernateTemplate")  
  24.     private HibernateTemplate hibernateTemplate;  
  25.   
  26.   
  27.     public SysUsers findByUserAccount(String userName) {  
  28.         try {  
  29.             SysUsers instance;  
  30.             List<SysUsers> instances = hibernateTemplate.find(  
  31.                     "from SysUsers where userAccount='" + userName+"'");  
  32.             if ( null ==instances||instances.isEmpty()) {  
  33.                 System.out.println("没有相匹配的SysUsers实例对象!");  
  34.                 instance = new SysUsers();  
  35.             } else {  
  36.                 instance=instances.get(0);  
  37.                 System.out.println("相匹配的SysUsers实例对象被找到!");  
  38.                 }  
  39.             return instance;  
  40.         } catch (RuntimeException re) {  
  41.             System.out.println("findByUserAccount() 错误!");  
  42.             throw re;  
  43.         }  
  44.     }  
  45.   
  46. }  


SysUsersRolesDaoImpl.java


service层的实现

AuthoritiesResourcesManager.java

[java] view plain copy
  1. package org.joshua.ss.service;  
  2.   
  3. import org.joshua.ss.dao.daoimpl.BaseDaoImpl;  
  4. import org.joshua.ss.entity.SysAuthoritiesResources;  
  5. import org.springframework.stereotype.Service;  
  6.   
  7. /** 
  8.  *@author Joshua 
  9.  *@version 2011-12-20 下午02:19:19 
  10.  */  
  11. @Service("authoritiesResourcesManager")  
  12. public class AuthoritiesResourcesManager extends BaseDaoImpl<SysAuthoritiesResources,Long>{  
  13.   
  14. }  

下同,

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

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

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

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

[java] view plain copy
  1. package org.joshua.ss.service;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.Set;  
  6.   
  7. import javax.annotation.Resource;  
  8.   
  9. import org.joshua.ss.dao.daoimpl.BaseDaoImpl;  
  10. import org.joshua.ss.dao.daoimpl.SysUsersDaoImpl;  
  11. import org.joshua.ss.entity.SysRolesAuthorities;  
  12. import org.joshua.ss.entity.SysUsers;  
  13. import org.joshua.ss.entity.SysUsersRoles;  
  14. import org.springframework.orm.hibernate3.HibernateTemplate;  
  15. import org.springframework.security.core.GrantedAuthority;  
  16. import org.springframework.security.core.authority.GrantedAuthorityImpl;  
  17. import org.springframework.stereotype.Service;  
  18.   
  19. /** 
  20.  *@author Joshua 
  21.  *@version 2011-12-15 下午03:58:38 
  22.  * @param <SysUsers> 
  23.  */  
  24. @Service("userManager")  
  25. public class UserManager extends BaseDaoImpl<SysUsers,Long>{  
  26.     @Resource(name="hibernateTemplate")  
  27.     public HibernateTemplate  hibernateTemplate;  
  28.       
  29.     @Resource(name="sysUsersDaoImpl")  
  30.     public SysUsersDaoImpl userDao;  
  31.       
  32.     public SysUsersDaoImpl getUserDao() {  
  33.         return userDao;  
  34.     }  
  35.     public void setUserDao(SysUsersDaoImpl userDao) {  
  36.         this.userDao = userDao;  
  37.           
  38.     }  
  39.     public SysUsers queryUnique(String id){  
  40.         return hibernateTemplate.get(SysUsers.class, id);  
  41.     }  
  42.     public List<GrantedAuthority> loadUserAuthoritiesByName(String username) {  
  43.   
  44.         try {  
  45.   
  46.             List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();  
  47.             List<String> authorityNameList = loadUserAuthorities(username);  
  48.   
  49.             for (String authorityName : authorityNameList) {  
  50.                 //??  
  51.                 System.out.println(getClass().getName()+authorityName);  
  52.                 GrantedAuthorityImpl authority = new GrantedAuthorityImpl(authorityName);  
  53.                 auths.add(authority);  
  54.             }  
  55.   
  56.             return auths;  
  57.   
  58.         } catch (RuntimeException re) {  
  59.             throw re;  
  60.         }  
  61.     }  
  62.   
  63.     public List<String> loadUserAuthorities(final String username) {  
  64.         try {  
  65.   
  66.             List<String> authNameList = new ArrayList<String>();  
  67.             //根据用户名获得user  
  68.             SysUsers user = userDao.findByUserAccount(username);  
  69.             //根据user获得roles  
  70.             Set<SysUsersRoles> usersRoles =   user.getSysUsersRoleses();  
  71.             for(SysUsersRoles usersrole:usersRoles){  
  72.                 //更据roles获得authenority 获得auth_name  
  73.                 Set<SysRolesAuthorities>  rolesAuthorities = usersrole.getSysRoles().getSysRolesAuthorities();  
  74.                 for(SysRolesAuthorities roleAuthoritiy:rolesAuthorities){  
  75.                     String authName = roleAuthoritiy.getSysAuthorities().getAuthorityName();  
  76.                     authNameList.add(authName);  
  77.                 }             
  78.             }  
  79.             return authNameList;  
  80.         } catch (RuntimeException re) {  
  81.             System.out.println("find by authorities by username failed."  
  82.                     + re.getMessage());  
  83.             throw re;  
  84.         }  
  85.   
  86.     }  
  87.   
  88.   
  89.       
  90.       
  91. }  

2.4配置容器的xxx.xml文件

web.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.     <!-- 配置ioc容器路径 -->  
  8.     <context-param>  
  9.         <param-name>contextConfigLocation</param-name>  
  10.         <param-value>classpath:applicationContext*.xml</param-value>  
  11.     </context-param>  
  12.     <!-- 通过监听器加载ioc容器 -->  
  13.     <listener>  
  14.         <listener-class>  
  15.             org.springframework.web.context.ContextLoaderListener  
  16.         </listener-class>  
  17.     </listener>  
  18.       
  19.       
  20.     <!-- 通过过滤器加载struts2框架 -->  
  21.     <filter>  
  22.         <filter-name>struts2</filter-name>  
  23.         <filter-class>  
  24.             org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  
  25.         </filter-class>  
  26.     </filter>  
  27. <span style="color:#FF6666;"> <!-- Spring Secutiry-->  
  28.     <filter>  
  29.         <filter-name>springSecurityFilterChain</filter-name>  
  30.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  31.     </filter>  
  32.     </span>  
  33.     <filter-mapping>  
  34.         <filter-name>springSecurityFilterChain</filter-name>  
  35.         <url-pattern>/*</url-pattern>  
  36.     </filter-mapping>  
  37.       
  38.       
  39.     <!-- 解决Hibernate的延迟加载造成的Session提前关闭问题,设置该项使Session保持Request请求  
  40.                  完成才关闭Session。      -->  
  41.     <filter>  
  42.         <filter-name>opensession</filter-name>  
  43.         <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>  
  44.         <init-param>  
  45.             <param-name>singleSession</param-name>  
  46.             <param-value>true</param-value>  
  47.         </init-param>  
  48.     </filter>    
  49.   
  50.     <filter-mapping>  
  51.         <filter-name>opensession</filter-name>  
  52.         <url-pattern>/*</url-pattern>  
  53.     </filter-mapping>  
  54.       
  55.     <!-- 
  56.         使用Spring中的过滤器解决在请求和应答中的中文乱码问题(不是为了初始化每个jsp页面) 
  57.     -->  
  58.     <filter>  
  59.         <filter-name>characterEncodingFilter</filter-name>  
  60.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  61.         <init-param>  
  62.             <param-name>encoding</param-name>  
  63.             <param-value>gbk</param-value>  
  64.         </init-param>  
  65.         <init-param>  
  66.             <!--强制转换编码(request和response均适用) -->  
  67.             <param-name>ForceEncoding</param-name>  
  68.             <param-value>true</param-value>  
  69.         </init-param>  
  70.     </filter>  
  71.       
  72.       
  73.   
  74.     <filter-mapping>  
  75.         <filter-name>characterEncodingFilter</filter-name>  
  76.         <url-pattern>/*</url-pattern>  
  77.     </filter-mapping>  
  78.       
  79.       
  80.     <filter-mapping>  
  81.         <filter-name>struts2</filter-name>  
  82.         <url-pattern>/*</url-pattern>  
  83.     </filter-mapping>  
  84.       
  85.     <!-- 避免乱码问题 -->  
  86.     <filter>  
  87.         <filter-name>struts-cleanup</filter-name>  
  88.         <filter-class>  
  89.             org.apache.struts2.dispatcher.ActionContextCleanUp  
  90.         </filter-class>  
  91.     </filter>  
  92.       
  93.     <filter-mapping>  
  94.         <filter-name>struts-cleanup</filter-name>  
  95.         <url-pattern>/*</url-pattern>  
  96.     </filter-mapping>  
  97.       
  98.       
  99.   <welcome-file-list>  
  100.     <welcome-file>index.jsp</welcome-file>  
  101.   </welcome-file-list>  
  102. </web-app>  

applicationContext.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  8.            http://www.springframework.org/schema/context  
  9.            http://www.springframework.org/schema/context/spring-context-2.5.xsd  
  10.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">  
  11.     <!-- 通过注解完成对bean的管理 -->  
  12.     <context:component-scan base-package="org.joshua.ss" />  
  13. </beans>  


applicationContext_db.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"  
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  8.            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  9.            http://www.springframework.org/schema/context  
  10.            http://www.springframework.org/schema/context/spring-context-2.5.xsd  
  11.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  12.            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  13.     <!-- 加载属性文件 -->  
  14.     <bean  
  15.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  16.         <property name="locations">  
  17.             <value>classpath:dbConfig.properties</value>  
  18.         </property>  
  19.     </bean>  
  20.   
  21.     <!-- 配置数据源 -->  
  22.   
  23.     <bean id="dataSource"  
  24.         class="org.apache.commons.dbcp.BasicDataSource"  
  25.         destroy-method="close">  
  26.         <property name="driverClassName" value="${jdbc.driver}" />  
  27.         <property name="url" value="${jdbc.url}" />  
  28.         <property name="username" value="${jdbc.user}" />  
  29.         <property name="password" value="${jdbc.pwd}" />  
  30.     </bean>  
  31.     <!-- 创建session 工厂 -->  
  32.     <bean id="sessionFactory"  
  33.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  34.         <property name="dataSource" ref="dataSource" />  
  35.         <!-- 加载映射文件 -->  
  36.         <property name="mappingResources">  
  37.             <list>  
  38.                 <value>org/joshua/ss/res/SysAuthorities.hbm.xml</value>  
  39.                 <value>org/joshua/ss/res/SysAuthoritiesResources.hbm.xml</value>  
  40.                 <value>org/joshua/ss/res/SysResources.hbm.xml</value>  
  41.                 <value>org/joshua/ss/res/SysRoles.hbm.xml</value>  
  42.                 <value>org/joshua/ss/res/SysRolesAuthorities.hbm.xml</value>  
  43.                 <value>org/joshua/ss/res/SysUsers.hbm.xml</value>  
  44.                 <value>org/joshua/ss/res/SysUsersRoles.hbm.xml</value>  
  45.             </list>  
  46.         </property>  
  47.         <!-- 
  48.                 通过扫描包路径加载 
  49.         --><!--<property name="annotatedPackages">  
  50.             <list>  
  51.                 <value>org.joshua.ss.webapp.entity</value>  
  52.             </list>  
  53.         </property>  
  54.         --><!-- 配置session factory 的属性 -->  
  55.         <property name="hibernateProperties">  
  56.             <value>  
  57.                 hibernate.dialect=org.hibernate.dialect.OracleDialect  
  58.                 hibernate.show_sql=true  
  59.                 <!-- 启用二级缓存 -->  
  60.                 hibernate.cache.use_second_level_cache=true  
  61.                 hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider  
  62.             </value>  
  63.         </property>  
  64.     </bean>  
  65.   
  66.     <!-- 配置事务管理器 -->  
  67.     <bean id="txManager"  
  68.         class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  69.         <property name="sessionFactory" ref="sessionFactory" />  
  70.     </bean>  
  71.     <!-- 启用注解管理事务 -->  
  72.     <tx:annotation-driven transaction-manager="txManager" />  
  73.     <!-- 获取HibernateTemplate 对象 -->  
  74.     <bean id="hibernateTemplate"  
  75.         class="org.springframework.orm.hibernate3.HibernateTemplate">  
  76.         <property name="sessionFactory" ref="sessionFactory"></property>  
  77.     </bean>  
  78. </beans>  


applicationContext_security.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <b:beans xmlns="http://www.springframework.org/schema/security"  
  3.     xmlns:b="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  6.     http://www.springframework.org/schema/security   
  7.     http://www.springframework.org/schema/security/spring-security-3.0.xsd">  
  8.     <http auto-config="true" access-denied-page="/accessDenied.jsp">  
  9.         <!-- 不要过滤图片等静态资源  filters="none"-->  
  10.         <intercept-url pattern="/**/*.jpg" filters="none" />  
  11.         <intercept-url pattern="/**/*.png" filters="none" />  
  12.         <intercept-url pattern="/**/*.gif" filters="none" />  
  13.         <intercept-url pattern="/**/*.css" filters="none" />  
  14.         <intercept-url pattern="/**/*.js" filters="none" />  
  15.           
  16.         <!-- 登陆页和忘记密码或注册等不需要过滤的页面 -->  
  17.         <intercept-url pattern="/login.jsp" filters="none" />  
  18.         <intercept-url pattern="/jsp/forgotpassword.jsp"  
  19.             filters="none" />  
  20.   
  21.         <form-login login-page="/login.jsp"  
  22.             authentication-failure-url="/login.jsp?error=true"  
  23.             default-target-url="/index.jsp" />  
  24.           
  25.         <logout logout-success-url="/login.jsp" />  
  26.   
  27.         <!-- "记住我"功能,采用持久化策略(将用户的登录信息存放在数据库表中)需要创建一张persistent_logins 表   
  28.         <remember-me data-source-ref="dataSource" />  
  29.   
  30.         --><!-- 检测失效的sessionId,超时时定位到另外一个URL -->  
  31.         <session-management invalid-session-url="/sessionTimeout.jsp" />  
  32.   
  33.         <!-- 
  34.             增加一个自定义的filter,放在FILTER_SECURITY_INTERCEPTOR之前,实现用户、角色、权限、资源的数据库管理。 
  35.         -->  
  36.         <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR" />  
  37.     </http>  
  38.   
  39.     <!--  
  40.         一个自定义的filter  
  41.         必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性。  
  42.     -->  
  43.     <b:bean id="myFilter" class="org.joshua.ss.MyFilterSecurityInterceptor">  
  44.         <b:property name="authenticationManager" ref="authenticationManager" />  
  45.         <b:property name="accessDecisionManager" ref="myAccessDecisionManager" />  
  46.         <b:property name="securityMetadataSource" ref="mySecurityMetadataSource" />  
  47.     </b:bean>  
  48.   
  49.     <!-- 注意能够为authentication-manager 设置alias别名  -->  
  50.     <authentication-manager alias="authenticationManager">  
  51.         <authentication-provider user-service-ref="myUserDetailService"><!-- 
  52.              <password-encoder hash="md5" /> 
  53.         --></authentication-provider>  
  54.     </authentication-manager>  
  55.   
  56.     <b:bean id="myUserDetailService" class="org.joshua.ss.MyUserDetailService" />  
  57.   
  58.     <!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源。11/3/23 -->  
  59.     <b:bean id="myAccessDecisionManager"  
  60.         class="org.joshua.ss.MyAccessDecisionManager">  
  61.     </b:bean>    
  62.   
  63.     <!-- 资源源数据定义,将所有的资源和权限对应关系建立起来,即定义某一资源可以被哪些角色去访问。11/3/23 -->  
  64.     <b:bean id="mySecurityMetadataSource"  
  65.         class="org.joshua.ss.MyInvocationSecurityMetadataSource">  
  66.     </b:bean>   
  67.   
  68. </b:beans>  


dbConfig.properties
[plain] view plain copy
  1. jdbc.user=scott  
  2. jdbc.pwd=snail  
  3. jdbc.url=jdbc\:oracle\:thin\:@localhost\:1521\:oracle  
  4. jdbc.driver=oracle.jdbc.driver.OracleDriver  


ehcache.xml 没有深入的研究,暂且搁置
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <ehcache>  
  3.     <diskStore path="user.dir"></diskStore>  
  4.     <defaultCache   
  5.     maxElementsInMemory="10000"  
  6.     eternal="false"  
  7.     timeToIdleSeconds="120"  
  8.     timeToLiveSeconds="120"  
  9.     overflowToDisk="true" />  
  10. </ehcache>  


struts.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5. <struts>  
  6.     <!--  常量  -->  
  7.     <constant name="struts.il8n.encoding" value="UTF-8"/>  
  8.     <constant name="struts.enable.DynamicMethodInvocation" value="false"/>  
  9.     <constant name="struts.action.extension" value="do"/>  
  10.     <!-- 表示struts2中action 来自于spring的ioc容器 -->  
  11.     <constant name="struts.objectFactory" value="spring"/>  
  12.     <package name="user" namespace="" extends="struts-default">  
  13.         <action name="*" class="loginAction" method="{1}">  
  14.             <result name="success">/success.jsp</result>  
  15.             <result name="error">/error.jsp</result>  
  16.         </action>  
  17.     </package>  
  18. </struts>  

spring security 中最重要的核心

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

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



MyAccessDecisionManager.java

[java] view plain copy
  1. package org.joshua.ss;  
  2.   
  3. import java.util.Collection;  
  4. import java.util.Iterator;  
  5.   
  6. import org.springframework.security.access.AccessDecisionManager;  
  7. import org.springframework.security.access.AccessDeniedException;  
  8. import org.springframework.security.access.ConfigAttribute;  
  9. import org.springframework.security.access.SecurityConfig;  
  10. import org.springframework.security.authentication.InsufficientAuthenticationException;  
  11. import org.springframework.security.core.Authentication;  
  12. import org.springframework.security.core.GrantedAuthority;  
  13. /** 
  14.  *AccessdecisionManager在Spring security中是很重要的。 
  15.  * 
  16.  *在验证部分简略提过了,所有的Authentication实现需要保存在一个GrantedAuthority对象数组中。  
  17.  *这就是赋予给主体的权限。 GrantedAuthority对象通过AuthenticationManager 
  18.  *保存到 Authentication对象里,然后从AccessDecisionManager读出来,进行授权判断。  
  19.  * 
  20.  *Spring Security提供了一些拦截器,来控制对安全对象的访问权限,例如方法调用或web请求。  
  21.  *一个是否允许执行调用的预调用决定,是由AccessDecisionManager实现的。  
  22.  *这个 AccessDecisionManager 被AbstractSecurityInterceptor调用, 
  23.  *它用来作最终访问控制的决定。 这个AccessDecisionManager接口包含三个方法:  
  24.  * 
  25.  void decide(Authentication authentication, Object secureObject, 
  26.  List<ConfigAttributeDefinition> config) throws AccessDeniedException; 
  27.  boolean supports(ConfigAttribute attribute); 
  28.  boolean supports(Class clazz); 
  29.   
  30.   从第一个方法可以看出来,AccessDecisionManager使用方法参数传递所有信息,这好像在认证评估时进行决定。  
  31.   特别是,在真实的安全方法期望调用的时候,传递安全Object启用那些参数。  
  32.   比如,让我们假设安全对象是一个MethodInvocation。  
  33.   很容易为任何Customer参数查询MethodInvocation, 
  34.   然后在AccessDecisionManager里实现一些有序的安全逻辑,来确认主体是否允许在那个客户上操作。  
  35.   如果访问被拒绝,实现将抛出一个AccessDeniedException异常。 
  36.  
  37.   这个 supports(ConfigAttribute) 方法在启动的时候被 
  38.   AbstractSecurityInterceptor调用,来决定AccessDecisionManager 
  39.   是否可以执行传递ConfigAttribute。  
  40.   supports(Class)方法被安全拦截器实现调用, 
  41.   包含安全拦截器将显示的AccessDecisionManager支持安全对象的类型。 
  42.  * @author Joshua 
  43.  * 
  44.  */  
  45.   
  46. public class MyAccessDecisionManager implements AccessDecisionManager {  
  47.     // In this method, need to compare authentication with configAttributes.  
  48.     // 1, A object is a URL, a filter was find permission configuration by this  
  49.     // URL, and pass to here.  
  50.     // 2, Check authentication has attribute in permission configuration  
  51.     // (configAttributes)  
  52.     // 3, If not match corresponding authentication, throw a  
  53.     // AccessDeniedException.  
  54.   
  55.     public void decide(Authentication authentication, Object object,  
  56.             Collection<ConfigAttribute> configAttributes)  
  57.             throws AccessDeniedException, InsufficientAuthenticationException {  
  58.         if (configAttributes == null) {  
  59.             return;  
  60.         }  
  61.         // object is a URL.  
  62.         Iterator<ConfigAttribute> ite = configAttributes.iterator();  
  63.       
  64.         while (ite.hasNext()) {  
  65.             ConfigAttribute ca = ite.next();  
  66.             String needRole = ((SecurityConfig) ca).getAttribute();  
  67.               
  68.             //ga 为用户所被赋予的权限。 needRole 为访问相应的资源应该具有的权限。  
  69.             for (GrantedAuthority ga : authentication.getAuthorities()) {  
  70.                 if (needRole.trim().equals(ga.getAuthority().trim())) {   
  71.                     return;  
  72.                 }  
  73.             }  
  74.         }  
  75.         //  
  76.         throw new AccessDeniedException("no right!");  
  77.     }  
  78.   
  79.     public boolean supports(ConfigAttribute arg0) {  
  80.       
  81.         return true;  
  82.     }  
  83.   
  84.     public boolean supports(Class<?> clazz) {  
  85.       
  86.         return true;  
  87.     }  
  88.   
  89. }  


MyFilterSecurityInterceptor.java
[java] view plain copy
  1. package org.joshua.ss;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.Filter;  
  6. import javax.servlet.FilterChain;  
  7. import javax.servlet.FilterConfig;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.ServletRequest;  
  10. import javax.servlet.ServletResponse;  
  11.   
  12. import org.springframework.security.access.SecurityMetadataSource;  
  13. import org.springframework.security.access.intercept.AbstractSecurityInterceptor;  
  14. import org.springframework.security.access.intercept.InterceptorStatusToken;  
  15. import org.springframework.security.web.FilterInvocation;  
  16. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;  
  17.   
  18. /** 
  19.  * 该过滤器的主要作用就是通过spring的IoC生成securityMetadataSource。 
  20.  * securityMetadataSource相当于本包中自定义的MyInvocationSecurityMetadataSource。 
  21.  * 该MyInvocationSecurityMetadataSource的作用提从数据库提取权限和资源,装配到HashMap中, 供Spring 
  22.  * Security使用,用于权限校验。 
  23.  *  
  24.  * @author Joshua 
  25.  *  
  26.  */  
  27. public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor  
  28.         implements Filter {  
  29.     private FilterInvocationSecurityMetadataSource securityMetadataSource;  
  30.   
  31.     @Override  
  32.     public Class<? extends Object> getSecureObjectClass() {  
  33.         return FilterInvocation.class;  
  34.     }  
  35.   
  36.     public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {  
  37.         return securityMetadataSource;  
  38.     }  
  39.   
  40.     public void setSecurityMetadataSource(  
  41.             FilterInvocationSecurityMetadataSource securityMetadataSource) {  
  42.         this.securityMetadataSource = securityMetadataSource;  
  43.     }  
  44.   
  45.     @Override  
  46.     public SecurityMetadataSource obtainSecurityMetadataSource() {  
  47.         return this.securityMetadataSource;  
  48.     }  
  49.   
  50.     public void invoke(FilterInvocation fi) throws IOException,  
  51.             ServletException {  
  52.   
  53.         InterceptorStatusToken token = super.beforeInvocation(fi);  
  54.   
  55.         try {  
  56.             fi.getChain().doFilter(fi.getRequest(), fi.getResponse());  
  57.         } finally {  
  58.             super.afterInvocation(token, null);  
  59.         }  
  60.   
  61.     }  
  62.   
  63.     public void destroy() {  
  64.   
  65.     }  
  66.   
  67.     public void doFilter(ServletRequest request, ServletResponse response,  
  68.             FilterChain chain) throws IOException, ServletException {  
  69.         FilterInvocation fi = new FilterInvocation(request, response, chain);  
  70.         invoke(fi);  
  71.     }  
  72.   
  73.     public void init(FilterConfig arg0) throws ServletException {  
  74.   
  75.     }  
  76.   
  77. }  


MyInvocationSecurityMetadataSource.java
[java] view plain copy
  1. package org.joshua.ss;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collection;  
  5. import java.util.HashMap;  
  6. import java.util.Iterator;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9. import java.util.Set;  
  10.   
  11. import org.joshua.ss.entity.SysAuthorities;  
  12. import org.joshua.ss.entity.SysAuthoritiesResources;  
  13. import org.joshua.ss.service.AuthorityManager;  
  14. import org.springframework.context.ApplicationContext;  
  15. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  16. import org.springframework.security.access.ConfigAttribute;  
  17. import org.springframework.security.access.SecurityConfig;  
  18. import org.springframework.security.web.FilterInvocation;  
  19. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; //import org.springframework.security.web.access.intercept.RequestKey;  
  20. import org.springframework.security.web.util.AntUrlPathMatcher;  
  21. import org.springframework.security.web.util.UrlMatcher;  
  22.   
  23. /** 
  24.  * 最核心的地方,就是提供某个资源对应的权限定义,即getAttributes方法返回的结果。 此类在初始化时,应该取到所有资源及其对应角色的定义。 
  25.  *  
  26.  * @author Joshua 
  27.  *  
  28.  */  
  29. public class MyInvocationSecurityMetadataSource implements  
  30.         FilterInvocationSecurityMetadataSource {  
  31.   
  32.     private UrlMatcher urlMatcher = new AntUrlPathMatcher();  
  33.   
  34.     private static Map<String, Collection<ConfigAttribute>> resourceMap=null;  
  35.   
  36.     public MyInvocationSecurityMetadataSource() {  
  37.         loadResourceDefine();  
  38.     }  
  39.   
  40.     private void loadResourceDefine() {  
  41.   
  42.         resourceMap = new HashMap<String, Collection<ConfigAttribute>>();  
  43.         // Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();  
  44.         // 获取所有的authority_name的List  
  45.         ApplicationContext context = new ClassPathXmlApplicationContext(  
  46.                 new String[] { "applicationContext.xml",  
  47.                         "applicationContext_db.xml" });  
  48.         // 获取业务层对象  
  49.         AuthorityManager authorityManager = (AuthorityManager) context  
  50.                 .getBean("authorityManager");  
  51.         List<SysAuthorities> authoritiesList = new ArrayList<SysAuthorities>();  
  52.         authoritiesList = authorityManager.getAll();  
  53.         // 获得为authority_name 对应的 resource_string的 放入resourceMap  
  54.         for (SysAuthorities auth : authoritiesList) {  
  55.             ConfigAttribute ca = new SecurityConfig(auth.getAuthorityName());  
  56.   
  57.             Set<SysAuthoritiesResources> authoritiesResources = auth  
  58.                     .getSysAuthoritiesResourceses();  
  59.             for (SysAuthoritiesResources authorityResource : authoritiesResources) {  
  60.                 // resourceList.add(authorityResource.getSysResources());  
  61.                 String url = authorityResource.getSysResources()  
  62.                         .getResourceString();  
  63.                   
  64.                 if (resourceMap.containsKey(url)) {  
  65.                     Collection<ConfigAttribute> value = resourceMap.get(url);  
  66.                     value.add(ca);  
  67.                     resourceMap.put(url, value);  
  68.                 } else {  
  69.                     Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();  
  70.                     atts.add(ca);  
  71.                     resourceMap.put(url, atts);  
  72.                       
  73.                 }  
  74.   
  75.             }  
  76.         }  
  77.           
  78.     }  
  79.   
  80.     // According to a URL, Find out permission configuration of this URL.  
  81.     public Collection<ConfigAttribute> getAllConfigAttributes() {  
  82.   
  83.         return null;  
  84.     }  
  85.   
  86.     public Collection<ConfigAttribute> getAttributes(Object object)  
  87.             throws IllegalArgumentException {  
  88.         // object 是一个URL,被用户请求的url。  
  89.         String url = ((FilterInvocation) object).getRequestUrl();  
  90.         //??  
  91.         System.out.println(getClass().getName() + "~~~~~~~~~" + url);  
  92.   
  93.         int firstQuestionMarkIndex = url.indexOf("?");  
  94.   
  95.         if (firstQuestionMarkIndex != -1) {  
  96.             url = url.substring(0, firstQuestionMarkIndex);  
  97.         }  
  98.   
  99.         Iterator<String> ite = resourceMap.keySet().iterator();  
  100.         while (ite.hasNext()) {  
  101.             String resURL = ite.next();  
  102.             if (urlMatcher.pathMatchesUrl(url, resURL)) {  
  103.   
  104.                 return resourceMap.get(resURL);  
  105.   
  106.             }  
  107.   
  108.         }  
  109.   
  110.         return null;  
  111.     }  
  112.   
  113.     public boolean supports(Class<?> arg0) {  
  114.   
  115.         return true;  
  116.     }  
  117.   
  118. }  


MyUserDetails.java
[java] view plain copy
  1. package org.joshua.ss;  
  2.   
  3. import java.util.Set;  
  4.   
  5. import org.springframework.security.core.userdetails.UserDetails;  
  6.   
  7. /** 
  8.  *@author Joshua 
  9.  *@version 2011-12-27 上午11:14:46 
  10.  */  
  11. public interface MyUserDetails extends UserDetails{  
  12.     //用户id  
  13.     public String getUserId();  
  14.     //用户账户  
  15.     public String getUserAccount();  
  16.     //用户名  
  17.     public String getUserName();  
  18.     //用户密码  
  19.     public String getUserPassword();  
  20.     //用户描述或简介  
  21.     public String getUserDesc();  
  22.     //用户是否能用  
  23.     public boolean getEnabled();  
  24.     //是否超级用户  
  25.     public Boolean getIssys();    
  26.     //所属的单位  
  27.     public String getUserDept();  
  28.     //用户职位  
  29.     public String getUserDuty();  
  30.     //用户分管的子系统  
  31.     public String getSubSystem();     
  32.     //用户相对应的角色集  
  33.     public Set getSysUsersRoleses();  
  34. }  


MyUserDetailService.java
[java] view plain copy
  1. package org.joshua.ss;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collection;  
  5. import java.util.HashSet;  
  6.   
  7. import javax.annotation.Resource;  
  8.   
  9. import org.joshua.ss.entity.SysUsers;  
  10. import org.joshua.ss.service.UserManager;  
  11. import org.springframework.dao.DataAccessException;  
  12. import org.springframework.security.core.GrantedAuthority;  
  13. import org.springframework.security.core.userdetails.UserDetails;  
  14. import org.springframework.security.core.userdetails.UserDetailsService;  
  15. import org.springframework.security.core.userdetails.UsernameNotFoundException;  
  16.   
  17. public class MyUserDetailService implements UserDetailsService {  
  18.     @Resource(name = "userManager")  
  19.     private UserManager userManager;  
  20.   
  21.     public UserDetails loadUserByUsername(String username)  
  22.             throws UsernameNotFoundException, DataAccessException {  
  23.   
  24.         Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();  
  25.         if (null == userManager) {  
  26.             userManager = new UserManager();  
  27.         }  
  28.   
  29.         // 得到用户的权限  
  30.         auths = userManager.loadUserAuthoritiesByName(username);  
  31.         // 根据用户名取得一个SysUsers对象,以获取该用户的其他信息。  
  32.           
  33.         SysUsers user = userManager.userDao.findByUserAccount(username);  
  34.           
  35.         System.out.println("user.getUserId() "+user.getUserId()+" user.getUserName()"+user.getUserName()+" user.getUserPassword()"+user.getUserPassword());  
  36.   
  37.         return new SysUsers(  
  38.                 user.getUserId(),  
  39.                 user.getUserAccount(),   
  40.                 user.getUserName(),   
  41.                 user.getUserPassword(),   
  42.                 user.getUserDesc(),  
  43.                 user.getEnabled(),  
  44.                 user.getIssys(),   
  45.                 user.getUserDuty(),   
  46.                 user.getUserDept(),   
  47.                 user.getSubSystem(),   
  48.                 new HashSet(0),   
  49.                 true,   
  50.                 true,   
  51.                 true,  
  52.                 auths);  
  53.         /*return new User(username, user.getUserPassword(), true, true, true, true, auths); 
  54. */  
  55.     }  
  56.   
  57. }  

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

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

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


你可能感兴趣的:(java,DAO,spring,Security,user,null)