首页

事件监听器设计原理流程及常见得监听器使用案例分析,提供源码使用说明及下载

标签:事件监听器,listener,spring,监听器,EventObject,触发器,事件对象,事件源     发布时间:2015-06-29   

事件监听器一般包括事件对象、事件监听器、事件源。事件源注册事件监听器对象,通过向监听器对象发送触发事件,并在监听器对定义事件发生后不同处理流程。

1.事件对象

在jdk中通过提供java.util.EventObject由用户自定义事件对象,例如web项目中HttpSessionEvent会话事件对象源码

package javax.servlet.http;@b@@b@import java.util.EventObject;@b@@b@public class HttpSessionEvent extends EventObject@b@{@b@  public HttpSessionEvent(HttpSession source)@b@  {@b@    super(source);@b@  }@b@@b@  public HttpSession getSession() {@b@    return (HttpSession)super.getSource();@b@  }@b@}

或者对于spring的ApplicationEvent也是类似道理,只是按照业务及系统设计的需要重新定义性质属性,源码如下

import org.springframework.context.ApplicationEvent;@b@@b@public class EntityEvent<E> extends ApplicationEvent@b@{@b@  public static final Type ADD = Type.ADD;@b@  public static final Type UPDATE = Type.UPDATE;@b@  public static final Type DELETE = Type.DELETE;@b@  protected final Type type;@b@  private E oldEntity;@b@@b@  public EntityEvent(E entity, Type type)@b@  {@b@    super(entity);@b@    this.type = type;@b@  }@b@@b@  public EntityEvent(E oldEntity, E newEntity, Type type) {@b@    super(newEntity);@b@    this.oldEntity = oldEntity;@b@    this.type = type;@b@  }@b@@b@  public Type getType() {@b@    return this.type;@b@  }@b@@b@  public E getEntity()@b@  {@b@    return this.source;@b@  }@b@@b@  public E getOldEntity() {@b@    return this.oldEntity;@b@  }@b@@b@  public static enum Type {@b@    ADD, @b@    UPDATE, @b@    DELETE;@b@  }@b@}
public class AuthorityEvent extends EntityEvent<Authority>@b@{@b@ @b@  public AuthorityEvent(Authority auth, EntityEvent.Type type)@b@  {@b@    super(auth, type);@b@  }@b@@b@  public AuthorityEvent(Authority old, Authority auth, EntityEvent.Type type) {@b@    super(old, auth, type);@b@  }@b@}

2.事件监听器

在jdk中提供java.util.EventListener让用户自定义监听器,负责定义事件的调用接口及响应处理流程,源码如下

package javax.servlet.http;@b@@b@import java.util.EventListener;@b@@b@public abstract interface HttpSessionAttributeListener extends EventListener@b@{@b@  public abstract void attributeAdded(HttpSessionBindingEvent paramHttpSessionBindingEvent);@b@@b@  public abstract void attributeRemoved(HttpSessionBindingEvent paramHttpSessionBindingEvent);@b@@b@  public abstract void attributeReplaced(HttpSessionBindingEvent paramHttpSessionBindingEvent);@b@}

用例场景一:统计并记录在线用户数,实现代码如下:

import java.util.ArrayList;@b@import java.util.List;@b@import javax.servlet.ServletContext;@b@import javax.servlet.ServletContextEvent;@b@import javax.servlet.ServletContextListener;@b@import javax.servlet.http.HttpSessionAttributeListener;@b@import javax.servlet.http.HttpSessionBindingEvent;@b@import javax.servlet.http.HttpSessionEvent;@b@import javax.servlet.http.HttpSessionListener;@b@@b@public class OnlineListener implements ServletContextListener,@b@        HttpSessionListener, HttpSessionAttributeListener {@b@    private ServletContext application;@b@    public void sessionCreated(HttpSessionEvent arg0) {@b@    }@b@@b@    public void sessionDestroyed(HttpSessionEvent arg0) {@b@    }@b@@b@    public void attributeAdded(HttpSessionBindingEvent arg0) {@b@        List l = (List) this.application.getAttribute("AllUsers");@b@        l.add(arg0.getValue());@b@    }@b@@b@    public void attributeRemoved(HttpSessionBindingEvent arg0) {@b@        List l = (List) this.application.getAttribute("AllUsers");@b@        l.remove(arg0.getValue());@b@    }@b@@b@    public void attributeReplaced(HttpSessionBindingEvent arg0) {@b@    }@b@@b@    public void contextDestroyed(ServletContextEvent arg0) {@b@    }@b@    public void contextInitialized(ServletContextEvent arg0) {@b@        this.application = arg0.getServletContext();@b@        this.application.setAttribute("AllUsers", new ArrayList());@b@    }@b@}

用例场景二:现定义继承实现业务授权成功的监听器源码,代码如下:

import java.util.Date;@b@import org.apache.commons.logging.Log;@b@import org.apache.commons.logging.LogFactory;@b@import org.springframework.context.ApplicationListener;@b@import org.springframework.security.Authentication;@b@import org.springframework.security.event.authentication.AuthenticationSuccessEvent;@b@@b@public class AuthenticationSuccessListener@b@  implements ApplicationListener<AuthenticationSuccessEvent>@b@{@b@  protected Log log = LogFactory.getLog(AuthenticationSuccessListener.class);@b@@b@  public void onApplicationEvent(AuthenticationSuccessEvent event) {@b@    if ((event instanceof AuthenticationSuccessEvent)) {@b@      this.log.debug("Catch a AuthenticationSuccessEvent");@b@      Object obj = event.getSource();@b@      if ((obj instanceof Authentication)) {@b@        Authentication auth = (Authentication)obj;@b@        this.log.debug("Authentication Details:" + auth.getDetails());@b@@b@        onUserLoginSuccess((UserData)auth.getPrincipal(), HttpServletRequestHolder.getIP());@b@      }@b@    }@b@  }@b@@b@  protected void onUserLoginSuccess(UserData user, String ip) {@b@    Date lastLoginTime = user.getLastLoginTime();@b@@b@    UserLoginProcessor loginProcessor = UserConfig.getLoginProcessor();@b@    if (loginProcessor.supports(user.getClass())) {@b@      loginProcessor.onUserLoginSuccess(user, ip);@b@    }@b@@b@    user.setLastLoginTime(lastLoginTime);@b@  }@b@}

3.事件源

触发事件的源头,不同的事件会在不同用例场景下出发不同的事件类型,完整的用例如下

a.事件对象的定义

import java.util.EventObject;@b@public class DemoEvent extends EventObject {@b@    private static final long serialVersionUID = -2421553409758288940L;@b@    public DemoEvent(Object source) {@b@        super(source);@b@    }@b@}

b.定义两个事件监听器

import java.util.EventListener;@b@public interface DemoEventListener extends EventListener {@b@    public void processEvent(DemoEvent demoEvent);@b@    }@b@}

第一个具体监听器

public class FirstEventListener implements DemoEventListener {@b@    public void processEvent(DemoEvent demoEvent) {@b@        System.out.println("First event listener process event...");@b@    }@b@}

第二个具体监听器

public class SecondEventListener implements DemoEventListener {@b@    public void processEvent(DemoEvent demoEvent) {@b@        System.out.println("Second event listener process event...");@b@    }@b@}

c.定义事件源

public class EventSource {@b@    private List<DemoEventListener> listeners = new ArrayList<DemoEventListener>();@b@    public EventSource() {@b@    }@b@    public void addDemoListener(DemoEventListener demoListener) {@b@        listeners.add(demoListener);@b@    }@b@    public void notifyDemoEvent() {@b@        for (DemoEventListener eventListener : listeners) {@b@            DemoEvent demoEvent = new DemoEvent(this);@b@            eventListener.processEvent(demoEvent);@b@        }@b@    }@b@}

d.测试事件监听器完整的处理过程

public class DemoEventClient {@b@ @b@    public static void main(String args[]) {@b@        //定义事件源@b@        EventSource eventSource = new EventSource();@b@        //定义并向事件源中注册事件监听器@b@        FirstEventListener firstEventListener = new FirstEventListener();@b@        eventSource.addDemoListener(firstEventListener);@b@        //定义并向事件源中注册事件监听器@b@        SecondEventListener secondEventListener=new SecondEventListener();@b@        eventSource.addDemoListener(secondEventListener);@b@        //事件通知@b@        eventSource.notifyDemoEvent();@b@    }@b@}