Spring Security应用实例(一):用户登录

经过Spring Security官方文档及相关资料的学习,自己做了一个简单的用户登录模块,现在将自己写的代码整理处理,以供大家参考或交流,如有不对,请指正错误。

1、库表建立

     1)用户表

Sql代码  收藏代码
  1. DROP TABLE IF EXISTS `users`;  
  2. CREATE TABLE `users` (  
  3.   `id` int(10) NOT NULL auto_increment,  
  4.   `login_name` varchar(20) default NULL,  
  5.   `passwordvarchar(20) default NULL,  
  6.   `namevarchar(20) default NULL,  
  7.   `email` varchar(30) default NULL,  
  8.   PRIMARY KEY  (`id`)  
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  

     2)角色表

Sql代码  收藏代码
  1. DROP TABLE IF EXISTS `roles`;  
  2. CREATE TABLE `roles` (  
  3.   `id` int(10) NOT NULL auto_increment,  
  4.   `namevarchar(20) default NULL,  
  5.   PRIMARY KEY  (`id`)  
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  

     3)权限表

Sql代码  收藏代码
  1. DROP TABLE IF EXISTS `authorities`;  
  2. CREATE TABLE `authorities` (  
  3.   `id` int(10) NOT NULL auto_increment,  
  4.   `namevarchar(20) default NULL,  
  5.   `display_name` varchar(20) default NULL,  
  6.   PRIMARY KEY  (`id`)  
  7. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  

     4)用户-角色表

Sql代码  收藏代码
  1. DROP TABLE IF EXISTS `users_roles`;  
  2. CREATE TABLE `users_roles` (  
  3.   `user_id` int(10) NOT NULL,  
  4.   `role_id` int(10) NOT NULL,  
  5.   PRIMARY KEY  (`user_id`,`role_id`),  
  6.   KEY `FK_R_2` (`role_id`),  
  7.   CONSTRAINT `FK_R_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),  
  8.   CONSTRAINT `FK_R_2` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`)  

 

    5)角色-权限表

Sql代码  收藏代码
  1. DROP TABLE IF EXISTS `roles_authorities`;  
  2. CREATE TABLE `roles_authorities` (  
  3.   `role_id` int(10) NOT NULL,  
  4.   `authority_id` int(10) NOT NULL,  
  5.   PRIMARY KEY  (`role_id`,`authority_id`),  
  6.   KEY `FK_R_4` (`authority_id`),  
  7.   CONSTRAINT `FK_R_3` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`),  
  8.   CONSTRAINT `FK_R_4` FOREIGN KEY (`authority_id`) REFERENCES `authorities` (`id`)  
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  

 

2、建立Pojo类

     1)用户

Java代码  收藏代码
  1. package cn.com.sunjiesh.springmvcdemo.entity;  
  2.   
  3. import javax.persistence.GeneratedValue;  
  4. import javax.persistence.GenerationType;  
  5. import javax.persistence.Id;  
  6. import javax.persistence.MappedSuperclass;  
  7.   
  8. /** 
  9.  * 统一定义id的entity基类. 
  10.  *  
  11.  * @author calvin 
  12.  */  
  13. @MappedSuperclass  
  14. public class IdEntity {  
  15.   
  16.     private Long id;  
  17.   
  18.     @Id  
  19.     @GeneratedValue(strategy = GenerationType.IDENTITY)  
  20.     public Long getId() {  
  21.         return id;  
  22.     }  
  23.   
  24.     public void setId(Long id) {  
  25.         this.id = id;  
  26.     }  
  27. }  
 
Java代码  收藏代码
  1. package cn.com.sunjiesh.springmvcdemo.entity.user;  
  2.   
  3. import java.util.LinkedHashSet;  
  4. import java.util.List;  
  5. import java.util.Set;  
  6.   
  7. import javax.persistence.CascadeType;  
  8. import javax.persistence.Column;  
  9. import javax.persistence.Entity;  
  10. import javax.persistence.FetchType;  
  11. import javax.persistence.JoinColumn;  
  12. import javax.persistence.JoinTable;  
  13. import javax.persistence.ManyToMany;  
  14. import javax.persistence.OrderBy;  
  15. import javax.persistence.Table;  
  16. import javax.persistence.Transient;  
  17.   
  18. import org.apache.commons.lang.builder.ToStringBuilder;  
  19. import org.hibernate.annotations.Cache;  
  20. import org.hibernate.annotations.CacheConcurrencyStrategy;  
  21. import org.hibernate.annotations.Fetch;  
  22. import org.hibernate.annotations.FetchMode;  
  23. import org.springside.modules.utils.CollectionUtils;  
  24.   
  25. import cn.com.sunjiesh.springmvcdemo.entity.IdEntity;  
  26.   
  27. /** 
  28.  * 用户. 
  29.  *  
  30.  * 注意@Cache(Entity与集合的缓存),@ManyToMany/@JoinTable(多对多关系),@OrderBy/LinkedHashSet(集合排序),@Transient(非持久化属性)的应用. 
  31.  *  
  32.  * @author calvin 
  33.  */  
  34. @Entity  
  35. @Table(name = "USERS")  
  36. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
  37. public class User extends IdEntity {  
  38.   
  39.     private String loginName;  
  40.   
  41.     private String password;  
  42.   
  43.     private String name;  
  44.   
  45.     private String email;  
  46.   
  47.     private Set<Role> roles = new LinkedHashSet<Role>();  
  48.   
  49.     @Column(name="login_name")  
  50.     public String getLoginName() {  
  51.         return loginName;  
  52.     }  
  53.   
  54.     public void setLoginName(String loginName) {  
  55.         this.loginName = loginName;  
  56.     }  
  57.   
  58.     @Column(name="password")  
  59.     public String getPassword() {  
  60.         return password;  
  61.     }  
  62.   
  63.     public void setPassword(String password) {  
  64.         this.password = password;  
  65.     }  
  66.   
  67.     @Column(name="name")  
  68.     public String getName() {  
  69.         return name;  
  70.     }  
  71.   
  72.     public void setName(String name) {  
  73.         this.name = name;  
  74.     }  
  75.   
  76.     @Column(name="email")  
  77.     public String getEmail() {  
  78.         return email;  
  79.     }  
  80.   
  81.     public void setEmail(String email) {  
  82.         this.email = email;  
  83.     }  
  84.   
  85.     @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE },fetch=FetchType.EAGER)  
  86.     @JoinTable(name = "USERS_ROLES", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })  
  87.     @OrderBy("id")  
  88.     @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
  89.     public Set<Role> getRoles() {  
  90.         return roles;  
  91.     }  
  92.   
  93.     public void setRoles(Set<Role> roles) {  
  94.         this.roles = roles;  
  95.     }  
  96.   
  97.     @Transient  
  98.     public String getRoleNames() throws Exception {  
  99.         return CollectionUtils.fetchPropertyToString(roles, "name"", ");  
  100.     }  
  101.   
  102.     @SuppressWarnings("unchecked")  
  103.     @Transient  
  104.     public List<Long> getRoleIds() throws Exception {  
  105.         return CollectionUtils.fetchPropertyToList(roles, "id");  
  106.     }  
  107.   
  108.     @Override  
  109.     public String toString() {  
  110.         return ToStringBuilder.reflectionToString(this);  
  111.     }  
  112. }  
 

     2)角色

Java代码  收藏代码
  1. package cn.com.sunjiesh.springmvcdemo.entity.user;  
  2.   
  3. import java.util.LinkedHashSet;  
  4. import java.util.List;  
  5. import java.util.Set;  
  6.   
  7. import javax.persistence.CascadeType;  
  8. import javax.persistence.Entity;  
  9. import javax.persistence.FetchType;  
  10. import javax.persistence.JoinColumn;  
  11. import javax.persistence.JoinTable;  
  12. import javax.persistence.ManyToMany;  
  13. import javax.persistence.OrderBy;  
  14. import javax.persistence.Table;  
  15. import javax.persistence.Transient;  
  16.   
  17. import org.apache.commons.lang.builder.ToStringBuilder;  
  18. import org.hibernate.annotations.Cache;  
  19. import org.hibernate.annotations.CacheConcurrencyStrategy;  
  20. import org.springside.modules.utils.CollectionUtils;  
  21.   
  22. import cn.com.sunjiesh.springmvcdemo.entity.IdEntity;  
  23.   
  24. /** 
  25.  * 角色. 
  26.  *  
  27.  * 注意@Cache(Entity与集合的缓存),@ManyToMany/@JoinTable(多对多关系),@OrderBy/LinkedHashSet(集合排序),@Transient(非持久化属性)的应用. 
  28.  *  
  29.  * @author calvin 
  30.  */  
  31. @Entity  
  32. @Table(name = "ROLES")  
  33. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
  34. public class Role extends IdEntity {  
  35.   
  36.     private String name;  
  37.   
  38.     private Set<Authority> auths = new LinkedHashSet<Authority>();  
  39.   
  40.     public String getName() {  
  41.         return name;  
  42.     }  
  43.   
  44.     public void setName(String name) {  
  45.         this.name = name;  
  46.     }  
  47.   
  48.     @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE },fetch=FetchType.EAGER)  
  49.     @JoinTable(name = "ROLES_AUTHORITIES", joinColumns = { @JoinColumn(name = "ROLE_ID") }, inverseJoinColumns = { @JoinColumn(name = "AUTHORITY_ID") })  
  50.     @OrderBy("id")  
  51.     @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
  52.     public Set<Authority> getAuths() {  
  53.         return auths;  
  54.     }  
  55.   
  56.     public void setAuths(Set<Authority> auths) {  
  57.         this.auths = auths;  
  58.     }  
  59.   
  60.     @Transient  
  61.     public String getAuthNames() throws Exception {  
  62.         return CollectionUtils.fetchPropertyToString(auths, "displayName"", ");  
  63.     }  
  64.   
  65.     @SuppressWarnings("unchecked")  
  66.     @Transient  
  67.     public List<Long> getAuthIds() throws Exception {  
  68.         return CollectionUtils.fetchPropertyToList(auths, "id");  
  69.     }  
  70.   
  71.     @Override  
  72.     public String toString() {  
  73.         return ToStringBuilder.reflectionToString(this);  
  74.     }  
  75. }  
 

     3)权限

Java代码  收藏代码
  1. package cn.com.sunjiesh.springmvcdemo.entity.user;  
  2.   
  3. import javax.persistence.Column;  
  4. import javax.persistence.Entity;  
  5. import javax.persistence.Table;  
  6.   
  7. import org.apache.commons.lang.builder.ToStringBuilder;  
  8. import org.hibernate.annotations.Cache;  
  9. import org.hibernate.annotations.CacheConcurrencyStrategy;  
  10.   
  11. import cn.com.sunjiesh.springmvcdemo.entity.IdEntity;  
  12.   
  13. /** 
  14.  * 权限. 
  15.  *  
  16.  * @Cache使用READ_ONLY策略. 
  17.  *  
  18.  * @author calvin 
  19.  */  
  20. @Entity  
  21. @Table(name = "AUTHORITIES")  
  22. @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)  
  23. public class Authority extends IdEntity {  
  24.   
  25.     private String name;  
  26.   
  27.     private String displayName;  
  28.   
  29.     public String getName() {  
  30.         return name;  
  31.     }  
  32.   
  33.     public void setName(String name) {  
  34.         this.name = name;  
  35.     }  
  36.   
  37.     @Column(name="display_name")  
  38.     public String getDisplayName() {  
  39.         return displayName;  
  40.     }  
  41.   
  42.     public void setDisplayName(String displayName) {  
  43.         this.displayName = displayName;  
  44.     }  
  45.   
  46.     @Override  
  47.     public String toString() {  
  48.         return ToStringBuilder.reflectionToString(this);  
  49.     }  
  50. }  
 

     注意:@ManyToMany中的fetch=FetchType.EAGER。如果fetch=FetchType.LAZY会报异常。

3、建立DAO类

    1)接口

 

Java代码  收藏代码
  1. package cn.com.sunjiesh.springmvcdemo.dao.iface;  
  2.   
  3. import cn.com.sunjiesh.springmvcdemo.entity.user.User;  
  4.   
  5.   
  6.   
  7. /** 
  8.  *  
  9.  * @author sunjie 
  10.  * @since 2009-03-29 
  11.  *  
  12.  */  
  13. public interface IUserDAO extends IBaseHibernateDAO<User> {  
  14.   
  15.     public User getUserByUserName(String username);  
  16.   
  17. }  
 

    2)实现类

Java代码  收藏代码
  1. package cn.com.sunjiesh.springmvcdemo.dao.impl;  
  2.   
  3. import org.apache.log4j.Logger;  
  4. import org.hibernate.Query;  
  5.   
  6.   
  7. import cn.com.sunjiesh.springmvcdemo.dao.iface.IUserDAO;  
  8. import cn.com.sunjiesh.springmvcdemo.entity.user.User;  
  9.   
  10. public class UserDAOImpl extends BaseHibernateDAOImpl<User> implements IUserDAO {  
  11.   
  12.     private static Logger LOG = Logger.getLogger(UserDAOImpl.class);  
  13.   
  14.     public User getUserByUserName(String username) {  
  15.         String hql = "from User where loginName = ?";  
  16.         Query query = getSession().createQuery(hql);  
  17.         query.setParameter(0, username);  
  18.         User user = (User) query.list().get(0);  
  19.         return user;  
  20.     }  
  21.   
  22. }  

 

4、Spring Security相关代码

Java代码  收藏代码
  1. package cn.com.sunjiesh.springmvcdemo.service.security;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.apache.log4j.Logger;  
  7. import org.springframework.dao.DataAccessException;  
  8. import org.springframework.security.GrantedAuthority;  
  9. import org.springframework.security.GrantedAuthorityImpl;  
  10.   
  11. import org.springframework.security.userdetails.UserDetails;  
  12. import org.springframework.security.userdetails.UserDetailsService;  
  13. import org.springframework.security.userdetails.UsernameNotFoundException;  
  14.   
  15. import cn.com.sunjiesh.springmvcdemo.dao.iface.IUserDAO;  
  16. import cn.com.sunjiesh.springmvcdemo.entity.user.Authority;  
  17. import cn.com.sunjiesh.springmvcdemo.entity.user.Role;  
  18. import cn.com.sunjiesh.springmvcdemo.entity.user.User;  
  19.   
  20.   
  21.   
  22. /** 
  23.  * 实现SpringSecurity的UserDetailsService接口,获取用户Detail信息. 
  24.  * @author calvin 
  25.  */  
  26. public class UserDetailServiceImpl implements UserDetailsService{  
  27.   
  28.     private static Logger LOG=Logger.getLogger(UserDetailServiceImpl.class);  
  29.       
  30.     private IUserDAO userDao;  
  31.       
  32.     public UserDetails loadUserByUsername(String username)  
  33.             throws UsernameNotFoundException, DataAccessException {  
  34.         if(username==null){  
  35.             LOG.error("username is null");  
  36.         }  
  37.         if(userDao==null){  
  38.             LOG.error("userDao is null");  
  39.         }  
  40.         User user=userDao.getUserByUserName(username);  
  41.         //TOTO 判断用户存在,如果不存在,则抛出异常。  
  42.         if(user==null){  
  43.             LOG.error(username+" is not exist"new UsernameNotFoundException(username+" is not exist"));  
  44.         }  
  45.           
  46.         List<GrantedAuthority> authsList = new ArrayList<GrantedAuthority>();  
  47.           
  48.         System.out.println("user.getRoles().size()="+user.getRoles().size());  
  49.         for (Role role : user.getRoles()) {  
  50.             for (Authority authority : role.getAuths()) {  
  51.                 authsList.add(new GrantedAuthorityImpl(authority.getName()));  
  52.             }  
  53.         }  
  54.           
  55.         //TODO   
  56.         org.springframework.security.userdetails.User userdetail = new org.springframework.security.userdetails.User(  
  57.                 user.getLoginName(), user.getPassword(), truetruetruetrue, authsList  
  58.                         .toArray(new GrantedAuthority[authsList.size()]));  
  59.   
  60.         return userdetail;  
  61.     }  
  62.   
  63.     public void setUserDao(IUserDAO userDao) {  
  64.         this.userDao = userDao;  
  65.     }  
  66. }  
 

5、配置文件

    1)web.xml

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app id="WebApp_ID" version="2.4"  
  3.     xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  5.     <display-name> SpringMVCDemo</display-name>  
  6.     <context-param>  
  7.         <param-name>contextConfigLocation</param-name>  
  8.         <param-value>classpath:/cn/com/sunjiesh/springmvcdemo/spring/spring-*.xml,/WEB-INF/springmvcdemo-servlet.xml</param-value>  
  9.     </context-param>  
  10.     <listener>  
  11.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  12.     </listener>  
  13.     <!--  
  14.         Spring Security可以限制一个主体并行认证到同一系统的次数。  
  15.         很多ISV利用这点来加强授权公里,网管也喜欢这个功能,因为它可以防止人们共享登录名。  
  16.         你可以,比如,禁止用户"Batman"从两个不同的会话登录到web应用里。  
  17.     -->  
  18.     <listener>  
  19.         <listener-class>org.springframework.security.ui.session.HttpSessionEventPublisher</listener-class>  
  20.     </listener>  
  21.       
  22.       
  23.     <!--Character Encoding Convert-->  
  24.     <filter>  
  25.         <filter-name>encodingFilter</filter-name>  
  26.         <filter-class> org.springframework.web.filter.CharacterEncodingFilter   
  27.         </filter-class>  
  28.         <init-param>  
  29.             <param-name>encoding</param-name>  
  30.             <param-value>gb2312</param-value>  
  31.         </init-param>  
  32.     </filter>  
  33.     <filter-mapping>  
  34.         <filter-name>encodingFilter</filter-name>  
  35.         <url-pattern>*.do</url-pattern>  
  36.     </filter-mapping>  
  37.     <!-- Spring Security Filter-->  
  38.     <filter>  
  39.         <filter-name>springSecurityFilterChain</filter-name>  
  40.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  41.     </filter>  
  42.     <filter-mapping>  
  43.         <filter-name>springSecurityFilterChain</filter-name>  
  44.         <url-pattern>/*</url-pattern>  
  45.     </filter-mapping>  
  46.       
  47.     <!-- Use DWR -->  
  48.     <servlet>  
  49.         <servlet-name>dwr-invoker</servlet-name>  
  50.         <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>  
  51.     </servlet>  
  52.     <servlet-mapping>  
  53.         <servlet-name>dwr-invoker</servlet-name>  
  54.         <url-pattern>/dwr/*</url-pattern>  
  55.     </servlet-mapping>  
  56.     <!-- Spring MVC Dispatcher -->  
  57.     <servlet>  
  58.         <servlet-name>springmvcdemo</servlet-name>  
  59.         <servlet-class> org.springframework.web.servlet.DispatcherServlet   
  60.         </servlet-class>  
  61.         <init-param>  
  62.             <param-name>contextConfigLocation</param-name>  
  63.             <param-value>WEB-INF/springmvcdemo-servlet.xml</param-value>  
  64.         </init-param>  
  65.         <load-on-startup>1</load-on-startup>  
  66.     </servlet>  
  67.     <servlet-mapping>  
  68.         <servlet-name>springmvcdemo</servlet-name>  
  69.         <url-pattern>*.do</url-pattern>  
  70.     </servlet-mapping>  
  71.       
  72.     <!-- JSTL Configuration -->  
  73.     <jsp-config>  
  74.         <taglib>  
  75.             <taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>  
  76.             <taglib-location>/WEB-INF/tlds/fmt.tld</taglib-location>  
  77.         </taglib>  
  78.         <taglib>  
  79.             <taglib-uri>http://java.sun.com/jstl/fmt-rt</taglib-uri>  
  80.             <taglib-location>/WEB-INF/tlds/fmt-rt.tld</taglib-location>  
  81.         </taglib>  
  82.         <taglib>  
  83.             <taglib-uri>http://java.sun.com/jstl/core</taglib-uri>  
  84.             <taglib-location>/WEB-INF/tlds/c.tld</taglib-location>  
  85.         </taglib>  
  86.         <taglib>  
  87.             <taglib-uri>http://java.sun.com/jstl/core-rt</taglib-uri>  
  88.             <taglib-location>/WEB-INF/tlds/c-rt.tld</taglib-location>  
  89.         </taglib>  
  90.         <taglib>  
  91.             <taglib-uri>http://java.sun.com/jstl/sql</taglib-uri>  
  92.             <taglib-location>/WEB-INF/tlds/sql.tld</taglib-location>  
  93.         </taglib>  
  94.         <taglib>  
  95.             <taglib-uri>http://java.sun.com/jstl/sql-rt</taglib-uri>  
  96.             <taglib-location>/WEB-INF/tlds/sql-rt.tld</taglib-location>  
  97.         </taglib>  
  98.         <taglib>  
  99.             <taglib-uri>http://java.sun.com/jstl/x</taglib-uri>  
  100.             <taglib-location>/WEB-INF/tlds/x.tld</taglib-location>  
  101.         </taglib>  
  102.         <taglib>  
  103.             <taglib-uri>http://java.sun.com/jstl/x-rt</taglib-uri>  
  104.             <taglib-location>/WEB-INF/tlds/x-rt.tld</taglib-location>  
  105.         </taglib>  
  106.     </jsp-config>  
  107.     <welcome-file-list>  
  108.         <welcome-file>index.html</welcome-file>  
  109.         <welcome-file>index.htm</welcome-file>  
  110.         <welcome-file>index.jsp</welcome-file>  
  111.         <welcome-file>default.html</welcome-file>  
  112.         <welcome-file>default.htm</welcome-file>  
  113.         <welcome-file>default.jsp</welcome-file>  
  114.     </welcome-file-list>  
  115. </web-app>  
 

 

    2)spring-base.xml

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
  3. <beans>  
  4.     <bean id="propertyConfigurer"  
  5.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  6.         <property name="locations">  
  7.             <list>  
  8.                 <value>classpath:/cn/com/sunjiesh/springmvcdemo/spring/jdbc.properties</value>  
  9.             </list>  
  10.         </property>  
  11.     </bean>  
  12.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
  13.         destroy-method="close">  
  14.         <property name="driverClassName" value="${jdbc.driverClassName}" />  
  15.         <property name="url" value="${jdbc.url}" />  
  16.         <property name="username" value="${jdbc.username}" />  
  17.         <property name="password" value="${jdbc.password}" />  
  18.     </bean>  
  19.     <bean id="sessionFactory"  
  20.         class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
  21.         <property name="dataSource" ref="dataSource" />  
  22.         <!-- Hibernate Annotation Entity -->  
  23.         <property name="annotatedClasses">  
  24.             <list>  
  25.                 <value>cn.com.sunjiesh.springmvcdemo.entity.user.Authority</value>  
  26.                 <value>cn.com.sunjiesh.springmvcdemo.entity.user.Role</value>  
  27.                 <value>cn.com.sunjiesh.springmvcdemo.entity.user.User</value>  
  28.             </list>  
  29.         </property>  
  30.         <property name="hibernateProperties">  
  31.             <props>  
  32.                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
  33.                 <prop key="hibernate.show_sql">true</prop>  
  34.                 <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>  
  35.                 <prop key="hibernate.cache.use_second_level_cache">false</prop>  
  36.                 <prop key="hibernate.cache.use_query_cache">false</prop>  
  37.             </props>  
  38.         </property>  
  39.     </bean>  
  40.     <bean id="txManager"  
  41.         class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  42.         <property name="sessionFactory" ref="sessionFactory" />  
  43.     </bean>  
  44.     <bean id="baseTxService"  
  45.         class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"  
  46.         abstract="true">  
  47.         <property name="transactionManager" ref="txManager" />  
  48.         <property name="proxyTargetClass" value="true" />  
  49.         <property name="transactionAttributes">  
  50.             <props>  
  51.                 <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>  
  52.                 <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>  
  53.                 <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>  
  54.                 <prop key="save*">PROPAGATION_REQUIRED</prop>  
  55.                 <prop key="update*">PROPAGATION_REQUIRED</prop>  
  56.                 <prop key="remove*">PROPAGATION_REQUIRED</prop>  
  57.             </props>  
  58.         </property>  
  59.     </bean>  
  60. </beans>  
 

    3)spring-dao.xml

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
  3. <!--   
  4.     Author By Sun Jie  
  5.     Shared document  
  6. -->  
  7. <beans default-autowire="byName" default-lazy-init="true">  
  8.       
  9.     <!-- Add By Sun Jie -->  
  10.     <bean id="userDaoTarget" class="cn.com.sunjiesh.springmvcdemo.dao.impl.UserDAOImpl">  
  11.     </bean>  
  12.     <!-- End Edit -->  
  13.       
  14.     <!-- Add By Sun Jie -->  
  15.     <bean id="userDao" parent="baseTxService">  
  16.         <property name="target">  
  17.             <ref bean="userDaoTarget"/>  
  18.         </property>  
  19.     </bean>  
  20.     <!-- End Edit -->  
  21. </beans>  
 

    4)spring-security.xml

Xml代码  收藏代码
  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" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:security="http://www.springframework.org/schema/security"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  6.         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">  
  7.     <!-- 
  8.         FilterChainProxy会按顺序来调用这些filter,使这些filter能享用Spring Ioc的功能 
  9.     -->  
  10.     <bean id="springSecurityFilterChain" class="org.springframework.security.util.FilterChainProxy">  
  11.         <security:filter-chain-map path-type="ant">  
  12.             <security:filter-chain pattern="/user/**"  
  13.                 filters="httpSessionContextIntegrationFilter,logoutFilter,authenticationProcessingFilter,basicProcessingFilter,securityContextHolderAwareRequestFilter,exceptionTranslationFilter" />  
  14.         </security:filter-chain-map>  
  15.     </bean>  
  16.     <!--  
  17.         集成过滤器(HttpSessionContextIntegrationFilter是集成过滤器的一个实现)  
  18.         每次request前HttpSessionContextIntegrationFilter从Session中获取Authentication对象,在request完后  
  19.         又把Authentication对象保存到Session中供下次request使用,此filter必须在其他Acegi filter前使用  
  20.     -->  
  21.     <bean id="httpSessionContextIntegrationFilter"  
  22.         class="org.springframework.security.context.HttpSessionContextIntegrationFilter" />  
  23.       
  24.     <!-- 
  25.         退出(Logout)过滤器 退出登录操作 
  26.     -->  
  27.     <bean id="logoutFilter" class="org.springframework.security.ui.logout.LogoutFilter">  
  28.         <!-- 退出系统后系统跳转到此URL -->  
  29.         <constructor-arg value="/login.action" />  
  30.         <!-- 退出系统后的操作(调用logout方法) -->  
  31.         <constructor-arg>  
  32.             <list>  
  33.                 <!-- 实现了LogoutHandler接口(logout方法) -->  
  34.                 <ref bean="rememberMeServices" />  
  35.                 <bean  
  36.                     class="org.springframework.security.ui.logout.SecurityContextLogoutHandler" />  
  37.             </list>  
  38.         </constructor-arg>  
  39.     </bean>  
  40.     <!--  
  41.         处理表单认证filter: 1.authenticationManager 认证管理器 2.authenticationFailureUrl  
  42.         定义登录失败时转向的页面 3.defaultTargetUrl 定义登录成功时转向的页面 4.filterProcessesUrl  
  43.         定义登录请求的地址 5.rememberMeServices 在验证成功后添加cookie信息  
  44.     -->  
  45.     <bean id="authenticationProcessingFilter"  
  46.         class="org.springframework.security.ui.webapp.AuthenticationProcessingFilter">  
  47.         <property name="authenticationManager" ref="authenticationManager"></property>  
  48.         <property name="authenticationFailureUrl" value="/user/login.jsp"></property>  
  49.         <property name="defaultTargetUrl" value="/user/index.jsp"></property>  
  50.         <property name="filterProcessesUrl" value="/user/j_spring_security_check"></property>  
  51.         <property name="rememberMeServices" ref="rememberMeServices"></property>  
  52.     </bean>  
  53.       
  54.     <!-- 基本认证机制处理 -->  
  55.     <bean id="basicProcessingFilter"  
  56.         class="org.springframework.security.ui.basicauth.BasicProcessingFilter">  
  57.         <property name="authenticationManager">  
  58.             <ref bean="authenticationManager" />  
  59.         </property>  
  60.         <property name="authenticationEntryPoint">  
  61.             <bean id="authenticationEntryPoint"  
  62.                 class="org.springframework.security.ui.basicauth.BasicProcessingFilterEntryPoint">  
  63.                 <property name="realmName">  
  64.                     <value>Name Of Your Realm</value>  
  65.                 </property>  
  66.             </bean>  
  67.         </property>  
  68.     </bean>  
  69.     <bean id="securityContextHolderAwareRequestFilter"  
  70.         class="org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter" />  
  71.         <!-- 
  72.         如果不存在任何授权信息时,自动添加匿名用户身份至SecurityContextHolder中 
  73.     -->  
  74.     <bean id="anonymousProcessingFilter"  
  75.         class="org.springframework.security.providers.anonymous.AnonymousProcessingFilter">  
  76.         <property name="key" value="springsecurity"></property>  
  77.         <property name="userAttribute" value="anonymousUser,ROLE_ANONYMOUS"></property>  
  78.     </bean>  
  79.     <!--  
  80.         异常处理filter(异常转换过滤器),主要是处理AccessDeniedException和AuthenticationException,  
  81.         将给每个异常找到合适的"去向"  
  82.     -->  
  83.     <bean id="exceptionTranslationFilter"  
  84.         class="org.springframework.security.ui.ExceptionTranslationFilter">  
  85.         <property name="authenticationEntryPoint" ref="authenticationProcessingFilterEntryPoint" />  
  86.         <property name="accessDeniedHandler">  
  87.             <bean class="org.springframework.security.ui.AccessDeniedHandlerImpl">  
  88.                 <property name="errorPage" value="/accessDenied.jsp" />  
  89.             </bean>  
  90.         </property>  
  91.     </bean>  
  92.     <!--  
  93.         使用过滤器安全拦截器保护资源  
  94.         filterSecurityInterceptor在执行转向目标url前检查objectDefinitionSource中设定的用户权限信息,  
  95.         安全强制过滤器负责拦截请求,判断请求是否安全,并且给予认证和访问决策管理器一个机会来验证用户的身份和权限 过程:  
  96.         首先,过滤器安全拦截器使用authenticationManager调用自己的provider来对用户的认证信息进行验证并获取用户已有的权限。  
  97.         然后,使用访问决策管理器来判断用户是否拥用合适的授权来访问受保护的资源。  
  98.         (objectDefinitionSource属性定义了访问URL需要的权限信息)  
  99.         最后,有投票者根据用户持有认证和访问url需要的属性,调用自己的voter来投票,决定是否允许访问。  
  100.     -->  
  101.     <bean id="filterSecurityInterceptor"  
  102.         class="org.springframework.security.intercept.web.FilterSecurityInterceptor">  
  103.         <property name="authenticationManager" ref="authenticationManager"></property>  
  104.         <property name="accessDecisionManager" ref="accessDecisionManager"></property>  
  105.         <!--  
  106.             <property name="objectDefinitionSource"  
  107.             ref="objectDefinitionSource"></property>  
  108.         -->  
  109.         <property name="objectDefinitionSource">  
  110.             <security:filter-invocation-definition-source>  
  111.                 <security:intercept-url pattern="/secure/super/**"  
  112.                     access="ROLE_WE_DONT_HAVE" />  
  113.                 <security:intercept-url pattern="/secure/**"  
  114.                     access="ROLE_SUPERVISOR,ROLE_TELLER" />  
  115.                 <security:intercept-url pattern="/login.action*"  
  116.                     access="IS_AUTHENTICATED_ANONYMOUSLY" />  
  117.                 <security:intercept-url pattern="/user/user!save.action*"  
  118.                     access="ROLE_MODIFY_USER" />  
  119.                 <security:intercept-url pattern="/user/user!delete.action*"  
  120.                     access="ROLE_MODIFY_USER" />  
  121.                 <security:intercept-url pattern="/user/user*.action*"  
  122.                     access="ROLE_VIEW_USER" />  
  123.                 <security:intercept-url pattern="/user/role!save.action*"  
  124.                     access="ROLE_MODIFY_ROLE" />  
  125.                 <security:intercept-url pattern="/user/role!delete.action*"  
  126.                     access="ROLE_MODIFY_ROLE" />  
  127.                 <security:intercept-url pattern="/user/role*.action*"  
  128.                     access="ROLE_VIEW_ROLE" />  
  129.             </security:filter-invocation-definition-source>  
  130.         </property>  
  131.     </bean>  
  132.     <!--  
  133.         访问决策管理器  
  134.         验证用户是否有权限访问相应的资源(filterSecurityInterceptor中objectDefinitionSource属性定义的访问URL需要的属性信息)  
  135.     -->  
  136.     <bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased"  
  137.         p:allowIfAllAbstainDecisions="false">  
  138.         <property name="decisionVoters">  
  139.             <list>  
  140.                 <bean class="org.springframework.security.vote.RoleVoter" />  
  141.                 <bean class="org.springframework.security.vote.AuthenticatedVoter" />  
  142.             </list>  
  143.         </property>  
  144.     </bean>  
  145.     <bean id="authenticationProcessingFilterEntryPoint"  
  146.         class="org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint">  
  147.         <property name="loginFormUrl" value="/login.jsp" />  
  148.         <property name="forceHttps" value="false" />  
  149.     </bean>  
  150.     <!--  
  151.         认证管理器(org.springframework.security.AuthenticationManager接口)  
  152.         org.springframework.security.providers.ProviderManager是认证管理器的一个实现,  
  153.         ProviderManager通过遍历一个提供者的集合来实现身份验证, 直到某一个认证提供者能够成功地验证该用户的身份  
  154.     -->  
  155.     <!--  
  156.         通过Providers提供认证者列表,如果一个认证提供者失败可以尝试另外一个认证提供者,以保证获取不同来源的身份认证,如  
  157.         DaoAuthenticationProvider 从数据库中读取用户信息验证身份  
  158.         AnonymousAuthenticationProvider 匿名用户身份认证  
  159.         RememberMeAuthenticationProvider 已存cookie中的用户信息身份认证 其它的还有  
  160.         AuthByAdapterProvider 使用容器的适配器验证身份 CasAuthenticationProvider  
  161.         根据Yale中心认证服务验证身份, 用于实现单点登陆 JaasAuthenticationProvider  
  162.         从JASS登陆配置中获取用户信息验证身份 RemoteAuthenticationProvider 根据远程服务验证用户身份  
  163.         RunAsImplAuthenticationProvider 对身份已被管理器替换的用户进行验证  
  164.         X509AuthenticationProvider 从X509认证中获取用户信息验证身份  
  165.         TestingAuthenticationProvider 单元测试时使用  
  166.         每个认证者会对自己指定的证明信息进行认证,如DaoAuthenticationProvider仅对UsernamePasswordAuthenticationToken这个证明信息进行认证。  
  167.     -->  
  168.     <bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">  
  169.         <property name="providers">  
  170.             <list>  
  171.                 <ref local="daoAuthenticationProvider" />  
  172.                 <ref local="anonymousAuthenticationProvider" />  
  173.             </list>  
  174.         </property>  
  175.         <!-- <property name="sessionController" ref="concurrentSessionController" /> -->  
  176.     </bean>  
  177.     <bean id="daoAuthenticationProvider"  
  178.         class="org.springframework.security.providers.dao.DaoAuthenticationProvider">  
  179.         <!--  <property name="passwordEncoder" ref="passwordEncoder"></property>-->  
  180.         <property name="userDetailsService" ref="userDetailsService"></property>  
  181.     </bean>  
  182.     <bean id="anonymousAuthenticationProvider"  
  183.         class="org.springframework.security.providers.anonymous.AnonymousAuthenticationProvider">  
  184.         <property name="key" value="springsecurity"></property>  
  185.     </bean>  
  186.     <!-- RemeberMeServices -->  
  187.     <bean id="rememberMeServices"  
  188.         class="org.springframework.security.ui.rememberme.TokenBasedRememberMeServices">  
  189.         <property name="key" value="springsecurity"></property>  
  190.         <property name="userDetailsService" ref="userDetailsService"></property>  
  191.     </bean>  
  192.     <bean id="userDetailsService"  
  193.         class="cn.com.sunjiesh.springmvcdemo.service.security.UserDetailServiceImpl">  
  194.         <property name="userDao" ref="userDao"></property>  
  195.         </bean>  
  196.     <bean id="passwordEncoder"  
  197.         class="org.springframework.security.providers.encoding.Md5PasswordEncoder" />  
  198.     <bean id="loggerListener"  
  199.         class="org.springframework.security.event.authentication.LoggerListener" />  
  200. </beans>  
 

    5)springmvcdemo-servlet.xml

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!--  
  3.     Author Sun Jie 
  4.  -->  
  5. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
  6. <beans>  
  7.   
  8.     <!-- Multi-Action-->  
  9.     <bean id="methodNameResolver"  
  10.         class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">  
  11.         <property name="paramName" value="method" />  
  12.         <property name="defaultMethodName" value="index" />  
  13.     </bean>  
  14.     <!-- View Resolver -->  
  15.     <bean id="viewResolver"  
  16.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  17.         <property name="viewClass"  
  18.             value="org.springframework.web.servlet.view.JstlView" />  
  19.         <property name="prefix" value="/" />  
  20.     </bean>  
  21.     <bean id="adminHandlerMapping"  
  22.         class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">  
  23.         <property name="mappings">  
  24.             <props>  
  25.                 <!-- Add By Sun Jie -->  
  26.                 <prop key="/user/login.do">userLoginController</prop>  
  27.                 <!-- Add By Sun Jie -->  
  28.             </props>  
  29.         </property>  
  30.     </bean>  
  31.       
  32.     <bean id="userLoginController" class="cn.com.sunjiesh.springmvcdemo.web.user.LoginController"  
  33.         autowire="byName">  
  34.         <property name="successView" value="/user/index.jsp" />  
  35.         <property name="errorView" value="" />  
  36.     </bean>  
  37. </beans>  
 

6、页面

Html代码  收藏代码
  1. <%@ page contentType="text/html;charset=gb2312"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3. <%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>  
  4. <%@ page import="org.springframework.security.ui.AbstractProcessingFilter"%>  
  5. <%@ page import="org.springframework.security.ui.webapp.AuthenticationProcessingFilter"%>  
  6. <%@ page import="org.springframework.security.AuthenticationException"%>  
  7.   
  8. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  9. <html xmlns="http://www.w3.org/1999/xhtml">  
  10.     <head>  
  11.         <title>SpringMVCDemo登录页</title>  
  12.         <%@ include file="/common/meta.jsp"%>  
  13.         <script src="${ctx}/js/validate/jquery.validate.js" type="text/javascript"></script>  
  14.         <script src="${ctx}/js/validate/messages_cn.js" type="text/javascript"></script>  
  15.         <script>  
  16.             $(document).ready(function(){  
  17.                 $("#loginForm").validate();  
  18.              });  
  19.         </script>  
  20.     </head>  
  21.     <body>  
  22. <c:set var="ctx" value="${pageContext.request.contextPath}"/>  
  23.         <div id="content">  
  24.             <%  
  25.                 if (session.getAttribute(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY) != null) {  
  26.             %>  
  27.             <span style="color:red"> 登录失败,请重试. </span>  
  28.             <%  
  29.                 }  
  30.             %>  
  31.             <h2>SpringMVCDemo示例</h2>  
  32.             <h3>--CRUD管理界面演示</h3>  
  33.             <form id="loginForm" action="${ctx}/user/j_spring_security_check" method="post">  
  34.                 <table class="inputView">  
  35.                     <tr>  
  36.                         <td>  
  37.                             用户名:  
  38.                         </td>  
  39.                         <td>  
  40.                             <input type='text' name='j_username'  
  41.                                 <c:if test="${not empty param.error}"> value='<%=session.getAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY)%>'</c:if> class="required"/>  
  42.                         </td>  
  43.                     </tr>  
  44.                     <tr>  
  45.                         <td>  
  46.                             密码:  
  47.                         </td>  
  48.                         <td>  
  49.                             <input type='password' name='j_password' class="required" />  
  50.                         </td>  
  51.                     </tr>  
  52.                     <tr>  
  53.                         <td colspan='2'>  
  54.                             <input value="登录" type="submit" />  
  55.                         </td>  
  56.                     </tr>  
  57.                 </table>  
  58.             </form>  
  59.         </div>  
  60.     </body>  
  61. </html>  

 备注:登录页面上的表单action与spring-security中authenticationProcessingFilter过滤器中 的filterProcessesUrl相对应。用户名与输入框的name属性值分别是j_username与j_password。

 

posted @ 2012-03-26 13:25  张良  阅读(3913)  评论(1编辑  收藏  举报