对象作用域与Servlet事件监听器

来源:互联网 发布:java学士后6.0 编辑:程序博客网 时间:2024/06/10 13:20

对象作用域
在Servlet里可以用一个名字绑定一个对象
谁能看到并使用这个属性,它能存活多久
对象作用域
ServletContext应用上下文
设置在ServletContext对象中的属性可以被Web应用中的任何一部分来访问 ,线程不安全。
这里写图片描述
会话作用域
Session用于维护与一个客户的会话状态。对于同一个客户的多个请求,Session会跨这些请求持久存储 ,线程也不安全
这里写图片描述
请求作用域
属性可以保存在请求作用域范围中,存储时间比上下文作用域和会话作用域短。在请求结束后,对象就会被垃圾回收。在请求作用域范围之外就不能进行访问,所以线程安全。
这里写图片描述
监听器概述
监听session,request,application这三个对象里存取数据的变化
监听器对象可以在事情发生前、发生后可以做一些必要的处理
Servlet监听器主要目的是给Web应用增加事件处理机制,以便更好地监视和控制Web应用的状态变化
监听器分类
这里写图片描述
监听Web应用程序范围内的事件
Web应用启动和销毁事件
Web应用程序的属性发生改变的事件(包括增加、删除、修改)。
定义了ServletContextListener和ServletContextAttributeListener两个接口
ServletContextListener接口
ServletContextListener接口用于监听Web应用程序启动和销毁的事件
contextInitialized(ServletContextEvent sce):通知正在接受的对象,应用程序已经被加载及初始化
contextDestroyed(ServletContextEvent sce):通知正在接受的对象,应用程序已经被销毁
ServletContextEvent中的方法getServletContext()取得ServletContext对象
ServletContextAttributeListener接口
监听WEB应用属性改变的事件,包括:增加属性、删除属性、修改属性
attributeAdded(ServletContextAttributeEvent scab):若有属性对象加入Application的范围,通知正在收听的对象
attributeRemoved(ServletContextAttributeEvent scab):若有属性对象从Application的范围移除,通知正在收听的对象
attributeReplaced(ServletContextAttributeEvent scab):若在Application的范围中,有对象取代另一个对象时,通知正在收听的对象

HttpSessionBindingListener接口
监听对象加入Session范围时
监听从Session范围中移出对象时
接口有两个方法
void valueBound(HttpSessionBindingEvent event):当对象正在绑定到Session中,Servlet容器调用该方法来通知该对象
void valueUnbound(HttpSessionBindingEvent event):当从Session中删除对象时,Servlet容器调用该方法来通知该对象

HttpSessionBindingEvent类提供如下方法:
public String getName():返回绑定到Session中或从Session中删除的属性名字。
public Object getValue():返回被添加、删除、替换的属性值
public HttpSession getSession():返回HttpSession对象

HttpSessionAttributeListener
监听HttpSession中的属性的操作
当在Session中增加一个属性时,激发attributeAdded(HttpSessionBindingEvent se) 方法;
当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;
当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。

HttpSessionListener接口

监听HttpSession对象的创建和销毁操作,可用于在线人数的统计
当创建一个Session时,激发session Created(HttpSessionEvent se)方法
当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent se)方法

监听请求生命周期内事件
请求作用域范围内的生命周期事件用于管理整个request生命周期的状态和资源
ServletRequestListener接口
public void requestDestroyed(ServletRequestEvent sre):当请求被销毁时被处理。
public void requestInitialized(ServletRequestEvent sre):当请求被创建时被处理
ServletRequestAttributeListener接口
public void attributeAdded(ServletRequestAttributeEvent arg0) :当在请求作用域中添加一个属性的时候调用该方法。
public void attributeRemoved(ServletRequestAttributeEvent arg0) :当在请求作用域中删除一个属性时调用
public void attributeReplaced(ServletRequestAttributeEvent arg0) :当在请求作用域中替换一个属性值的时候调用

0 0
原创粉丝点击