您的位置:首页 > 编程语言 > Java开发

重新学javaweb---JavaEE 监听器

2016-05-07 14:53 483 查看
监听器:监听器就是一个java程序,功能是监听另一个java对象变化(方法调用、属性变更)

实现:

  写一个类实现响应的接口

  注册监听器 利用 web.xml

8个监听器,分为了3种

一.用来监听三大作用域的创建和销毁的监听器(除了page域)

1.ServletContextListener 用来监听ServletContext对象创建和销毁的监听器

创建:服务器启动,web应用加载后立即创建代表当前web应用的ServletContext对象

销毁:服务器关闭或web应用被移除出容器时,随着web应用的销毁而销毁

a.实现接口

package com.itheima.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
* 用来监听 servletCcontext 创建和销毁
* @author Fang
*
*/
public class MyListener implements ServletContextListener {

@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("servletContext 被销毁了"+sce.getServletContext());

}

@Override
public void contextInitialized(ServletContextEvent sce) {

System.out.println("servletContext 被创建出来了"+sce.getServletContext().getContextPath());
}

}


b.注册 在web.xml 配置

<listener>
<listener-class>com.itheima.listener.MyListener</listener-class>
</listener>


2.HttpSessionListener 用来监听HttpSession对象创建和销毁的监听器

创建:第一次调用request.getSession方法时创建代表当前会话的session对象

销毁:超过30分钟没人用销毁(可以在web.xml通过session-timeout标签修改时间)/调用invalidate方法自杀/服务器非正常关闭时随着web应用的销毁而销毁,如果服务器是正常关闭会被钝化起来.

当服务器正常关闭时,还存活着的session会随着服务器的关闭被以文件的形式存储在tomcat的work目录下,这个过程叫做session的钝化

当服务器再次正常开启时,服务器会找到之前的SESSIONS.ser文件从中恢复之前保存起来的session对象这个过程叫做session的活化

想要随着Session被钝化活化的对象(一般是bean)它的类必须实现Serializable接口

3.ServletRequestListener 用来监听ServletRequest对象创建和销毁的监听

创建:请求开始创建代表请求的request对象

销毁:请求结束时代表请求的request对象销毁

二。用来监听三大作用域中属性变化的监听器

ServletContextAttributeListener

public class MySCAttrListener implements ServletContextAttributeListener {

public void attributeAdded(ServletContextAttributeEvent scab) {
System.out.println("属性被加入到了SC域中"+scab.getName()+":"+scab.getValue());
}

public void attributeRemoved(ServletContextAttributeEvent scab) {
System.out.println("属性被移除出了SC域中"+scab.getName()+":"+scab.getValue());
}

public void attributeReplaced(ServletContextAttributeEvent scab) {
System.out.println("属性被替换在SC域中"+scab.getName()+":"+scab.getValue()+":"+scab.getServletContext().getAttribute(scab.getName()));
}
//  属性被加入到了SC域中age:23
//  属性被替换在SC域中age:23:24
//  属性被移除出了SC域中age:24
}


其中setvlet中代码核心为:

this.getServletContext().setAttribute("age", 23);
this.getServletContext().setAttribute("age", 24);
this.getServletContext().removeAttribute("age");


//下面这两个方法 和上面的类似

HttpSessionAttributeListener

ServletRequestAttributeListener

三.使javabean自己感知自己在Session中状态变化的监听器,这两个监听器很特殊,不需要自己去写类实现也不需要在web.xml中注册,只要使javabean实现这个接口就能起作用

javabean 在session有下面这四种 状态变化,两个监听器

1.HttpSessionBindingListener

javabean被绑定到session中

sessionDidActive(HttpSessionBindingEvent event)

javabean被移除绑定从session中

valueUnbound(HttpSessionBindingEvent event)方法

2.HttpSessionActivationListener

javabean随着session被钝化

sessionWillPassivate(HttpSessionBindingEvent event)

javabean随着session被活化

sessionDidActive(HttpSessionBindingEvent event)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  web应用 监听器