Servlet事件监听器

监听域对象的生命周期

  • 在web应用程序的运行期间,web容器会创建和销毁三个比较重要的对象
  • 分别是ServletContext、Httpsession和ServletRequest
  • 他们对应的方法分别是contextInitialized、contextDestroyed方法
  • 和sessionDestroyed、sessionCreated方法
  • 和requestInitialized、requestDestroyed方法

设计统计当前在线人数的web代码

该项目使用的是HttpSessionListener接口

分别用的是sessionDestroyed方法和sessionCreated方法

jsp页面代码

index.jsp的login的代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>统计当前在线的人数</title>
</head>
<body>
    <h3>
        当前在线的人数为:
        <%=application.getAttribute("count") %>
    </h3>
    <a href="<%=response.encodeUrl("logout.jsp") %>" >退出登录</a>
</body>
</html>

logout代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>退出登录</title>
</head>
<body>
    <%session.invalidate(); %>
    <h3>您已退出本系统 </h3>
</body>
</html>

Servlet层代码

package com.java.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class CountListener implements HttpSessionListener {

    private int count=0; //用于统计在线人数

    @Override
    public void sessionCreated(HttpSessionEvent hse) {
        count++;  //session对象创建时count变量加1
        ServletContext context=hse.getSession().getServletContext();
        context.setAttribute("count", new Integer(count));//将变量保存到session值中
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent hse) {
        count--;    //session对象销毁时count变量减一
        ServletContext context=hse.getSession().getServletContext();
        context.setAttribute("count", new Integer(count));
    }
}

web.xml代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>LYJDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <listener>
      <listener-class>
          com.java.listener.CountListener
      </listener-class>
  </listener>

</web-app>