public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
	private RoleService roleService;
	public RoleService getRoleService() {
		return roleService;
	}
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
	private UrlMatcher urlMatcher = new AntUrlPathMatcher();
	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;	
	public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
	}
        /**
         *采用有参数的构造函数
         *RoleService 是获取资源的类
        **/
	public MyInvocationSecurityMetadataSource(RoleService roleService) {
		this.roleService = roleService;
        loadResourceDefine();
    }	
    private void loadResourceDefine() {
        resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
        List<Role> roles = roleService.findAllRoles();
        if(roles!=null && roles.size()>0){
        	for(Role o:roles){
        		ConfigAttribute ca = new SecurityConfig(o.getName());
        		List<Resource> resources = o.getResources();
        		if(resources!=null && resources.size()>0){
        			for(Resource resource:resources){
        				if(resourceMap.containsKey(resource.getResourceString())){
        					resourceMap.get(resource.getResourceString()).add(ca);
        				}else{
        					Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
        	        		atts.add(ca);
                    		resourceMap.put(resource.getResourceString(), atts);
        				}
        			}
        		}
        	}
        }else{
            ConfigAttribute ca = new SecurityConfig("ROLE_ADMIN");
            Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
            atts.add(ca);
            resourceMap.put("/index.jsp", atts);
            resourceMap.put("/i.jsp", atts);
        }
        /**
        ConfigAttribute ca = new SecurityConfig("ROLE_ADMIN");
        atts.add(ca);
        resourceMap.put("/index.jsp", atts);
        resourceMap.put("/i.jsp", atts);
        */
    }    
	public Collection<ConfigAttribute> getAttributes(Object arg0)
			throws IllegalArgumentException {
        String url = ((FilterInvocation)arg0).getRequestUrl();
        Iterator<String> ite = resourceMap.keySet().iterator();
        while (ite.hasNext()) {
            String resURL = ite.next();
            if (urlMatcher.pathMatchesUrl(url, resURL)) {
                return resourceMap.get(resURL);
            }
        }
        return null;
	}
	public boolean supports(Class<?> arg0) {
		return true;
	}
}
    <!-- 
MyInvocationSecurityMetadataSource 配置修改如下
资源源数据定义,即定义某一资源可以被哪些角色访问 
-->
    <beans:bean id="securityMetadataSource"
        class="com.shoesishow.security.MyInvocationSecurityMetadataSource">
        <beans:constructor-arg><beans:ref bean="roleService"/></beans:constructor-arg> 
    </beans:bean>  
回复  更多评论