JavaWeb三大组件(Servlet、Filter、Listener)和八个监听器

八个监听器

image.png image.png

监听器三大类

ServletRequestListener ServletContextListener HttpSessionListener

ServletContextListener

当Servlet 容器启动Web 应用时调用该方法。在调用完该方法之后,容器再对Filter 初始化,
并且对那些在Web 应用启动时就需要被初始化的Servlet 进行初始化。

contextInitialized(ServletContextEvent sce) 
 

当Servlet 容器终止Web 应用时调用该方法。在调用该方法之前,容器会先销毁所有的Servlet 和Filter 过滤器。
contextDestroyed(ServletContextEvent sce)

HttpSessionListener

// 当用户与服务器之间开始session时触发该方法
public void sessionCreated(HttpSessionEvent se)

// 当用户与服务器之间session断开时触发该方法
/session自动失效(超时timeout),手动设置session失效(session.invalidate())
public void sessionDestroyed(HttpSessionEvent se)

ServletRequestListener

//request初始化,对实现客户端的请求进行监听
public void requestInitialized(ServletRequestEvent sre);

//对销毁客户端进行监听,即当执行request.removeAttribute("XXX")时调用
public void requestDestroyed(ServletRequestEvent sre);

监听三大域对象的属性变化的监听器

ServletRequestAttributeListener ServletContextAttributeListener HttpSessionAttributeListener

ServletRequestAttributeListener ServletContextAttributeListener HttpSessionAttributeListener

ServletContextAttributeListener用于监听ServletContext(application)范围内属性的变化,实现该接口的监听器需要实现如下三个方法。

attributeAdded(ServletContextAttributeEvent event):当程序把一个属性存入application范围时触发该方法。

attributeRemoved(ServletContextAttributeEvent event):当程序把一个属性从application范围删除时触发该方法。

attributeReplaced(ServletContextAttributeEvent event):当程序替换application范围内的属性时将触发该方法。

HttpSessionAttributeListener 独有的两个方法

一、钝化和活化
钝化:就是序列化,把对象转化为字节序列,把Session对象从内存保存到硬盘里。(持久化操作)
活化:就是反序列化,把字节序列转化为对象,把Session对象从硬盘再读回内存。
HttpSessionActivationListener监控Session时必须把它添加到Session中,所以当Session的序列化/反序列化执行的时候它都会监听到。此接口中有两个方法:
sessionWillPassivate(HttpSessionEvent):Session对象钝化之前执行

sessionDidActivate(HttpSessionEvent):Session对象活化后执行
HttpSessionBindingListener(绑定解绑监听器):
当某个类实现了该接口后,可以感知本类对象添加到session中,以及感知从session中移除。例如让Person类实现HttpSessionBindingListener接口,那么当把Person对象添加到session中,或者把Person对象从session中移除时会调用下面两个方法:
● public void valueBound(HttpSessionBindingEvent event):当把监听器对象添加到session中会调用监听器对象的本方法;

● public void valueUnbound(HttpSessionBindingEvent event):当把监听器对象从session中移除时会调用监听器对象的本方法;
这里要注意,HttpSessionBindingListener监听器的使用与前面介绍的都不相同,当该监听器对象添加到session中,或把该监听器对象从session移除时会调用监听器中的方法。并且无需在web.xml文件中部署这个监听器。

request.getSession().getServletContext().getAttribute() 和request.getSession.getAttribute()的区别?

ServletContext > Session > Request > Page,这是从大到小的范围 ServletContext:是全局的,所有Session都可取到。el中用 applicationScope Session:整个会话中的。el中用 sessionScope

Request:当前请求中的。el中用 requestScope

Page:只是当前页面中的。el中用 pageScope