servlet监听

一、对象作用域

  ServletContext(上下文)

整个Web应用程序,线程不安全

获取对象getServletContext()方法

HttpSession(会话)

一个会话交互过程,线程不安全

ServletRequest(请求)

一次请求过程

解决Servlet线程安全问题

1、编写Servlet类时实现 SingleThreadModel接口将Servlet变成单线程机制

2、使用synchronized同步加锁

3尽量不在Servlet中定义成员变量,使用局部变量

最好使用第三种,线程安全,性能高

二、监听器概述

  实现一到多个Servlet事件监听接口类

事件类型

ServletContext

ServletContextListener

ServletContextAttributeListener

HttpSession

HttpSessionListener

HttpSessionActivationListener

HttpSessionAttributeListener

HttpessionBindingListener

ServletRequest

ServletRequestListener

ServletRequestAttributeListener

三、监听Web应用程序范围内的事件

ServletContextListener

void contextInitialized(ServletContextEvent sce)

通知正在接受的对象,应用程序已经被加载及初始化

void contextDestroyed(ServletContextEvent sce)

通知正在接受的对象,应用程序已经被销毁

ServletContextAttributeListener

void attributeAdded(ServletContextAttributeEvent scab)

若有属性对象加入Application的范围,通知正在收听的对象

void attributeRemoved(ServletContextAttributeEvent scab)

若有属性对象从Application的范围移除,通知正在收听的对象

void attributeReplaced(ServletContextAttributeEvent scab)

若在Application的范围中,有对象代另一个对象时,通知正在收听的对象

四、监听会话范围内的事件

  HttpessionBindingListener

唯一不需要在web.xml中注册的

void valueBound(HttpSessionBindingEvent event)

当对象正在绑定到session中Servlet容器调用该方法来通知对象

void valueUnbound(HttpSessionBindingEvent event)

当从session中删除对象时,Servlet调用该方法通知对象

HttpSessionAttributeListener

主要监听HttpSession中属性的操作

HttpSessionListener

监听HttpSession的操作

HttpSessionActivationListener

public void sessionDidActivate(HttpSessionEvent hse): 会话被激活

public void sessionWillPassivate(HttpSessionEvent hse): 会话被迁移

五、监听请求生命周期内的事件

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值