监听器的使用
Java的事件监听机制
1、事件监听涉及到三个组件:事件源、事件参数对象、事件监听器
2、当事件源上发生某一个动作时,它会调用事件监听器的一个方法,并在调用该方法时把事件参数对象传递进去,
开发人员在监听器中通过事件参数对象,就可以拿到事件源,从而对事件源进行操作。 案例一:GUI编程中监听机制
public static void main(String[] args) {Frame f = new Frame();f.setSize(400, 400);f.setVisible(true);f.addWindowListener(new WindowListener(){public void windowActivated(WindowEvent e) {// TODO Auto-generated method stub}public void windowClosed(WindowEvent e) {// TODO Auto-generated method stub}public void windowClosing(WindowEvent e) {Frame f = (Frame) e.getSource();f.dispose();}public void windowDeactivated(WindowEvent e) {// TODO Auto-generated method stub}public void windowDeiconified(WindowEvent e) {// TODO Auto-generated method stub}public void windowIconified(WindowEvent e) {// TODO Auto-generated method stub}public void windowOpened(WindowEvent e) {// TODO Auto-generated method stub}});}
案例二:观察者设计模式的实现
//设计一个事件源,被监听器监听 Observer(观察者设计模式)
public class Demo2 {/*** @param args*/public static void main(String[] args) {Person p = new Person();p.registerListener(new PersonListener(){public void doeat(Event e) {Person p = (Person)e.getSource();System.out.println(p.getName() + "吃啥呢");}public void dorun(Event e) {Person p = (Person)e.getSource();System.out.println(p.getName() + "减肥呢");}});p.eat();}}class Person{private String name;private PersonListener listener;public String getName(){return name;}public void setName(String name){this.name=name;}public void eat(){System.out.println(name+"要吃东西了...");if(listener!=null){listener.doeat(new Event(this));}}public void run(){System.out.println(name+"要跑步了...");if(listener!=null){listener.dorun(new Event(this));}}public void registerListener(PersonListener listener){this.listener = listener;}
}interface PersonListener{public void doeat(Event e);public void dorun(Event e);}class Event{private Object source;public Event() {super();// TODO Auto-generated constructor stub}public Event(Person source) {super();this.source = source;}public Object getSource() {return source;}public void setSource(Object source) {this.source = source;}}
什么是监听器
监听器用于监听web应用中某些对象(request,session,application)、信息的创建、销毁、增加,修改,删除等动作的发生,然后作出相应的响应处理。当范围对象的状态发生变化的时候,服务器自动调用监听器对象中的方法。常用于统计访问人数和在线用户,系统加载时进行信息初始化,统计网站的访问量等等。
监听器类型
生命周期监听器:
1 ServletContext上下文监听器
ServletContextListener接口内部方法:初始化:contextInitialized销毁:contextDestroyed
2 Session监听器
HttpSessionListener内部方法:sessionCreated:监听Session对象的创建sessionDestroyed:监听Session对象的销毁
3 request监听器
ServletRequestListener监听request对象的初始化和销毁内部方法:1、requestInitialized:监听request对象的初始化2、requestDestroyed:监听request对象的销毁
2.2.2属性变化监听器:
1 ServletContext属性变化监听器
ServletContextAttributeListener接口 内部的方法: attributeAdded:监听属性的添加 attributeRemoved:监听属性的移除 attributeReplaced:监听属性的修改
2 session属性变化监听器
HttpSessionAttributeListener监听HttpSession的内容的变化内部的方法:attributeAdded:监听属性的添加attributeRemoved:监听属性的移除attributeReplaced:监听属性的修改
3 request属性变化监听器
ServletRequestAttributeListener监听属性内容变化内部方法:attributeAdded:监听属性的添加attributeRemoved:监听属性的移除attributeReplaced:监听属性的修改
感知型监听器:
1 对象从session添加或移除
HttpSessionBindingListener监听对象的添加和移除内部方法:valueBound:监听对象的绑定valueUnbound:监听对象的解除绑定
2 对象钝化和活化
HttpSessionActivationListener监听session的钝化和活化内部方法:sessionWillPassivate:监听Session内部存储对象的钝化-写入sessionDidActivate:监听Session内部存储对象的活化-读取对应类需要实现序列化接口Serializable在 web目录下创建META-INF文件夹,在META-INF文件夹中创建context.xml文件
<?xml version='1.0' encoding='utf-8'?>
<Context><Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="60"><Store className="org.apache.catalina.session.FileStore" directory="qf"> </Store>
</Manager>
</Context>
<!-- maxIdleSwap: session中的对象最大多长时间不使用就被钝化 (秒单位,但是时间不是太准确) -->
<!-- directory: 钝化后的对象的文件写到磁盘的哪个目录下 -->
<!-- 配置钝化的对象文件在${TOMCAT_HOME}/work/Catalina/localhost/YOUR_PROJECT/qf -->
监听器的2种配置
xml的配置
在web.xml中进行配置
<listener>
<!--直接写出自定义的监听器的类名即可--><listener-class>com.qf.web.listener.RequestLeftListener</listener-class>
</listener>
注解式配置
Servlet3.0之后新增的,使用注解@WebListener进行监听器的注册
代码实现
ServletContext的监听器:
a. 实现ServletContext生命周期的监听
/*** Application Lifecycle Listener implementation class FirstListener*监听ServletContext的初始化和销毁*/
@WebListener//注解式注册
public class ApplicationListener implements ServletContextListener {/*** Default constructor. */public ApplicationLeftListener() {// TODO Auto-generated constructor stub}/*** @see ServletContextListener#contextDestroyed(ServletContextEvent)* 销毁*/public void contextDestroyed(ServletContextEvent sce) { // TODO Auto-generated method stubSystem.out.println("网站被销毁了"+sce.getServletContext().hashCode());}/*** @see ServletContextListener#contextInitialized(ServletContextEvent)* 初始化*/public void contextInitialized(ServletContextEvent sce) { // TODO Auto-generated method stubSystem.out.println("网站初始化完成"+sce.getServletContext().hashCode());sce.getServletContext().setAttribute("fwrs", 0);}
}
b. ServletContext属性内容的变化
/*** Application Lifecycle Listener implementation class ApplicationAttributeListener* 实现ServletContext属性内容变化*/
@WebListener
public class ApplicationAttributeListener implements ServletContextAttributeListener {/*** Default constructor. */public ApplicationAttributeListener() {// TODO Auto-generated constructor stub}/*** @see ServletContextAttributeListener#attributeAdded(ServletContextAttributeEvent)* 新增内容*/public void attributeAdded(ServletContextAttributeEvent event) { // TODO Auto-generated method stubSystem.out.println("attributeAdded:"+event.getName());}/*** @see ServletContextAttributeListener#attributeRemoved(ServletContextAttributeEvent)* 删除属性内容*/public void attributeRemoved(ServletContextAttributeEvent event) { // TODO Auto-generated method stubSystem.out.println("attributeRemoved:"+event.getName());}/*** @see ServletContextAttributeListener#attributeReplaced(ServletContextAttributeEvent)* 修改内容*/public void attributeReplaced(ServletContextAttributeEvent event) { // TODO Auto-generated method stubSystem.out.println("attributeReplaced:"+event.getName());}
}
HttpSession监听器
a. 实现HttpSession生命周期的变化和属性内容的变化和id变化
/*** Application Lifecycle Listener implementation class SessionLeftListener* 该监听器实现HttpSession的生命周期变化和属性内容的变化**/
@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener{/*** Default constructor. */public SessionLeftListener() {// TODO Auto-generated constructor stub}/*** @see HttpSessionListener#sessionCreated(HttpSessionEvent)* Session的创建*/public void sessionCreated(HttpSessionEvent se) { // TODO Auto-generated method stubSystem.out.println("sessionCreated");int ct=(int) se.getSession().getServletContext().getAttribute("fwrs");se.getSession().getServletContext().setAttribute("fwrs", ++ct);se.getSession().setAttribute("tea", new Teacher("西施"));}/*** @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)* Session的销毁*/public void sessionDestroyed(HttpSessionEvent se) { // TODO Auto-generated method stubSystem.out.println("sessionDestroyed");}/*** @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)* Session中属性内容的添加*/public void attributeAdded(HttpSessionBindingEvent event) { // TODO Auto-generated method stub}/*** @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)* Session中属性内容的移除*/public void attributeRemoved(HttpSessionBindingEvent event) { // TODO Auto-generated method stub}/*** @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)* Session中属性内容的修改*/public void attributeReplaced(HttpSessionBindingEvent event) { // TODO Auto-generated method stub}//监听HttpSession的id的变化,Servlet3.1新特性@Overridepublic void sessionIdChanged(HttpSessionEvent event, String oldSessionId) {// TODO Auto-generated method stub}
}
案例:实现访问人数统计
public class VisitCountListener implements HttpSessionListener {@Overridepublic void sessionCreated(HttpSessionEvent se) {//负责人数增加ServletContext application=se.getSession().getServletContext();Integer count=(Integer)application.getAttribute("count");if(count==null){application.setAttribute("count", 1);}else{application.setAttribute("count", count+1);}System.out.println("人数增加了");}@Overridepublic void sessionDestroyed(HttpSessionEvent se) {//负责人数的减少ServletContext application=se.getSession().getServletContext();Integer count=(Integer)application.getAttribute("count");application.setAttribute("count", count-1);System.out.println("人数减少了");}}
ServletRequest监听器
a. 监听ServletRequest生命周期和属性内容变化
/*** Application Lifecycle Listener implementation class RequestLeftListener*监听Request对象的内容*/
//@WebListener
public class RequestListener implements ServletRequestAttributeListener,ServletRequestListener {/*** Default constructor. */public RequestLeftListener() {// TODO Auto-generated constructor stub}/*** @see ServletRequestListener#requestInitialized(ServletRequestEvent)* 请求对象的初始化*/public void requestInitialized(ServletRequestEvent sre) { // TODO Auto-generated method stub}/*** @see ServletRequestListener#requestDestroyed(ServletRequestEvent)* 销毁*/public void requestDestroyed(ServletRequestEvent sre) { // TODO Auto-generated method stub}/*** @see ServletRequestAttributeListener#attributeRemoved(ServletRequestAttributeEvent)* 移除属性内容*/public void attributeRemoved(ServletRequestAttributeEvent srae) { // TODO Auto-generated method stub}/*** @see ServletRequestAttributeListener#attributeAdded(ServletRequestAttributeEvent)* 添加*/public void attributeAdded(ServletRequestAttributeEvent srae) { // TODO Auto-generated method stub}/*** @see ServletRequestAttributeListener#attributeReplaced(ServletRequestAttributeEvent)* 修改*/public void attributeReplaced(ServletRequestAttributeEvent srae) { // TODO Auto-generated method stub}
}
案例:Session管理器
自定义Session管理器,session会话,会话的默认有效30分钟, 需要使用开发人员自己管理session的有效期,不需要系统管理。
功能1:把所有的session放入集合中。
功能2:遍历集合中每个session, 判断session有多长时间没有访问了,如果超过1分钟,把session失效了。
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;import javax.enterprise.inject.New;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;public class SessionManagerListener implements HttpSessionListener,ServletContextListener {private static Object lock=new Object();private Timer timer;//保存所有的sessionprivate List<HttpSession> sessions=new LinkedList<HttpSession>();@Overridepublic void sessionCreated(HttpSessionEvent se) {// TODO Auto-generated method stubsynchronized (lock) {sessions.add(se.getSession());}System.out.println("添加了session....."+se.getSession().getId());}@Overridepublic void sessionDestroyed(HttpSessionEvent se) {// TODO Auto-generated method stubSystem.out.println("销毁了session...."+se.getSession().getId());}@Overridepublic void contextInitialized(ServletContextEvent sce) {// TODO Auto-generated method stub//启动定时器timer=new Timer();timer.schedule(new MyTimerTask(), 0, 60*1000);System.out.println("定时器启动");//把集合放入application中sce.getServletContext().setAttribute("sessions", sessions);}@Overridepublic void contextDestroyed(ServletContextEvent sce) {// TODO Auto-generated method stubtimer.cancel();//取消定时器System.out.println("定时器取消了...");}class MyTimerTask extends TimerTask{@Overridepublic void run() {Iterator<HttpSession> it=sessions.iterator();synchronized (lock) {while(it.hasNext()){HttpSession session=it.next();if(System.currentTimeMillis()-session.getLastAccessedTime()>60000){session.invalidate();//session失效it.remove();}}}}}}