案例:监听域对象的生命周期

任务目标

实现监听ServletContext HttpSession ServletRequest这三个域对象的生命周期

创建监听器MyListener

public class MyListener implements 
     ServletContextListener, HttpSessionListener,ServletRequestListener {
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("ServletContext对象被创建了");
	}
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("ServletContext对象被销毁了");
	}
	public void requestInitialized(ServletRequestEvent arg0) {
		System.out.println("ServletRequest对象被创建了");
	}
	public void requestDestroyed(ServletRequestEvent arg0) {
		System.out.println("ServletRequest对象被销毁了");
	}
	public void sessionCreated(HttpSessionEvent arg0) {
		System.out.println("HttpSession对象被创建了");
	}
	public void sessionDestroyed(HttpSessionEvent arg0) {
		System.out.println("HttpSession对象被销毁了");
	}
}

web.xml中配置监听器

  <listener>
    <listener-class>cn.itcast.chapter08.listener.MyListener</listener-class>
  </listener>

启动项目,查看ServletContext对象创建信息

 关闭项目,查看ServletContext对象销毁信息

创建测试页面myjsp.jsp

测试HttpSessionListener,ServletRequestListener 

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<html>
<head>
<title>this is MyJsp.jsp page</title>
</head>
<body>
    这是一个测试监听器的页面
</body>
</html>

 设置session超时时间

  <session-config>  
    <session-timeout>2</session-timeout>
  </session-config>

再次启动项目,查看结果

访问测试页面http://localhost:8080/chapter08/myjsp.jsp

 浏览器关闭或者不刷新,两分钟后Session对象都会被销毁,所以控制台输出以下内容

猜你喜欢

转载自blog.csdn.net/daqi1983/article/details/121461413
今日推荐