您的位置:首页 > 理论基础 > 计算机网络

spring security源码分析_HttpSessionEventPublisher

2014-11-20 17:20 344 查看
SpringSecurity理解

SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。

SpringSecurity的前身是Acegi,一般来说,如果要对Web资源进行保护,最好的办法莫过于Filter,要想对方法调用进行保护,最好的办法莫过于AOP。Acegi对web资源的保护,就是靠Filter实现的。

一般来说,我们的Filter都是配置在web.xml中,但是Acegi不一样,它在web.xml中配置的只是一个代理,而真正起作用的Filter是作为Bean配置在Spring中的。web.xml中的代理依次调用这些Bean,就实现了对Web资源的保护,同时这些Filter作为Bean被Spring管理,所以实现AOP也很简单,真的是一举两得啊.

SpringSecurity3源码分析

web.xml中监听器:HttpSessionEventPublisher

<listener>

<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>

这个监听器实现了HttpSessionListener接口,主要监听sessionCreated、sessionDestroyed事件。

Java源码

public
class
HttpSessionEventPublisher implements
HttpSessionListener {
    private
static final
String LOGGER_NAME =HttpSessionEventPublisher.class.getName();
 
    ApplicationContextgetContext(ServletContext servletContext) {
        returnWebApplicationContextUtils.getWebApplicationContext(servletContext);
    }
   
    public
void
sessionCreated(HttpSessionEventevent) {
        HttpSessionCreatedEvent e = newHttpSessionCreatedEvent(event.getSession());
        Log log = LogFactory.getLog(LOGGER_NAME);
 
        if (log.isDebugEnabled()) {
            log.debug("Publishing event: " + e);
        }
    //通过ApplicationContext的事件发布机制发布sessionCreated事件
     getContext(event.getSession().getServletContext()).publishEvent(e);
    }
 
    public
void
sessionDestroyed(HttpSessionEventevent) {
        HttpSessionDestroyedEvent e = newHttpSessionDestroyedEvent(event.getSession());
        Log log = LogFactory.getLog(LOGGER_NAME);
 
        if (log.isDebugEnabled()) {
            log.debug("Publishing event: " + e);
        }
    //通过ApplicationContext的事件发布机制发布sessionDestroyed事件
     getContext(event.getSession().getServletContext()).publishEvent(e);
    }
}

 

由于ApplicationContext继承了ApplicationEventPublisher接口,所以ApplicationContext具有发布事件的能力

                                         

Spring中与事件有关的接口和类主要包括ApplicationEvent、ApplicationListener。

定义一个事件的类需要继承ApplicationEvent或者ApplicationContextEvent抽象类。针对一种事件需要特定的监听器,监听器需要实现ApplicationListener接口。当监听器接收到一个事件的时候,就会去执行它的onApplicationEvent()方法。

 

HttpSessionEventPublisher监听器的目的很明显,这个过滤器首先监听session失效的事件(web容器配置的timeout、直接调用session.invalidate方法),然后由SessionRegistryImpl处理session失效事件,从自己维护的集合缓存中清除已经失效的session信息以及session对应的认证实体信息,避免造成oom(OutOfMemory)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息