菜鸟-教你把Acegi应用到实际项目(9)-实现FilterInvocationDefinition

 在实际应用中,开发者有时需要将Web资源授权信息(角色与授权资源之间的定义)存放在RDBMS中,以便更好的管理。事实上,我觉得一般的企业应用都应当如此,因为这样可以使角色和Web资源的管理更灵活,更自由。那么,我们应当如何实现这个需求呢?在接下来的内容当中,我们将一一解说。
      我们都知道,一般Web资源授权信息的配置类似如下代码:

Xml代码 复制代码 收藏代码
  1. <bean id="filterInvocationInterceptor"  
  2.     class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">  
  3.     ……   
  4.     <property name="objectDefinitionSource">  
  5.         <value>  
  6.             <![CDATA[  
  7.                 CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON  
  8.                 PATTERN_TYPE_APACHE_ANT  
  9.                 /secure/**=ROLE_SUPERVISOR  
  10.                 /authenticate/**=ROLE_USER,ROLE_SUPERVISOR  
  11.                 /**=IS_AUTHENTICATED_ANONYMOUSLY  
  12.             ]]>  
  13.         </value>  
  14.     </property>  
  15. </bean>  
<bean id="filterInvocationInterceptor"
	class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
	……
	<property name="objectDefinitionSource">
		<value>
			<![CDATA[
				CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
				PATTERN_TYPE_APACHE_ANT
				/secure/**=ROLE_SUPERVISOR
				/authenticate/**=ROLE_USER,ROLE_SUPERVISOR
				/**=IS_AUTHENTICATED_ANONYMOUSLY
			]]>
		</value>
	</property>
</bean>

      objectDefinitionSource 属性定义发Web资源授权信息(角色与授权资源之间的关系)
      objectDefinitionSource 属性指定了”PATTERN_TYPE_APACHE_ANT”,即希望启用Apache Ant路径风格的URL匹配模式,则FilterInvocationDefinitionSourceEditor会实例化PathBasedFilterInvocationDefinitionMap实例。如果未指定这一字符串,即希望采用默认的正是表达式,则RegExpBasedFilterInvocationDefinitionMap会被实例化。注意,PathBasedFilterInvocationDefinitionMap和RegExpBasedFilterInvocationDefinitionMap都是FilterInvocationDefinitionSource的实现类。

      当Web容器装载Acegi时,Spring会自动找到FilterInvocationDefinitionSourceEditor属性编辑器,并采用它解析上述Web资源授权信息。由于FilterInvocationDefinitionSource同FilterInvocationDefinitionSourceEditor处在同一个Java包中,因此开发者不用显式注册这一属性编辑器,Spring会透明地为开发者考虑到这一切。
      为了能够通过RDBMS维护Web资源授权信息,我们必须提供自身的FilterInvocationDefinitionSource实现类。

      Acegi 安全系统需要记录一些配置信息,这些配置信息用于各种可能的请求。为了存储针对各种不同请求的各种安全配置,就要使用配置属性。在实现上配置属性通过ConfigAttribute接口来表示。SecurityConfig是ConfigAttribute接口的一个具体实现,它简单地把配置属性当作一个串(String)来存储。

      与特定请求相联系的ConfigAttributes 集合保存在ConfigAttributeDefinition中。这个类只是一个简单的ConfigAttributes存储器,并不做其它特别的处理。

      当安全性拦截器收到一个请求时,它需要判断使用哪些配置属性。换句话说,它需要找到用于这种请求的ConfigAttributeDefinition.这种判别是通过ObjectDefinitionSource接口来处理的.这个接口提供的主要方法是 public ConfigAttributeDefinition getAttributes(Object object),其中的Object 就是要保护的安全对象。因为安全对象包含了请求的细节,所以ObjectDefinitionSource实现类将能够抽取它所需要的细节来检查相关的ConfigAttributeDefinition。

 1、 增加Web资源授权信息表

Sql代码 复制代码 收藏代码
  1. create table webresdb(   
  2.     id bigint not null primary key,   
  3.     url varchar(60) not null,   
  4.     roles varchar(100) not null  
  5. );   
  6. INSERT INTO WEBRESDB VALUES(1,'/secure/**','ROLE_SUPERVISOR')   
  7. INSERT INTO WEBRESDB VALUES(2,'/authenticate/**','ROLE_USER,ROLE_SUPERVISOR')   
  8. INSERT INTO WEBRESDB VALUES(3,'/**','IS_AUTHENTICATED_ANONYMOUSLY')  
create table webresdb(
	id bigint not null primary key,
	url varchar(60) not null,
	roles varchar(100) not null
);
INSERT INTO WEBRESDB VALUES(1,'/secure/**','ROLE_SUPERVISOR')
INSERT INTO WEBRESDB VALUES(2,'/authenticate/**','ROLE_USER,ROLE_SUPERVISOR')
INSERT INTO WEBRESDB VALUES(3,'/**','IS_AUTHENTICATED_ANONYMOUSLY')

2、增加类似于EntryHolder的辅助类RdbmsEntryHolder
      通过分析PathBasedFilterInvocationDefinitionMap类,我们发现,对于每行Web  资源授权需求,比如“/secure/**=ROLE_SUPERVISOR”,它会借助于内部类EntryHolder存储各行内容。EntryHolder暴露了antPath和configAttributeDefinition属性,前者存储类似“/secure/**”的内容,而后者会通过configAttributeDefinition对象存储类似“ROLE_USER,ROLE_SUPERVISOR”的内容。在ConfigAttributeDefinition对象内部,它将各个角色拆分开,并分别借助SecurityConfig对象存储它们,即ROLE_USER和ROLE_SUPERVISOR,从而保存在configAttributes私有变量中。
      在此,我们提供了类似于EntryHolder的辅助类:

Java代码 复制代码 收藏代码
  1. public class RdbmsEntryHolder implements Serializable {   
  2.     private static final long serialVersionUID = 2317309106087370323L;   
  3.     // 保护的URL模式   
  4.     private String url;   
  5.     // 要求的角色集合   
  6.     private ConfigAttributeDefinition cad;   
  7.     public String getUrl() {   
  8.         return url;   
  9.     }   
  10.     public ConfigAttributeDefinition getCad() {   
  11.         return cad;   
  12.     }   
  13.     public void setUrl(String url) {   
  14.         this.url = url;   
  15.     }   
  16.     public void setCad(ConfigAttributeDefinition cad) {   
  17.         this.cad = cad;   
  18.     }   
  19.   
  20. }  
public class RdbmsEntryHolder implements Serializable {
	private static final long serialVersionUID = 2317309106087370323L;
	// 保护的URL模式
	private String url;
	// 要求的角色集合
	private ConfigAttributeDefinition cad;
	public String getUrl() {
		return url;
	}
	public ConfigAttributeDefinition getCad() {
		return cad;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public void setCad(ConfigAttributeDefinition cad) {
		this.cad = cad;
	}

}

3、增加从RDBMS装载所有的Web资源授权信息的类

Java代码 复制代码 收藏代码
  1. public class RdbmsSecuredUrlDefinition extends MappingSqlQuery{   
  2.   
  3.     protected static final Log logger = LogFactory.getLog(RdbmsSecuredUrlDefinition.class);   
  4.        
  5.     protected RdbmsSecuredUrlDefinition(DataSource ds) {   
  6.         super(ds, Constants.ACEGI_RDBMS_SECURED_SQL);   
  7.         logger.debug("进入到RdbmsInvocationDefinition构建器中.........");   
  8.            
  9.         compile();   
  10.     }   
  11.   
  12.     /**  
  13.      * convert each row of the ResultSet into an object of the result type.  
  14.      */  
  15.     protected Object mapRow(ResultSet rs, int rownum)   
  16.         throws SQLException {   
  17.         logger.debug("抽取webresdb中的记录.........");   
  18.            
  19.         RdbmsEntryHolder rsh = new RdbmsEntryHolder();   
  20.         // 设置URL   
  21.         rsh.setUrl(rs.getString(Constants.ACEGI_RDBMS_SECURED_URL).trim());   
  22.            
  23.         ConfigAttributeDefinition cad = new ConfigAttributeDefinition();   
  24.            
  25.         String rolesStr = rs.getString(Constants.ACEGI_RDBMS_SECURED_ROLES).trim();   
  26.         // commaDelimitedListToStringArray:Convert a CSV list into an array of Strings   
  27.         // 以逗号为分割符, 分割字符串   
  28.         String[] tokens =    
  29.                 StringUtils.commaDelimitedListToStringArray(rolesStr); // 角色名数组   
  30.         // 构造角色集合   
  31.         for(int i = 0; i < tokens.length;++i)   
  32.             cad.addConfigAttribute(new SecurityConfig(tokens[i]));   
  33.            
  34.         //设置角色集合   
  35.         rsh.setCad(cad);   
  36.            
  37.         return rsh;   
  38.     }   
  39.   
  40. }  
public class RdbmsSecuredUrlDefinition extends MappingSqlQuery{

	protected static final Log logger = LogFactory.getLog(RdbmsSecuredUrlDefinition.class);
	
    protected RdbmsSecuredUrlDefinition(DataSource ds) {
        super(ds, Constants.ACEGI_RDBMS_SECURED_SQL);
    	logger.debug("进入到RdbmsInvocationDefinition构建器中.........");
    	
        compile();
    }

    /**
     * convert each row of the ResultSet into an object of the result type.
     */
    protected Object mapRow(ResultSet rs, int rownum)
        throws SQLException {
    	logger.debug("抽取webresdb中的记录.........");
    	
    	RdbmsEntryHolder rsh = new RdbmsEntryHolder();
    	// 设置URL
    	rsh.setUrl(rs.getString(Constants.ACEGI_RDBMS_SECURED_URL).trim());
    	
        ConfigAttributeDefinition cad = new ConfigAttributeDefinition();
        
        String rolesStr = rs.getString(Constants.ACEGI_RDBMS_SECURED_ROLES).trim();
        // commaDelimitedListToStringArray:Convert a CSV list into an array of Strings
        // 以逗号为分割符, 分割字符串
        String[] tokens = 
        		StringUtils.commaDelimitedListToStringArray(rolesStr); // 角色名数组
        // 构造角色集合
        for(int i = 0; i < tokens.length;++i)
        	cad.addConfigAttribute(new SecurityConfig(tokens[i]));
        
        //设置角色集合
        rsh.setCad(cad);
    	
        return rsh;
    }

}

      这样,我们可以利用RdbmsSecuredUrlDefinition将webresdb中的各行记录组装成RdbmsEntryHolder对象,进而返回RdbmsEntryHolder集合给调用者。

4、增加FilterInvocationDefinitionSource的实现类

Java代码 复制代码 收藏代码
  1. /**  
  2.  * FilterInvocationDefinitionSource实现类1  
  3.  *   
  4.  * @author qiuzj  
  5.  *   
  6.  */  
  7. public class RdbmsFilterInvocationDefinitionSource extends JdbcDaoSupport   
  8.         implements FilterInvocationDefinitionSource {   
  9.   
  10.     protected static final Log logger = LogFactory.getLog(RdbmsFilterInvocationDefinitionSource.class);   
  11.        
  12.     private RdbmsSecuredUrlDefinition rdbmsInvocationDefinition;   
  13.   
  14.     private PathMatcher pathMatcher = new AntPathMatcher();   
  15.        
  16.     private Ehcache webresdbCache;   
  17.        
  18.     /**  
  19.      * 实现ObjectDefinitionSource接口的方法  
  20.      * 最核心的方法, 几乎可以认为RdbmsFilterInvocationDefinitionSource的其他大部分方法都是为这一方法服务的  
  21.      *   
  22.      * Accesses the <code>ConfigAttributeDefinition</code> that applies to a given secure object.<P>Returns  
  23.      * <code>null</code> if no <code>ConfigAttribiteDefinition</code> applies.</p>  
  24.      *  
  25.      * @param object the object being secured  
  26.      *  
  27.      * @return the <code>ConfigAttributeDefinition</code> that applies to the passed object  
  28.      * @返回 适用于传入对象的ConfigAttributeDefinition(角色集合)  
  29.      *  
  30.      * @throws IllegalArgumentException if the passed object is not of a type supported by the  
  31.      *         <code>ObjectDefinitionSource</code> implementation  
  32.      */  
  33.     public ConfigAttributeDefinition getAttributes(Object object)   
  34.             throws IllegalArgumentException {   
  35.         if ((object == null) || !this.supports(object.getClass())) {   
  36.             throw new IllegalArgumentException("抱歉,目标对象不是FilterInvocation类型");   
  37.         }   
  38.   
  39.         // 抽取出待请求的URL   
  40.         String url = ((FilterInvocation) object).getRequestUrl();   
  41.         logger.info("待请示的URL: " + url);   
  42.            
  43.         // 获取所有RdbmsEntryHolder列表(url与角色集合对应列表)   
  44.         List list = this.getRdbmsEntryHolderList();   
  45.         if (list == null || list.size() == 0)   
  46.             return null;   
  47.   
  48.         // 去掉待请求url参数信息   
  49.         int firstQuestionMarkIndex = url.indexOf("?");   
  50.         if (firstQuestionMarkIndex != -1) {   
  51.             url = url.substring(0, firstQuestionMarkIndex);   
  52.         }   
  53.   
  54.         Iterator iter = list.iterator();   
  55.         // 循环判断用户是否有权限访问当前url, 有则返回ConfigAttributeDefinition(角色集合)   
  56.         while (iter.hasNext()) {   
  57.             RdbmsEntryHolder entryHolder = (RdbmsEntryHolder) iter.next();   
  58.             // 判断当前访问的url是否符合entryHolder.getUrl()模式, 即判断用户是否有权限访问当前url   
  59.             // 如url="/secure/index.jsp", entryHolder.getUrl()="/secure/**", 则有权限访问   
  60.             boolean matched = pathMatcher.match(entryHolder.getUrl(), url);   
  61.   
  62.             if (logger.isDebugEnabled()) {   
  63.                 logger.debug("匹配到如下URL: '" + url + ";模式为 "  
  64.                         + entryHolder.getUrl() + ";是否被匹配:" + matched);   
  65.             }   
  66.   
  67.             // 如果在用户所有被授权的URL中能找到匹配的, 则返回该ConfigAttributeDefinition(角色集合)   
  68.             if (matched) {   
  69.                 return entryHolder.getCad();   
  70.             }   
  71.         }   
  72.   
  73.         return null;   
  74.     }   
  75.   
  76.     /**   
  77.      * 实现接口方法   
  78.      *    
  79.      * If available, all of the <code>ConfigAttributeDefinition</code>s defined by the implementing class.<P>This   
  80.      * is used by the {@link AbstractSecurityInterceptor} to perform startup time validation of each   
  81.      * <code>ConfigAttribute</code> configured against it.</p>   
  82.      *   
  83.      * @return an iterator over all the <code>ConfigAttributeDefinition</code>s or <code>null</code> if unsupported   
  84.      * @返回 ConfigAttributeDefinition迭代集合(Iterator)   
  85.      */   
  86.     public Iterator getConfigAttributeDefinitions() {   
  87.         Set set = new HashSet();   
  88.         Iterator iter = this.getRdbmsEntryHolderList().iterator();   
  89.   
  90.         while (iter.hasNext()) {   
  91.             RdbmsEntryHolder entryHolder = (RdbmsEntryHolder) iter.next();   
  92.             set.add(entryHolder.getCad());   
  93.         }   
  94.   
  95.         return set.iterator();   
  96.     }   
  97.   
  98.     /**  
  99.      * 实现接口方法, 检验传入的安全对象是否是与FilterInvocation类相同类型, 或是它的子类  
  100.      * getAttributes(Object object)方法会调用这个方法  
  101.      * 保证String url = ((FilterInvocation) object).getRequestUrl();的正确性  
  102.      *   
  103.      * Indicates whether the <code>ObjectDefinitionSource</code> implementation is able to provide  
  104.      * <code>ConfigAttributeDefinition</code>s for the indicated secure object type.  
  105.      *  
  106.      * @param clazz the class that is being queried  
  107.      *  
  108.      * @return true if the implementation can process the indicated class  
  109.      */  
  110.     public boolean supports(Class clazz) {   
  111.         if (FilterInvocation.class.isAssignableFrom(clazz)) {   
  112.             return true;   
  113.         } else {   
  114.             return false;   
  115.         }   
  116.     }   
  117.   
  118.     /**  
  119.      * 覆盖JdbcDaoSupport中的方法, 用于将数据源传入RdbmsSecuredUrlDefinition中  
  120.      * JdbcDaoSupport实现了InitializingBean接口, 该接口中的afterPropertiesSet()方法  
  121.      * 用于在所有spring bean属性设置完毕后做一些初始化操作, BeanFactory会负责调用它  
  122.      * 而在JdbcDaoSupport的实现中, afterPropertiesSet()方法调用了initDao()方法, 故我们  
  123.      * 借此做一些初始化操作.   
  124.      * 在此用于将数据源传入RdbmsSecuredUrlDefinition中  
  125.      */  
  126.     protected void initDao() throws Exception {   
  127.         logger.info("第一个执行的方法: initDao()");   
  128.         this.rdbmsInvocationDefinition =    
  129.                 new RdbmsSecuredUrlDefinition(this.getDataSource()); // 传入数据源, 此数据源由Spring配置文件注入   
  130.         if (this.webresdbCache == null)   
  131.             throw new IllegalArgumentException("必须为RdbmsFilterInvocationDefinitionSource配置一EhCache缓存");   
  132.     }   
  133.   
  134.     /**  
  135.      * 获取所有RdbmsEntryHolder列表(url与角色集合对应列表)  
  136.      *   
  137.      * @return  
  138.      */  
  139.     private List getRdbmsEntryHolderList(){   
  140.         List list = null;   
  141.         Element element = this.webresdbCache.get("webres");   
  142.            
  143.         if (element != null){ // 如果缓存中存在RdbmsEntryHolder列表, 则直接获取返回   
  144.             list = (List) element.getValue();   
  145.         } else { // 如果缓存中不存在RdbmsEntryHolder列表, 则重新查询, 并放到缓存中   
  146.             list = this.rdbmsInvocationDefinition.execute();   
  147.             Element elem = new Element("webres", list);   
  148.             this.webresdbCache.put(elem);   
  149.         }   
  150.         //list = this.rdbmsInvocationDefinition.execute();   
  151.         return list;   
  152.     }   
  153.        
  154.     /**  
  155.      * 用于Spring注入  
  156.      *   
  157.      * @param webresdbCache  
  158.      */  
  159.     public void setWebresdbCache(Ehcache webresdbCache) {   
  160.         this.webresdbCache = webresdbCache;   
  161.     }   
  162.        
  163. }  
/**
 * FilterInvocationDefinitionSource实现类1
 * 
 * @author qiuzj
 * 
 */
public class RdbmsFilterInvocationDefinitionSource extends JdbcDaoSupport
		implements FilterInvocationDefinitionSource {

	protected static final Log logger = LogFactory.getLog(RdbmsFilterInvocationDefinitionSource.class);
	
	private RdbmsSecuredUrlDefinition rdbmsInvocationDefinition;

	private PathMatcher pathMatcher = new AntPathMatcher();
	
	private Ehcache webresdbCache;
	
	/**
	 * 实现ObjectDefinitionSource接口的方法
	 * 最核心的方法, 几乎可以认为RdbmsFilterInvocationDefinitionSource的其他大部分方法都是为这一方法服务的
	 * 
     * Accesses the <code>ConfigAttributeDefinition</code> that applies to a given secure object.<P>Returns
     * <code>null</code> if no <code>ConfigAttribiteDefinition</code> applies.</p>
     *
     * @param object the object being secured
     *
     * @return the <code>ConfigAttributeDefinition</code> that applies to the passed object
     * @返回 适用于传入对象的ConfigAttributeDefinition(角色集合)
     *
     * @throws IllegalArgumentException if the passed object is not of a type supported by the
     *         <code>ObjectDefinitionSource</code> implementation
     */
	public ConfigAttributeDefinition getAttributes(Object object)
			throws IllegalArgumentException {
		if ((object == null) || !this.supports(object.getClass())) {
			throw new IllegalArgumentException("抱歉,目标对象不是FilterInvocation类型");
		}

		// 抽取出待请求的URL
		String url = ((FilterInvocation) object).getRequestUrl();
		logger.info("待请示的URL: " + url);
		
		// 获取所有RdbmsEntryHolder列表(url与角色集合对应列表)
		List list = this.getRdbmsEntryHolderList();
		if (list == null || list.size() == 0)
			return null;

		// 去掉待请求url参数信息
		int firstQuestionMarkIndex = url.indexOf("?");
		if (firstQuestionMarkIndex != -1) {
			url = url.substring(0, firstQuestionMarkIndex);
		}

		Iterator iter = list.iterator();
		// 循环判断用户是否有权限访问当前url, 有则返回ConfigAttributeDefinition(角色集合)
		while (iter.hasNext()) {
			RdbmsEntryHolder entryHolder = (RdbmsEntryHolder) iter.next();
			// 判断当前访问的url是否符合entryHolder.getUrl()模式, 即判断用户是否有权限访问当前url
			// 如url="/secure/index.jsp", entryHolder.getUrl()="/secure/**", 则有权限访问
			boolean matched = pathMatcher.match(entryHolder.getUrl(), url);

			if (logger.isDebugEnabled()) {
				logger.debug("匹配到如下URL: '" + url + ";模式为 "
						+ entryHolder.getUrl() + ";是否被匹配:" + matched);
			}

			// 如果在用户所有被授权的URL中能找到匹配的, 则返回该ConfigAttributeDefinition(角色集合)
			if (matched) {
				return entryHolder.getCad();
			}
		}

		return null;
	}

	/**
	 * 实现接口方法
	 * 
     * If available, all of the <code>ConfigAttributeDefinition</code>s defined by the implementing class.<P>This
     * is used by the {@link AbstractSecurityInterceptor} to perform startup time validation of each
     * <code>ConfigAttribute</code> configured against it.</p>
     *
     * @return an iterator over all the <code>ConfigAttributeDefinition</code>s or <code>null</code> if unsupported
     * @返回 ConfigAttributeDefinition迭代集合(Iterator)
     */
	public Iterator getConfigAttributeDefinitions() {
        Set set = new HashSet();
        Iterator iter = this.getRdbmsEntryHolderList().iterator();

        while (iter.hasNext()) {
        	RdbmsEntryHolder entryHolder = (RdbmsEntryHolder) iter.next();
            set.add(entryHolder.getCad());
        }

        return set.iterator();
	}

	/**
	 * 实现接口方法, 检验传入的安全对象是否是与FilterInvocation类相同类型, 或是它的子类
	 * getAttributes(Object object)方法会调用这个方法
	 * 保证String url = ((FilterInvocation) object).getRequestUrl();的正确性
	 * 
     * Indicates whether the <code>ObjectDefinitionSource</code> implementation is able to provide
     * <code>ConfigAttributeDefinition</code>s for the indicated secure object type.
     *
     * @param clazz the class that is being queried
     *
     * @return true if the implementation can process the indicated class
     */
	public boolean supports(Class clazz) {
		if (FilterInvocation.class.isAssignableFrom(clazz)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 覆盖JdbcDaoSupport中的方法, 用于将数据源传入RdbmsSecuredUrlDefinition中
	 * JdbcDaoSupport实现了InitializingBean接口, 该接口中的afterPropertiesSet()方法
	 * 用于在所有spring bean属性设置完毕后做一些初始化操作, BeanFactory会负责调用它
	 * 而在JdbcDaoSupport的实现中, afterPropertiesSet()方法调用了initDao()方法, 故我们
	 * 借此做一些初始化操作. 
	 * 在此用于将数据源传入RdbmsSecuredUrlDefinition中
	 */
	protected void initDao() throws Exception {
		logger.info("第一个执行的方法: initDao()");
		this.rdbmsInvocationDefinition = 
				new RdbmsSecuredUrlDefinition(this.getDataSource()); // 传入数据源, 此数据源由Spring配置文件注入
		if (this.webresdbCache == null)
			throw new IllegalArgumentException("必须为RdbmsFilterInvocationDefinitionSource配置一EhCache缓存");
	}

	/**
	 * 获取所有RdbmsEntryHolder列表(url与角色集合对应列表)
	 * 
	 * @return
	 */
	private List getRdbmsEntryHolderList(){
		List list = null;
		Element element = this.webresdbCache.get("webres");
		
		if (element != null){ // 如果缓存中存在RdbmsEntryHolder列表, 则直接获取返回
			list = (List) element.getValue();
		} else { // 如果缓存中不存在RdbmsEntryHolder列表, 则重新查询, 并放到缓存中
			list = this.rdbmsInvocationDefinition.execute();
			Element elem = new Element("webres", list);
			this.webresdbCache.put(elem);
		}
		//list = this.rdbmsInvocationDefinition.execute();
		return list;
	}
	
	/**
	 * 用于Spring注入
	 * 
	 * @param webresdbCache
	 */
	public void setWebresdbCache(Ehcache webresdbCache) {
		this.webresdbCache = webresdbCache;
	}
	
}

      由于RdbmsFilterInvocationDefinitionSource是针对Web资源的,因此它实现的supports()方法需要评估FilterInvocation对象。另外,为了减少同RDBMS的交互次数,我们启用了Spring EhCache服务。

 5、通过Spring DI注入RdbmsFilterInvocationDefinitionSource

Xml代码 复制代码 收藏代码
  1. <bean id="filterInvocationInterceptor"  
  2.     class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">  
  3.     ......   
  4.     <property name="objectDefinitionSource"  
  5.         ref="rdbmsFilterInvocationDefinitionSource" />  
  6. </bean>  
  7.   
  8. <bean id="rdbmsFilterInvocationDefinitionSource"  
  9.     class="sample.RdbmsFilterInvocationDefinitionSource">  
  10.     <property name="dataSource" ref="dataSource" />  
  11.     <property name="webresdbCache" ref="webresCacheBackend" />  
  12. </bean>  
  13.   
  14. <bean id="webresCacheBackend"  
  15.     class="org.springframework.cache.ehcache.EhCacheFactoryBean">  
  16.     <property name="cacheManager">  
  17.         <ref local="cacheManager" />  
  18.     </property>  
  19.     <property name="cacheName">  
  20.         <value>webresdbCache</value>  
  21.     </property>  
  22. </bean>  
<bean id="filterInvocationInterceptor"
	class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
	......
	<property name="objectDefinitionSource"
		ref="rdbmsFilterInvocationDefinitionSource" />
</bean>

<bean id="rdbmsFilterInvocationDefinitionSource"
	class="sample.RdbmsFilterInvocationDefinitionSource">
	<property name="dataSource" ref="dataSource" />
	<property name="webresdbCache" ref="webresCacheBackend" />
</bean>

<bean id="webresCacheBackend"
	class="org.springframework.cache.ehcache.EhCacheFactoryBean">
	<property name="cacheManager">
		<ref local="cacheManager" />
	</property>
	<property name="cacheName">
		<value>webresdbCache</value>
	</property>
</bean>

 6、运行说明
 下载源代码,我提供了相应脚本,存放在Acegi8WebRoot dbms目录下。
1)、在rdbms目录下运行server.bat文件,启动hsqldb数据库。关于hsqldb的使用说明,请参考“菜鸟-手把手教你把Acegi应用到实际项目中(6)” http://zhanjia.iteye.com/blog/258282
 2)、运行Acegi8项目
 3)、用户名为javaee、qiuzj,密码为password

      至此,我们此节所讲的内容已结束,大家可以下载源代码以便调试。另外,代码中还提供了另一个版本的实现类RdbmsFilterInvocationDefinitionSourceVersion2,它继承了AbstractFilterInvocationDefinitionSource,在一定程序上减少了代码量,朋友们可以自行研究。

7、其他说明
开发环境:
MyEclipse 5.0GA
Eclipse3.2.1
JDK1.5.0_10
tomcat5.5.23
acegi-security-1.0.7
Spring2.0


Jar包:
acegi-security-1.0.7.jar
Spring.jar(2.0.8)
commons-codec.jar
jstl.jar (1.1)
standard.jar
commons-logging.jar(1.0)
hsqldb.jar(1.8.0.10)
log4j-1.2.13.jar
ehcache-1.3.0.jar

 更正注释, 红色部分为更改后的注释:

// 循环判断是否对当前url设置了安全角色访问机制, 有则返回相应的ConfigAttributeDefinition(角色集合), 否则返回null

Java代码 复制代码 收藏代码
  1. while (iter.hasNext()) {   
  2.     RdbmsEntryHolder entryHolder = (RdbmsEntryHolder) iter.next();   
  3.     boolean matched = pathMatcher.match(entryHolder.getUrl(), url);   
  4.   
  5.     if (logger.isDebugEnabled()) {   
  6.         logger.debug("匹配到如下URL: '" + url + ";模式为 "  
  7.                 + entryHolder.getUrl() + ";是否被匹配:" + matched);   
  8.     }   
  9.   
  10.     if (matched) {   
  11.         return entryHolder.getCad();   
  12.     }   
  13. }  
while (iter.hasNext()) {
	RdbmsEntryHolder entryHolder = (RdbmsEntryHolder) iter.next();
	boolean matched = pathMatcher.match(entryHolder.getUrl(), url);

	if (logger.isDebugEnabled()) {
		logger.debug("匹配到如下URL: '" + url + ";模式为 "
				+ entryHolder.getUrl() + ";是否被匹配:" + matched);
	}

	if (matched) {
		return entryHolder.getCad();
	}
}
原文地址:https://www.cnblogs.com/wzh123/p/3393008.html