三大域监听器的使用

来源:互联网 发布:苹果mac键盘怎么解锁 编辑:程序博客网 时间:2024/06/16 07:20

ServletContextListener监听器的使用



使用
ServletContextListener监听器监听ServletContext的创建和销毁的实现思路是怎样的?

1、创建监听器类实现ServletContextListener接口,重新接口的所有方法。

package com.web.demo02;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;/** *  * @author 坏坏实现小目标 * *ServletContextListenerTest监听器 *事件源:ServletContext *监听器:ServletContextListenerTest *事件源和监听器绑定:监听的是创建和销毁,通过配置来创建 * */public class ServletContextListenerTest implements ServletContextListener{@Override//监听ServletContext对象的创建public void contextInitialized(ServletContextEvent sce) {// TODO Auto-generated method stubSystem.out.println("服务器启动了");sce.getServletContext().setAttribute("count1",0);}//监听ServletContext对象的销毁@Overridepublic void contextDestroyed(ServletContextEvent sce) {// TODO Auto-generated method stubSystem.out.println("服务器销毁了");}}



2、将事件源和监听器进行绑定。(在web.xml中配置监听器就行了)

  <listener>  <listener-class>com.web.demo02.HttpAtttibteListenerTest</listener-class>  </listener>  



HttpSession对象在什么时候创建和销毁?

分别访问htmljspServlet是否会创建HttpSession对象?

1、HttpSession对象的创建和销毁:

a)      创建:在服务器端第一次调用getSession()方法是创建

b)     销毁:①、非正常关闭服务器时销毁session(正常关闭服务器,session会被序列化到硬盘);②、session过期;③、手动调用HttpSession的方法销毁session。

2、访问html:不会创建HttpSession对象;访问jsp:会创建HttpSession对象(HttpSession对象时jsp的内置对象,jsp在被翻译成Servlet时调用了getSession()方法);访问Servlet:默认不会创建HttpSession对象。



ServletRequestListener监听器的使用

ServletRequest对象在什么时候创建和销毁?

ServletRequestListener作用是:监听ServletRequest对象的创建和销毁;

ServletRequest创建时机:当客户端向服务器发送一次请求时创建

ServletRequest销毁时机:服务器对客户端作出相应之后销毁。






原创粉丝点击