监听器

监听器是专门用于对其他对象身上发生的事件或状态改变进行监视和响应处理的对象

监听应用程序环境(ServletContext)

监听会话对象(HttpSession)

监听请求消息对象(ServletRequest)

监听啥:监听他们的创建和销毁【监听生死】

例如监听session的生死:就可以统计出当前服务器在线人数

package com.zy.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Application Lifecycle Listener implementation class MySessionListener
 *注解版监听器-----不需要再web.xml配置
 */
@WebListener
public class MySessionListener implements HttpSessionListener {
    //
    int num=0;
    public void sessionCreated(HttpSessionEvent se)  { 
         // 每次创建一个会话会执行该方法
        
        //往域中存取要用servletContext,因为人数要一直保存,除非服务器关闭
        ServletContext servletContext = se.getSession().getServletContext();
        Object o = servletContext.getAttribute("num");
        
        if(o==null){
            num=1;
        }else{
            num=(int)o;
            num++;
            
        }
        servletContext.setAttribute("num", num);
    
    
    }

    //
    public void sessionDestroyed(HttpSessionEvent se)  { 
         // 每次销毁一个会话会执行该方法
        ServletContext servletContext = se.getSession().getServletContext();
        int a = (int)servletContext.getAttribute("num");
        a--;
        servletContext.setAttribute("num", a);
    }
    
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center><h2>中国淘宝</h2></center>
此时在线人数是${num}人
<a href="over.jsp">手动结束session</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 用脚本结束session -->
<%
session.invalidate();//关闭浏览器session不一定销毁(缓存)当前session作废(销毁)
%>
<h2>欢迎来到这里销毁session</h2>
</body>
</html>
原文地址:https://www.cnblogs.com/qfdy123/p/11177958.html