最近接触项目,发现项目用到了很多新鲜东西,也不能说是新鲜,只能说自己没有接触过,于是闲的无聊一项一项学习学习,别人问到也说上个七七八八。
今天可算是把spring-security搭建了出来并且运行了起来,主要是自己太菜,其实最后看来也就那么回事。
1.数据库的设计和搭建
用户 、角色、权限、资源以及关联表 用户--角色、角色--权限、权限--资源 总共七张表。
用户表
- create table SYS_USERS
- (
- USER_ID VARCHAR2(32) not null,
- USER_ACCOUNT VARCHAR2(30),
- USER_NAME VARCHAR2(40),
- USER_PASSWORD VARCHAR2(100),
- USER_DESC VARCHAR2(100),
- ENABLED NUMBER(1),
- ISSYS NUMBER(1),
- USER_DEPT VARCHAR2(20),
- USER_DUTY VARCHAR2(10),
- SUB_SYSTEM VARCHAR2(30)
- );
- alter table SYS_USERS add constraint PK_PUB_USERS primary key (USER_ID);
角色表
- create table SYS_ROLES
- (
- ROLE_ID VARCHAR2(32) not null,
- ROLE_NAME VARCHAR2(40),
- ROLE_DESC VARCHAR2(100),
- ENABLED NUMBER(1),
- ISSYS NUMBER(1),
- MODULE VARCHAR2(4)
- );
- alter table SYS_ROLES add constraint PK_PUB_ROLES primary key (ROLE_ID);
权限表
- create table SYS_AUTHORITIES
- (
- AUTHORITY_ID VARCHAR2(32) not null,
- AUTHORITY_NAME VARCHAR2(40),
- AUTHORITY_DESC VARCHAR2(100),
- ENABLED NUMBER(1),
- ISSYS NUMBER(1),
- MODULE VARCHAR2(4)
- );
- alter table SYS_AUTHORITIES add constraint PK_PUB_AUTHORITIES primary key (AUTHORITY_ID);
资源表
- create table SYS_RESOURCES
- (
- RESOURCE_ID VARCHAR2(32) not null,
- RESOURCE_NAME VARCHAR2(100),
- RESOURCE_DESC VARCHAR2(100),
- RESOURCE_TYPE VARCHAR2(40),
- RESOURCE_STRING VARCHAR2(200),
- PRIORITY NUMBER(1),
- ENABLED NUMBER(1),
- ISSYS NUMBER(1),
- MODULE VARCHAR2(4)
- );
- alter table SYS_RESOURCES add constraint PK_PUB_RESOURCES primary key (RESOURCE_ID);
用户角色表
- create table SYS_USERS_ROLES
- (
- ID NUMBER(13) not null,
- USER_ID VARCHAR2(32),
- ROLE_ID VARCHAR2(32),
- ENABLED NUMBER(1)
- );
-
- alter table SYS_USERS_ROLES add constraint PK_PUB_USERS_ROLES primary key (ID);
-
- alter table SYS_USERS_ROLES add constraint FK_USERS_ROLES_ROLES foreign key (ROLE_ID) references SYS_ROLES (ROLE_ID);
- alter table SYS_USERS_ROLES add constraint FK_USERS_ROLES_USERS foreign key (USER_ID) references SYS_USERS (USER_ID);
角色权限表
- create table SYS_ROLES_AUTHORITIES
- (
- ID NUMBER(13) not null,
- ROLE_ID VARCHAR2(32),
- AUTHORITY_ID VARCHAR2(32),
- ENABLED NUMBER(1)
- );
-
- alter table SYS_ROLES_AUTHORITIES add constraint PK_PUB_ROLES_AUTHORITY primary key (ID);
- alter table SYS_ROLES_AUTHORITIES add constraint FK_PUB_ROLES_AUTHORITIES_AU foreign key (AUTHORITY_ID) references SYS_AUTHORITIES (AUTHORITY_ID);
- alter table SYS_ROLES_AUTHORITIES add constraint FK_PUB_ROLES_AUTHORITIES_ROLES foreign key (ROLE_ID) references SYS_ROLES (ROLE_ID);
权限资源表
- create table SYS_AUTHORITIES_RESOURCES
- (
- ID NUMBER(13) not null,
- AUTHORITY_ID VARCHAR2(32),
- RESOURCE_ID VARCHAR2(32),
- ENABLED NUMBER(1)
- );
-
- alter table SYS_AUTHORITIES_RESOURCES add constraint PK_PUB_AUTHORITIES_RE primary key (ID);
-
- alter table SYS_AUTHORITIES_RESOURCES add constraint FK_PUB_AUTHORITIES_RE_AU foreign key (AUTHORITY_ID) references SYS_AUTHORITIES (AUTHORITY_ID);
- alter table SYS_AUTHORITIES_RESOURCES add constraint FK_PUB_AUTHORITIES_RE_RE foreign key (RESOURCE_ID) references SYS_RESOURCES (RESOURCE_ID);
加入关联的数据就可以了
2.web数据库整合
2.1jar包的导入 我所用到的几个jar包
- antlr-2.7.6.jar
- aopalliance.jar
- aspectjrt.jar
- aspectjweaver.jar
- backport-util-concurrent-3.1.jar
- c3p0-0.9.1.2.jar
- cglib-2.2.jar
- cglib-nodep-2.1_3.jar
- classes12.jar
- common-annotations.jar
- commons-collections-3.1.jar
- commons-dbcp-1.3.jar
- commons-fileupload-1.2.1.jar
- commons-io-1.3.2.jar
- commons-logging-1.0.4.jar
- commons-pool.jar
- dom4j-1.6.1.jar
- ehcache-1.5.0.jar
- freemarker-2.3.15.jar
- hibernate-commons-annotations-3.2.0.Final.jar
- hibernate-core-3.6.0.Final.jar
- hibernate-jpa-2.0-api-1.0.0.Final.jar
- hibernate3.jar
- javassist-3.9.0.GA.jar
- jta-1.1.jar
- mysql-connector-java-5.0.0-beta-bin.jar
- ognl-2.7.3.jar
- slf4j-api-1.6.1.jar
- slf4j-nop-1.6.1.jar
- spring-aop-3.0.4.RELEASE.jar
- spring-asm-3.0.4.RELEASE.jar
- spring-beans-3.0.4.RELEASE.jar
- spring-context-3.0.4.RELEASE.jar
- spring-context-support-3.0.4.RELEASE.jar
- spring-core-3.0.4.RELEASE.jar
- spring-expression-3.0.4.RELEASE.jar
- spring-jdbc-3.0.4.RELEASE.jar
- spring-orm-3.0.4.RELEASE.jar
- spring-security-acl-3.0.3.RELEASE.jar
- spring-security-config-3.0.3.RELEASE.jar
- spring-security-core-3.0.3.RELEASE.jar
- spring-security-taglibs-3.0.3.RELEASE.jar
- spring-security-web-3.0.3.RELEASE.jar
- spring-test-3.0.4.RELEASE.jar
- spring-tx-3.0.4.RELEASE.jar
- spring-web-3.0.4.RELEASE.jar
- spring-webmvc-3.0.4.RELEASE.jar
- spring-webmvc-struts.jar
- struts2-core-2.1.8.1.jar
- struts2-spring-plugin-2.1.8.1.jar
- xwork-core-2.1.6.jar
2.2创建实体类entity和映射文件xxx.hbm.xml(使用hibernate注解可以省略,下一阶段研究)
SysAuthorities.java
SysAuthoritiesResources.java
- package org.joshua.ss.entity;
-
- import java.io.Serializable;
-
-
-
-
-
-
- public class SysAuthoritiesResources implements Serializable {
-
-
-
-
-
- private static final long serialVersionUID = -2373269722400659636L;
- private long id;
- private SysAuthorities sysAuthorities;
- private SysResources sysResources;
- private Boolean enabled;
-
- public SysAuthoritiesResources() {
- }
-
- public SysAuthoritiesResources(long id) {
- this.id = id;
- }
-
- public SysAuthoritiesResources(long id, SysAuthorities sysAuthorities,
- SysResources sysResources, Boolean enabled) {
- this.id = id;
- this.sysAuthorities = sysAuthorities;
- this.sysResources = sysResources;
- this.enabled = enabled;
- }
-
- public long getId() {
- return this.id;
- }
-
- public void setId(long id) {
- this.id = id;
- }
-
- public SysAuthorities getSysAuthorities() {
- return this.sysAuthorities;
- }
-
- public void setSysAuthorities(SysAuthorities sysAuthorities) {
- this.sysAuthorities = sysAuthorities;
- }
-
- public SysResources getSysResources() {
- return this.sysResources;
- }
-
- public void setSysResources(SysResources sysResources) {
- this.sysResources = sysResources;
- }
-
- public Boolean getEnabled() {
- return this.enabled;
- }
-
- public void setEnabled(Boolean enabled) {
- this.enabled = enabled;
- }
-
- }
SysResources.java
SysRoles.java
- package org.joshua.ss.entity;
-
- import java.io.Serializable;
- import java.util.Set;
-
- import org.joshua.ss.dao.daoimpl.BaseDaoImpl;
-
-
- public class SysRoles implements Serializable {
-
-
-
-
-
- private static final long serialVersionUID = -243340671938105177L;
- private String roleId;
- private String roleName;
- private String roleDesc;
- private Boolean enabled;
- private Boolean issys;
-
-
- private String module;
-
- private Set<SysUsersRoles> sysUsersRoles;
- private Set<SysRolesAuthorities> sysRolesAuthorities;
-
- public SysRoles() {
- }
-
- public SysRoles(String roleId) {
- this.roleId = roleId;
- }
-
- public SysRoles(String roleId, String roleName, String roleDesc) {
- this.roleId = roleId;
- this.roleName = roleName;
- this.roleDesc = roleDesc;
- }
-
- public SysRoles(String roleId, String roleName, String roleDesc,
- Boolean enabled, Boolean issys, String module) {
- this.roleId = roleId;
- this.roleName = roleName;
- this.roleDesc = roleDesc;
- this.enabled = enabled;
- this.issys = issys;
- this.module = module;
- }
-
- public SysRoles(String roleId, String roleName, String roleDesc,
- Boolean enabled, Boolean issys, String module, Set<SysUsersRoles> sysUsersRoles,
- Set<SysRolesAuthorities> sysRolesAuthorities) {
- this.roleId = roleId;
- this.roleName = roleName;
- this.roleDesc = roleDesc;
- this.enabled = enabled;
- this.issys = issys;
- this.module = module;
- this.sysUsersRoles = sysUsersRoles;
- this.sysRolesAuthorities = sysRolesAuthorities;
- }
-
- public String getRoleId() {
- return this.roleId;
- }
-
- public void setRoleId(String roleId) {
- this.roleId = roleId;
- }
-
- public String getRoleName() {
- return this.roleName;
- }
-
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
-
- public String getRoleDesc() {
- return this.roleDesc;
- }
-
- public void setRoleDesc(String roleDesc) {
- this.roleDesc = roleDesc;
- }
-
- public Boolean getEnabled() {
- return this.enabled;
- }
-
- public void setEnabled(Boolean enabled) {
- this.enabled = enabled;
- }
-
- public Boolean getIssys() {
- return this.issys;
- }
-
- public void setIssys(Boolean issys) {
- this.issys = issys;
- }
-
-
- public String getModule() {
- return this.module;
- }
-
- public void setModule(String module) {
- this.module = module;
- }
-
- public Set<SysUsersRoles> getSysUsersRoles() {
- return this.sysUsersRoles;
- }
-
- public void setSysUsersRoles(Set<SysUsersRoles> sysUsersRoles) {
- this.sysUsersRoles = sysUsersRoles;
- }
-
- public Set<SysRolesAuthorities> getSysRolesAuthorities() {
- return this.sysRolesAuthorities;
- }
-
- public void setSysRolesAuthorities(Set<SysRolesAuthorities> sysRolesAuthorities) {
- this.sysRolesAuthorities = sysRolesAuthorities;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((enabled == null) ? 0 : enabled.hashCode());
- result = prime * result + ((issys == null) ? 0 : issys.hashCode());
- result = prime * result + ((module == null) ? 0 : module.hashCode());
- result = prime * result
- + ((roleDesc == null) ? 0 : roleDesc.hashCode());
- result = prime * result + ((roleId == null) ? 0 : roleId.hashCode());
- result = prime * result
- + ((roleName == null) ? 0 : roleName.hashCode());
- result = prime
- * result
- + ((sysRolesAuthorities == null) ? 0 : sysRolesAuthorities
- .hashCode());
- result = prime * result
- + ((sysUsersRoles == null) ? 0 : sysUsersRoles.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- SysRoles other = (SysRoles) obj;
- if (enabled == null) {
- if (other.enabled != null)
- return false;
- } else if (!enabled.equals(other.enabled))
- return false;
- if (issys == null) {
- if (other.issys != null)
- return false;
- } else if (!issys.equals(other.issys))
- return false;
- if (module == null) {
- if (other.module != null)
- return false;
- } else if (!module.equals(other.module))
- return false;
- if (roleDesc == null) {
- if (other.roleDesc != null)
- return false;
- } else if (!roleDesc.equals(other.roleDesc))
- return false;
- if (roleId == null) {
- if (other.roleId != null)
- return false;
- } else if (!roleId.equals(other.roleId))
- return false;
- if (roleName == null) {
- if (other.roleName != null)
- return false;
- } else if (!roleName.equals(other.roleName))
- return false;
- if (sysRolesAuthorities == null) {
- if (other.sysRolesAuthorities != null)
- return false;
- } else if (!sysRolesAuthorities.equals(other.sysRolesAuthorities))
- return false;
- if (sysUsersRoles == null) {
- if (other.sysUsersRoles != null)
- return false;
- } else if (!sysUsersRoles.equals(other.sysUsersRoles))
- return false;
- return true;
- }
-
- }
SysRolesAuthorities.java
- package org.joshua.ss.entity;
-
- import java.io.Serializable;
-
-
- public class SysRolesAuthorities implements Serializable {
-
-
-
-
- private static final long serialVersionUID = -4270137978962070889L;
- private long id;
- private SysAuthorities sysAuthorities;
- private SysRoles sysRoles;
- private Boolean enabled;
-
- public SysRolesAuthorities() {
- }
-
- public SysRolesAuthorities(long id) {
- this.id = id;
- }
-
- public SysRolesAuthorities(long id, SysAuthorities sysAuthorities,
- SysRoles sysRoles, Boolean enabled) {
- this.id = id;
- this.sysAuthorities = sysAuthorities;
- this.sysRoles = sysRoles;
- this.enabled = enabled;
- }
-
- public long getId() {
- return this.id;
- }
-
- public void setId(long id) {
- this.id = id;
- }
-
- public SysAuthorities getSysAuthorities() {
- return this.sysAuthorities;
- }
-
- public void setSysAuthorities(SysAuthorities sysAuthorities) {
- this.sysAuthorities = sysAuthorities;
- }
-
- public SysRoles getSysRoles() {
- return this.sysRoles;
- }
-
- public void setSysRoles(SysRoles sysRoles) {
- this.sysRoles = sysRoles;
- }
-
- public Boolean getEnabled() {
- return this.enabled;
- }
-
- public void setEnabled(Boolean enabled) {
- this.enabled = enabled;
- }
-
- }
SysUsers.java
- package org.joshua.ss.entity;
-
- import java.io.Serializable;
- import java.util.Collection;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.HashSet;
- import java.util.Set;
- import java.util.SortedSet;
- import java.util.TreeSet;
-
- import org.joshua.ss.MyUserDetails;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.util.Assert;
-
-
-
-
-
-
-
-
- public class SysUsers implements MyUserDetails,Serializable {
-
-
-
-
- private static final long serialVersionUID = -8680337263599302062L;
-
-
- private String userId;
-
-
- private String userAccount;
-
-
- private String userName;
-
-
- private String userPassword;
-
-
- private String userDesc;
-
-
- private Boolean enabled;
-
-
- private Boolean issys;
-
-
- private String userDept;
-
-
- private String userDuty;
-
-
- private String subSystem;
-
-
- private Set<SysUsersRoles> sysUsersRoleses =new HashSet(0);
-
-
-
-
-
-
-
-
-
- private String password;
- private String username;
- private Set<GrantedAuthority> authorities;
- private boolean accountNonExpired;
- private boolean accountNonLocked;
- private boolean credentialsNonExpired;
-
- public SysUsers(){
-
- }
-
- public SysUsers(String userId, String userAccount, String userName,
- String userPassword, String userDesc, Boolean enabled,
- Boolean issys, String userDept, String userDuty, String subSystem,
- Set<SysUsersRoles> sysUsersRoleses,boolean accountNonExpired, boolean accountNonLocked,
- boolean credentialsNonExpired,Collection<GrantedAuthority> authorities) {
-
- if (((userAccount == null) || "".equals(userAccount)) || (userPassword == null)) {
- throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
- }
-
- this.userId = userId;
- this.userAccount = userAccount;
- this.userName = userName;
- this.userPassword = userPassword;
- this.userDesc = userDesc;
- this.enabled = enabled;
- this.issys = issys;
- this.userDept = userDept;
- this.userDuty = userDuty;
- this.subSystem = subSystem;
- this.sysUsersRoleses = sysUsersRoleses;
- this.password = userPassword;
- this.username = userAccount;
- this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));
- this.accountNonExpired = accountNonExpired;
- this.accountNonLocked = accountNonLocked;
- this.credentialsNonExpired = credentialsNonExpired;
- }
-
-
-
-
- public boolean equals(Object rhs) {
- if (!(rhs instanceof SysUsers) || (rhs == null)) {
- return false;
- }
-
- SysUsers user = (SysUsers) rhs;
-
-
- if (!authorities.equals(user.authorities)) {
- return false;
- }
-
-
- return (this.getPassword().equals(user.getPassword()) && this.getUsername().equals(user.getUsername())
- && (this.isAccountNonExpired() == user.isAccountNonExpired())
- && (this.isAccountNonLocked() == user.isAccountNonLocked())
- && (this.isCredentialsNonExpired() == user.isCredentialsNonExpired())
- && (this.isEnabled() == user.isEnabled()));
- }
-
- public String getUserId() {
- return this.userId;
- }
-
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
- public String getUserAccount() {
- return this.userAccount;
- }
-
- public void setUserAccount(String userAccount) {
- this.userAccount = userAccount;
- }
-
- public String getUserName() {
- return this.userName;
- }
-
- public void setUserName(String userName) {
- this.userName = userName;
- }
-
- public String getUserPassword() {
- return this.userPassword;
- }
-
- public void setUserPassword(String userPassword) {
- this.userPassword = userPassword;
- }
-
- public String getUserDesc() {
- return this.userDesc;
- }
-
- public void setUserDesc(String userDesc) {
- this.userDesc = userDesc;
- }
-
- public boolean getEnabled() {
- return this.enabled;
- }
-
- public void setEnabled(Boolean enabled) {
- this.enabled = enabled;
- }
-
- public Boolean getIssys() {
- return this.issys;
- }
-
- public void setIssys(Boolean issys) {
- this.issys = issys;
- }
-
- public String getUserDept() {
- return this.userDept;
- }
-
- public void setUserDept(String userDept) {
- this.userDept = userDept;
- }
-
- public String getUserDuty() {
- return this.userDuty;
- }
-
- public void setUserDuty(String userDuty) {
- this.userDuty = userDuty;
- }
-
- public String getSubSystem() {
- return this.subSystem;
- }
-
- public void setSubSystem(String subSystem) {
- this.subSystem = subSystem;
- }
-
- public Set<SysUsersRoles> getSysUsersRoleses() {
- return this.sysUsersRoleses;
- }
-
- public void setSysUsersRoleses(Set<SysUsersRoles> sysUsersRoleses) {
- this.sysUsersRoleses = sysUsersRoleses;
- }
-
-
- public String getPassword() {
- return password;
- }
-
-
- public String getUsername() {
- return username;
- }
-
-
- public Set<GrantedAuthority> getAuthorities() {
- return authorities;
- }
-
-
- public void setAuthorities(Set<GrantedAuthority> authorities) {
- this.authorities = authorities;
- }
-
-
- public boolean isAccountNonExpired() {
- return accountNonExpired;
- }
-
- public boolean isAccountNonLocked() {
- return accountNonLocked;
- }
-
-
- public boolean isCredentialsNonExpired() {
- return credentialsNonExpired;
- }
-
- public boolean isEnabled() {
- return enabled;
- }
-
-
- public int hashCode() {
- int code = 9792;
-
-
- if (null != getUsername() && null != getAuthorities()) {
- for (GrantedAuthority authority : getAuthorities()) {
-
- code = code * (authority.hashCode() % 7);
- }
- }
-
- if (this.getPassword() != null) {
- code = code * (this.getPassword().hashCode() % 7);
- }
-
- if (this.getUsername() != null) {
- code = code * (this.getUsername().hashCode() % 7);
- }
-
- if (this.isAccountNonExpired()) {
- code = code * -2;
- }
-
- if (this.isAccountNonLocked()) {
- code = code * -3;
- }
-
- if (this.isCredentialsNonExpired()) {
- code = code * -5;
- }
-
- if (this.isEnabled()) {
- code = code * -7;
- }
-
- return code;
- }
-
-
- private static SortedSet<GrantedAuthority> sortAuthorities(Collection<GrantedAuthority> authorities) {
- Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");
-
- SortedSet<GrantedAuthority> sortedAuthorities =
- new TreeSet<GrantedAuthority>(new AuthorityComparator());
-
- for (GrantedAuthority grantedAuthority : authorities) {
- Assert.notNull(grantedAuthority, "GrantedAuthority list cannot contain any null elements");
- sortedAuthorities.add(grantedAuthority);
- }
-
- return sortedAuthorities;
- }
-
- private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable {
- public int compare(GrantedAuthority g1, GrantedAuthority g2) {
-
-
- if (g2.getAuthority() == null) {
- return -1;
- }
-
- if (g1.getAuthority() == null) {
- return 1;
- }
- return g1.getAuthority().compareTo(g2.getAuthority());
- }
- }
-
-
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append(super.toString()).append(": ");
- sb.append("Username: ").append(this.username).append("; ");
- sb.append("" +
- "" +
- ": [PROTECTED]; ");
- sb.append("UserAccount: ").append(this.userAccount).append("; ");
- sb.append("UserDept: ").append(this.userDept).append("; ");
- sb.append("UserDuty: ").append(this.userDuty).append("; ");
- sb.append("UserDesc: ").append(this.userDesc).append("; ");
- sb.append("UserSubSystem: ").append(this.subSystem).append("; ");
- sb.append("UserIsSys: ").append(this.issys).append("; ");
- sb.append("Enabled: ").append(this.enabled).append("; ");
- sb.append("AccountNonExpired: ").append(this.accountNonExpired).append("; ");
- sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired).append("; ");
- sb.append("AccountNonLocked: ").append(this.accountNonLocked).append("; ");
-
- if ( null !=authorities && !authorities.isEmpty()) {
- sb.append("Granted Authorities: ");
-
- boolean first = true;
- for (GrantedAuthority auth : authorities) {
- if (!first) {
- sb.append(",");
- }
- first = false;
-
- sb.append(auth);
- }
- } else {
- sb.append("Not granted any authorities");
- }
-
- return sb.toString();
- }
-
- }
SysUsersRoles.java
- package org.joshua.ss.entity;
-
- import java.io.Serializable;
-
- public class SysUsersRoles implements Serializable {
-
-
-
-
- private static final long serialVersionUID = 393623940722220854L;
- private long id;
- private SysUsers pubUsers;
- private SysRoles pubRoles;
- private Boolean enabled;
-
- public SysUsersRoles() {
- }
-
- public SysUsersRoles(long id) {
- this.id = id;
- }
-
- public SysUsersRoles(long id, SysUsers pubUsers, SysRoles pubRoles,
- Boolean enabled) {
- this.id = id;
- this.pubUsers = pubUsers;
- this.pubRoles = pubRoles;
- this.enabled = enabled;
- }
-
- public long getId() {
- return this.id;
- }
-
- public void setId(long id) {
- this.id = id;
- }
-
- public SysUsers getSysUsers() {
- return this.pubUsers;
- }
-
- public void setSysUsers(SysUsers pubUsers) {
- this.pubUsers = pubUsers;
- }
-
- public SysRoles getSysRoles() {
- return this.pubRoles;
- }
-
- public void setSysRoles(SysRoles pubRoles) {
- this.pubRoles = pubRoles;
- }
-
- public Boolean getEnabled() {
- return this.enabled;
- }
-
- public void setEnabled(Boolean enabled) {
- this.enabled = enabled;
- }
-
- }
2.2.2对应的映射文件xxx.hbm.xml
SysAuthorities.hbm.xml
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
-
- <hibernate-mapping>
- <class name="org.joshua.ss.entity.SysAuthorities" table="SYS_AUTHORITIES">
- <id name="authorityId" type="string">
- <column name="AUTHORITY_ID" length="32" />
- <generator class="assigned" />
- </id>
- <property name="authorityName" type="string">
- <column name="AUTHORITY_NAME" length="40" />
- </property>
- <property name="authorityDesc" type="string">
- <column name="AUTHORITY_DESC" length="100" />
- </property>
- <property name="enabled" type="java.lang.Boolean">
- <column name="ENABLED" precision="1" scale="0" />
- </property>
- <property name="issys" type="java.lang.Boolean">
- <column name="ISSYS" precision="1" scale="0" />
- </property>
- <property name="module" type="string">
- <column name="MODULE" length="4" />
- </property>
- <set name="sysRolesAuthoritieses" inverse="true" cascade="all" lazy="false">
- <key>
- <column name="AUTHORITY_ID" length="32" />
- </key>
- <one-to-many class="org.joshua.ss.entity.SysRolesAuthorities" />
- </set>
- <set name="sysAuthoritiesResourceses" inverse="true" cascade="all" lazy="false">
- <key>
- <column name="AUTHORITY_ID" length="32" />
- </key>
- <one-to-many class="org.joshua.ss.entity.SysAuthoritiesResources" />
- </set>
- </class>
- </hibernate-mapping>
SysAuthoritiesResources.hbm.xml
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class name="org.joshua.ss.entity.SysAuthoritiesResources" table="SYS_AUTHORITIES_RESOURCES">
- <id name="id" type="long">
- <column name="ID" precision="13" scale="0" />
- <generator class="assigned" />
- </id>
- <many-to-one name="sysAuthorities" class="org.joshua.ss.entity.SysAuthorities" fetch="select" lazy="false">
- <column name="AUTHORITY_ID" length="32" />
- </many-to-one>
- <many-to-one name="sysResources" class="org.joshua.ss.entity.SysResources" fetch="select" lazy="false">
- <column name="RESOURCE_ID" length="32" />
- </many-to-one>
- <property name="enabled" type="java.lang.Boolean">
- <column name="ENABLED" precision="1" scale="0" />
- </property>
- </class>
- </hibernate-mapping>
SysResources.hbm.xml
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class name="org.joshua.ss.entity.SysResources" table="Sys_RESOURCES">
- <id name="resourceId" type="string">
- <column name="RESOURCE_ID" length="32" />
- <generator class="assigned" />
- </id>
- <property name="resourceName" type="string">
- <column name="RESOURCE_NAME" length="100" />
- </property>
- <property name="resourceDesc" type="string">
- <column name="RESOURCE_DESC" length="100" />
- </property>
- <property name="resourceType" type="string">
- <column name="RESOURCE_TYPE" length="40" />
- </property>
- <property name="resourceString" type="string">
- <column name="RESOURCE_STRING" length="200" />
- </property>
- <property name="priority" type="java.lang.Boolean">
- <column name="PRIORITY" precision="1" scale="0" />
- </property>
- <property name="enabled" type="java.lang.Integer">
- <column name="ENABLED" precision="1" scale="0" />
- </property>
- <property name="issys" type="java.lang.Integer">
- <column name="ISSYS" precision="1" scale="0" />
- </property>
- <property name="module" type="string">
- <column name="MODULE" length="4" />
- </property>
- <set name="sysAuthoritiesResourceses" inverse="true" lazy="false">
- <key>
- <column name="RESOURCE_ID" length="32" />
- </key>
- <one-to-many class="org.joshua.ss.entity.SysAuthoritiesResources" />
- </set>
- </class>
- </hibernate-mapping>
SysRoles.hbm.xml
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class name="org.joshua.ss.entity.SysRoles" table="SYS_ROLES">
- <id name="roleId" type="string">
- <column name="ROLE_ID" length="32" />
- <generator class="assigned" />
- </id>
- <property name="roleName" type="string">
- <column name="ROLE_NAME" length="40" />
- </property>
- <property name="roleDesc" type="string">
- <column name="ROLE_DESC" length="100" />
- </property>
- <property name="enabled" type="java.lang.Boolean">
- <column name="ENABLED" precision="1" scale="0" />
- </property>
- <property name="issys" type="java.lang.Boolean">
- <column name="ISSYS" precision="1" scale="0" />
- </property>
- <property name="module" type="string">
- <column name="MODULE" length="4" />
- </property>
- <set name="sysUsersRoles" inverse="true" cascade="all" lazy="false">
- <key>
- <column name="ROLE_ID" length="32" />
- </key>
- <one-to-many class="org.joshua.ss.entity.SysUsersRoles"/>
- </set>
- <set name="sysRolesAuthorities" inverse="true" cascade="all" lazy="false">
- <key>
- <column name="ROLE_ID" length="32" />
- </key>
- <one-to-many class="org.joshua.ss.entity.SysRolesAuthorities" />
- </set>
- </class>
- </hibernate-mapping>
SysRolesAuthorities.hbm.xml
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
-
- <hibernate-mapping>
- <class name="org.joshua.ss.entity.SysRolesAuthorities" table="SYS_ROLES_AUTHORITIES">
- <id name="id" type="long">
- <column name="ID" precision="13" scale="0" />
- <generator class="assigned" />
- </id>
- <many-to-one name="sysAuthorities" class="org.joshua.ss.entity.SysAuthorities" fetch="select" lazy="false">
- <column name="AUTHORITY_ID" length="32" />
- </many-to-one>
- <many-to-one name="sysRoles" class="org.joshua.ss.entity.SysRoles" fetch="select" lazy="false">
- <column name="ROLE_ID" length="32" />
- </many-to-one>
- <!--
- <property name="authorityId" type="string">
- <column name="AUTHORITY_ID" length="32" />
- </property>
- <property name="roleId" type="string">
- <column name="ROLE_ID" length="32" />
- </property> -->
- <property name="enabled" type="java.lang.Boolean">
- <column name="ENABLED" precision="1" scale="0" />
- </property>
- </class>
- </hibernate-mapping>
SysUsers.hbm.xml
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class name="org.joshua.ss.entity.SysUsers" table="SYS_USERS">
- <id name="userId" type="string">
- <column name="USER_ID" length="32" />
- <generator class="assigned" />
- </id>
- <property name="userAccount" type="string">
- <column name="USER_ACCOUNT" length="30" />
- </property>
- <property name="userName" type="string">
- <column name="USER_NAME" length="40" />
- </property>
- <property name="userPassword" type="string">
- <column name="USER_PASSWORD" length="100" />
- </property>
- <property name="userDesc" type="string">
- <column name="USER_DESC" length="100" />
- </property>
- <property name="userDuty" type="string">
- <column name="USER_DUTY" length="10" />
- </property>
- <property name="userDept" type="string">
- <column name="USER_DEPT" length="20" />
- </property>
- <property name="subSystem" type="string">
- <column name="SUB_SYSTEM" length="30" />
- </property>
- <property name="enabled" type="java.lang.Boolean">
- <column name="ENABLED" precision="1" scale="0" />
- </property>
- <property name="issys" type="java.lang.Boolean">
- <column name="ISSYS" precision="1" scale="0" />
- </property>
- <set name="sysUsersRoleses" inverse="true" cascade="all" lazy="false">
- <key>
- <column name="USER_ID" length="32" />
- </key>
- <one-to-many class="org.joshua.ss.entity.SysUsersRoles" />
- </set>
- </class>
- </hibernate-mapping>
SysUsersRoles.hbm.xml
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class name="org.joshua.ss.entity.SysUsersRoles" table="SYS_USERS_ROLES">
- <id name="id" type="long">
- <column name="ID" precision="13" scale="0" />
- <generator class="assigned" />
- </id>
- <many-to-one name="sysUsers" class="org.joshua.ss.entity.SysUsers" fetch="select" lazy="false">
- <column name="USER_ID" length="32" />
- </many-to-one>
- <many-to-one name="sysRoles" class="org.joshua.ss.entity.SysRoles" fetch="select" lazy="false">
- <column name="ROLE_ID" length="32" />
- </many-to-one>
- <property name="enabled" type="java.lang.Boolean">
- <column name="ENABLED" precision="1" scale="0" />
- </property>
- </class>
- </hibernate-mapping>
2.3DAO层和service层的创建
最近看到通用dao,模仿着写了一个在这里
BaseDao.java
- package org.joshua.ss.dao;
-
- import java.io.Serializable;
- import java.util.List;
-
-
-
-
-
-
-
-
-
-
- public interface BaseDao<T,PK extends Serializable> {
-
-
-
-
-
-
- T getById(PK id);
-
-
-
-
-
- T save(T object);
-
-
-
-
- void remove(PK id);
-
-
-
-
- void remove(final T object);
-
-
-
-
- List<T> getAll();
-
-
- }
SysAuthoritiesDao.java接口下同
package org.joshua.ss.dao;
/**
*@author Joshua
*@version 2011-12-15 上午11:06:22
*/
public interface SysAuthoritiesDao{
}
SysAuthoritiesResourcesDao.java
SysResourcesDao.java
SysRolesAuthoritiesDao.java
SysRolesDao.java
SysUsersDao.java
SysUsersRolesDao.java
dao层接口的实现类
BaseDaoImpl.java
- package org.joshua.ss.dao.daoimpl;
-
- import java.io.Serializable;
- import java.lang.reflect.ParameterizedType;
- import java.lang.reflect.Type;
- import java.util.List;
-
- import javax.annotation.Resource;
-
- import org.joshua.ss.dao.BaseDao;
- import org.springframework.orm.hibernate3.HibernateTemplate;
- import org.springframework.util.Assert;
-
-
-
-
-
-
-
-
- public class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK>{
-
- @Resource(name="hibernateTemplate")
- private HibernateTemplate hibernateTemplate;
-
- private Class<T> persistentClass;
-
-
-
-
- @SuppressWarnings("unchecked")
- public BaseDaoImpl(){
-
- this.persistentClass=(Class<T>)getSuperClassGenricType(getClass(), 0);
- }
- public List<T> getAll() {
- return hibernateTemplate.loadAll(this.persistentClass);
- }
-
- public T getById(PK id) {
- Assert.notNull(id, "id 不可空");
- T entity =hibernateTemplate.get(this.persistentClass, id);
- return entity;
- }
-
- public void remove(PK id) {
- Assert.notNull(id, "id 不可空!");
- hibernateTemplate.delete(this.getById(id));
- }
-
- public void remove(final T entity) {
- Assert.notNull(entity, "entity 不可空!");
- hibernateTemplate.delete(entity);
- }
-
- public T save(T entity) {
- Assert.notNull(entity, "entity 不可空!");
- return hibernateTemplate.merge(entity);
- }
-
-
-
-
-
-
-
-
-
-
- @SuppressWarnings("unchecked")
- public static Class<Object> getSuperClassGenricType(final Class clazz, final int index) {
-
-
- Type genType = clazz.getGenericSuperclass();
-
- if (!(genType instanceof ParameterizedType)) {
- return Object.class;
- }
-
- Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
-
- if (index >= params.length || index < 0) {
- return Object.class;
- }
- if (!(params[index] instanceof Class)) {
- return Object.class;
- }
-
- return (Class) params[index];
- }
-
- }
SysAuthoritiesDaoImpl.java
- package org.joshua.ss.dao.daoimpl;
-
- import org.joshua.ss.dao.SysAuthoritiesDao;
- import org.joshua.ss.entity.SysAuthorities;
-
-
-
-
-
- public class SysAuthoritiesDaoImpl extends BaseDaoImpl<SysAuthorities, Long> implements SysAuthoritiesDao {
-
- }
下同,继承通用dao传递实体类型,也可自定义方法
SysAuthoritiesResourcesDaoImpl.java
SysResourcesDaoImpl.java
SysRolesAuthoritiesDaoImpl.java
SysRolesDaoImpl.java
SysUsersDaoImpl.java
- package org.joshua.ss.dao.daoimpl;
-
-
-
- import java.util.List;
-
- import javax.annotation.Resource;
-
- import org.joshua.ss.dao.SysUsersDao;
-
-
- import org.joshua.ss.entity.SysUsers;
- import org.springframework.orm.hibernate3.HibernateTemplate;
- import org.springframework.stereotype.Service;
-
-
-
-
-
- @Service("sysUsersDaoImpl")
- public class SysUsersDaoImpl extends BaseDaoImpl<SysUsersDao, Long> implements
- SysUsersDao {
- @Resource(name="hibernateTemplate")
- private HibernateTemplate hibernateTemplate;
-
-
- public SysUsers findByUserAccount(String userName) {
- try {
- SysUsers instance;
- List<SysUsers> instances = hibernateTemplate.find(
- "from SysUsers where userAccount='" + userName+"'");
- if ( null ==instances||instances.isEmpty()) {
- System.out.println("没有相匹配的SysUsers实例对象!");
- instance = new SysUsers();
- } else {
- instance=instances.get(0);
- System.out.println("相匹配的SysUsers实例对象被找到!");
- }
- return instance;
- } catch (RuntimeException re) {
- System.out.println("findByUserAccount() 错误!");
- throw re;
- }
- }
-
- }
SysUsersRolesDaoImpl.java
service层的实现
AuthoritiesResourcesManager.java
- package org.joshua.ss.service;
-
- import org.joshua.ss.dao.daoimpl.BaseDaoImpl;
- import org.joshua.ss.entity.SysAuthoritiesResources;
- import org.springframework.stereotype.Service;
-
-
-
-
-
- @Service("authoritiesResourcesManager")
- public class AuthoritiesResourcesManager extends BaseDaoImpl<SysAuthoritiesResources,Long>{
-
- }
下同,
这里说明一下我没有去操作对应的dao层而直接去操作通用dao,如果对应到里没有自定义的方法,或者没有用到dao自定义的方法,可以直接继承通dao,这样也可省去dao层
这也是springside封装通用dao将dao彻底省略掉,将增删改查分页等功能都封装到通用dao中.
AuthorityManager.java
ResourceManager.java
RoleManager.java
RolesAuthoritiesManager.java
UserManager.java
这里用到dao自定义的方法,所以注入dao
- package org.joshua.ss.service;
-
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Set;
-
- import javax.annotation.Resource;
-
- import org.joshua.ss.dao.daoimpl.BaseDaoImpl;
- import org.joshua.ss.dao.daoimpl.SysUsersDaoImpl;
- import org.joshua.ss.entity.SysRolesAuthorities;
- import org.joshua.ss.entity.SysUsers;
- import org.joshua.ss.entity.SysUsersRoles;
- import org.springframework.orm.hibernate3.HibernateTemplate;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.authority.GrantedAuthorityImpl;
- import org.springframework.stereotype.Service;
-
-
-
-
-
-
- @Service("userManager")
- public class UserManager extends BaseDaoImpl<SysUsers,Long>{
- @Resource(name="hibernateTemplate")
- public HibernateTemplate hibernateTemplate;
-
- @Resource(name="sysUsersDaoImpl")
- public SysUsersDaoImpl userDao;
-
- public SysUsersDaoImpl getUserDao() {
- return userDao;
- }
- public void setUserDao(SysUsersDaoImpl userDao) {
- this.userDao = userDao;
-
- }
- public SysUsers queryUnique(String id){
- return hibernateTemplate.get(SysUsers.class, id);
- }
- public List<GrantedAuthority> loadUserAuthoritiesByName(String username) {
-
- try {
-
- List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
- List<String> authorityNameList = loadUserAuthorities(username);
-
- for (String authorityName : authorityNameList) {
-
- System.out.println(getClass().getName()+authorityName);
- GrantedAuthorityImpl authority = new GrantedAuthorityImpl(authorityName);
- auths.add(authority);
- }
-
- return auths;
-
- } catch (RuntimeException re) {
- throw re;
- }
- }
-
- public List<String> loadUserAuthorities(final String username) {
- try {
-
- List<String> authNameList = new ArrayList<String>();
-
- SysUsers user = userDao.findByUserAccount(username);
-
- Set<SysUsersRoles> usersRoles = user.getSysUsersRoleses();
- for(SysUsersRoles usersrole:usersRoles){
-
- Set<SysRolesAuthorities> rolesAuthorities = usersrole.getSysRoles().getSysRolesAuthorities();
- for(SysRolesAuthorities roleAuthoritiy:rolesAuthorities){
- String authName = roleAuthoritiy.getSysAuthorities().getAuthorityName();
- authNameList.add(authName);
- }
- }
- return authNameList;
- } catch (RuntimeException re) {
- System.out.println("find by authorities by username failed."
- + re.getMessage());
- throw re;
- }
-
- }
-
-
-
-
- }
2.4配置容器的xxx.xml文件
web.xml
applicationContext.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
-
- <context:component-scan base-package="org.joshua.ss" />
- </beans>
applicationContext_db.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
-
- <bean
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <value>classpath:dbConfig.properties</value>
- </property>
- </bean>
-
-
-
- <bean id="dataSource"
- class="org.apache.commons.dbcp.BasicDataSource"
- destroy-method="close">
- <property name="driverClassName" value="${jdbc.driver}" />
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.user}" />
- <property name="password" value="${jdbc.pwd}" />
- </bean>
-
- <bean id="sessionFactory"
- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
-
- <property name="mappingResources">
- <list>
- <value>org/joshua/ss/res/SysAuthorities.hbm.xml</value>
- <value>org/joshua/ss/res/SysAuthoritiesResources.hbm.xml</value>
- <value>org/joshua/ss/res/SysResources.hbm.xml</value>
- <value>org/joshua/ss/res/SysRoles.hbm.xml</value>
- <value>org/joshua/ss/res/SysRolesAuthorities.hbm.xml</value>
- <value>org/joshua/ss/res/SysUsers.hbm.xml</value>
- <value>org/joshua/ss/res/SysUsersRoles.hbm.xml</value>
- </list>
- </property>
-
-
- <!--<property name="annotatedPackages">
- <list>
- <value>org.joshua.ss.webapp.entity</value>
- </list>
- </property>
- -->
- <property name="hibernateProperties">
- <value>
- hibernate.dialect=org.hibernate.dialect.OracleDialect
- hibernate.show_sql=true
-
- hibernate.cache.use_second_level_cache=true
- hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
- </value>
- </property>
- </bean>
-
-
- <bean id="txManager"
- class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory" />
- </bean>
-
- <tx:annotation-driven transaction-manager="txManager" />
-
- <bean id="hibernateTemplate"
- class="org.springframework.orm.hibernate3.HibernateTemplate">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
- </beans>
applicationContext_security.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <b:beans xmlns="http://www.springframework.org/schema/security"
- xmlns:b="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/security
- http://www.springframework.org/schema/security/spring-security-3.0.xsd">
- <http auto-config="true" access-denied-page="/accessDenied.jsp">
-
- <intercept-url pattern="/**/*.jpg" filters="none" />
- <intercept-url pattern="/**/*.png" filters="none" />
- <intercept-url pattern="/**/*.gif" filters="none" />
- <intercept-url pattern="/**/*.css" filters="none" />
- <intercept-url pattern="/**/*.js" filters="none" />
-
-
- <intercept-url pattern="/login.jsp" filters="none" />
- <intercept-url pattern="/jsp/forgotpassword.jsp"
- filters="none" />
-
- <form-login login-page="/login.jsp"
- authentication-failure-url="/login.jsp?error=true"
- default-target-url="/index.jsp" />
-
- <logout logout-success-url="/login.jsp" />
-
- <!-- "记住我"功能,采用持久化策略(将用户的登录信息存放在数据库表中)需要创建一张persistent_logins 表
- <remember-me data-source-ref="dataSource" />
-
- -->
- <session-management invalid-session-url="/sessionTimeout.jsp" />
-
-
-
-
- <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR" />
- </http>
-
- <!--
- 一个自定义的filter
- 必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性。
- -->
- <b:bean id="myFilter" class="org.joshua.ss.MyFilterSecurityInterceptor">
- <b:property name="authenticationManager" ref="authenticationManager" />
- <b:property name="accessDecisionManager" ref="myAccessDecisionManager" />
- <b:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
- </b:bean>
-
-
- <authentication-manager alias="authenticationManager">
- <authentication-provider user-service-ref="myUserDetailService">
-
- </authentication-provider>
- </authentication-manager>
-
- <b:bean id="myUserDetailService" class="org.joshua.ss.MyUserDetailService" />
-
-
- <b:bean id="myAccessDecisionManager"
- class="org.joshua.ss.MyAccessDecisionManager">
- </b:bean>
-
-
- <b:bean id="mySecurityMetadataSource"
- class="org.joshua.ss.MyInvocationSecurityMetadataSource">
- </b:bean>
-
- </b:beans>
dbConfig.properties
- jdbc.user=scott
- jdbc.pwd=snail
- jdbc.url=jdbc\:oracle\:thin\:@localhost\:1521\:oracle
- jdbc.driver=oracle.jdbc.driver.OracleDriver
ehcache.xml 没有深入的研究,暂且搁置
- <?xml version="1.0" encoding="UTF-8" ?>
- <ehcache>
- <diskStore path="user.dir"></diskStore>
- <defaultCache
- maxElementsInMemory="10000"
- eternal="false"
- timeToIdleSeconds="120"
- timeToLiveSeconds="120"
- overflowToDisk="true" />
- </ehcache>
struts.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
-
- <constant name="struts.il8n.encoding" value="UTF-8"/>
- <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
- <constant name="struts.action.extension" value="do"/>
-
- <constant name="struts.objectFactory" value="spring"/>
- <package name="user" namespace="" extends="struts-default">
- <action name="*" class="loginAction" method="{1}">
- <result name="success">/success.jsp</result>
- <result name="error">/error.jsp</result>
- </action>
- </package>
- </struts>
spring security 中最重要的核心
MyAccessDecisionManager.java
MyFilterSecurityInterceptor.java
MyInvocationSecurityMetadataSource.java
MyUserDetails.java(自定义的SysUsers实现的接口,可以省掉,使用框架提供的User,
org.springframework.security.core.userdetails.User
)
MyUserDetailService.java
MyAccessDecisionManager.java
- package org.joshua.ss;
-
- import java.util.Collection;
- import java.util.Iterator;
-
- import org.springframework.security.access.AccessDecisionManager;
- import org.springframework.security.access.AccessDeniedException;
- import org.springframework.security.access.ConfigAttribute;
- import org.springframework.security.access.SecurityConfig;
- import org.springframework.security.authentication.InsufficientAuthenticationException;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.GrantedAuthority;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public class MyAccessDecisionManager implements AccessDecisionManager {
-
-
-
-
-
-
-
-
- public void decide(Authentication authentication, Object object,
- Collection<ConfigAttribute> configAttributes)
- throws AccessDeniedException, InsufficientAuthenticationException {
- if (configAttributes == null) {
- return;
- }
-
- Iterator<ConfigAttribute> ite = configAttributes.iterator();
-
- while (ite.hasNext()) {
- ConfigAttribute ca = ite.next();
- String needRole = ((SecurityConfig) ca).getAttribute();
-
-
- for (GrantedAuthority ga : authentication.getAuthorities()) {
- if (needRole.trim().equals(ga.getAuthority().trim())) {
- return;
- }
- }
- }
-
- throw new AccessDeniedException("no right!");
- }
-
- public boolean supports(ConfigAttribute arg0) {
-
- return true;
- }
-
- public boolean supports(Class<?> clazz) {
-
- return true;
- }
-
- }
MyFilterSecurityInterceptor.java
- package org.joshua.ss;
-
- import java.io.IOException;
-
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
-
- import org.springframework.security.access.SecurityMetadataSource;
- import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
- import org.springframework.security.access.intercept.InterceptorStatusToken;
- import org.springframework.security.web.FilterInvocation;
- import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
-
-
-
-
-
-
-
-
-
-
- public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor
- implements Filter {
- private FilterInvocationSecurityMetadataSource securityMetadataSource;
-
- @Override
- public Class<? extends Object> getSecureObjectClass() {
- return FilterInvocation.class;
- }
-
- public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
- return securityMetadataSource;
- }
-
- public void setSecurityMetadataSource(
- FilterInvocationSecurityMetadataSource securityMetadataSource) {
- this.securityMetadataSource = securityMetadataSource;
- }
-
- @Override
- public SecurityMetadataSource obtainSecurityMetadataSource() {
- return this.securityMetadataSource;
- }
-
- public void invoke(FilterInvocation fi) throws IOException,
- ServletException {
-
- InterceptorStatusToken token = super.beforeInvocation(fi);
-
- try {
- fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
- } finally {
- super.afterInvocation(token, null);
- }
-
- }
-
- public void destroy() {
-
- }
-
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- FilterInvocation fi = new FilterInvocation(request, response, chain);
- invoke(fi);
- }
-
- public void init(FilterConfig arg0) throws ServletException {
-
- }
-
- }
MyInvocationSecurityMetadataSource.java
MyUserDetails.java
- package org.joshua.ss;
-
- import java.util.Set;
-
- import org.springframework.security.core.userdetails.UserDetails;
-
-
-
-
-
- public interface MyUserDetails extends UserDetails{
-
- public String getUserId();
-
- public String getUserAccount();
-
- public String getUserName();
-
- public String getUserPassword();
-
- public String getUserDesc();
-
- public boolean getEnabled();
-
- public Boolean getIssys();
-
- public String getUserDept();
-
- public String getUserDuty();
-
- public String getSubSystem();
-
- public Set getSysUsersRoleses();
- }
MyUserDetailService.java
- package org.joshua.ss;
-
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.HashSet;
-
- import javax.annotation.Resource;
-
- import org.joshua.ss.entity.SysUsers;
- import org.joshua.ss.service.UserManager;
- import org.springframework.dao.DataAccessException;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.core.userdetails.UserDetailsService;
- import org.springframework.security.core.userdetails.UsernameNotFoundException;
-
- public class MyUserDetailService implements UserDetailsService {
- @Resource(name = "userManager")
- private UserManager userManager;
-
- public UserDetails loadUserByUsername(String username)
- throws UsernameNotFoundException, DataAccessException {
-
- Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
- if (null == userManager) {
- userManager = new UserManager();
- }
-
-
- auths = userManager.loadUserAuthoritiesByName(username);
-
-
- SysUsers user = userManager.userDao.findByUserAccount(username);
-
- System.out.println("user.getUserId() "+user.getUserId()+" user.getUserName()"+user.getUserName()+" user.getUserPassword()"+user.getUserPassword());
-
- return new SysUsers(
- user.getUserId(),
- user.getUserAccount(),
- user.getUserName(),
- user.getUserPassword(),
- user.getUserDesc(),
- user.getEnabled(),
- user.getIssys(),
- user.getUserDuty(),
- user.getUserDept(),
- user.getSubSystem(),
- new HashSet(0),
- true,
- true,
- true,
- auths);
-
-
- }
-
- }
参考:http://www.blogjava.net/SpartaYew/archive/2011/06/15/350630.html
http://wenku.baidu.com/view/4ec7e324ccbff121dd368364.html
Spring+Security+安全权限管理手册 family168 (讲的比较细,够基础,好理解)