使用HttpSessionListener和ServletContextListener实现统计在线人数的功能

目录

  • ServletContextListenerImpl.java
  • HttpSessionListenerImpl.java
  • index.jsp

ServletContextListenerImpl.java

package com.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * 

Description: 使用ServletContext监听器创建用于统计在线用户数的全局参数

* @author HiTMT * @date 2019-10-21 17:10:52 */
@WebListener() public class ServletContextListenerImpl implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); context.setAttribute("usercount", 0); //创建在线用户人数参数到context中,用于在整个应用程序进行统计 } }

HttpSessionListenerImpl.java

package com.listener;

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

/**
 * 

Description: 使用HttpSession监听器统计在线人数

* @author HiTMT * @date 2019-10-21 16:21:37 */
@WebListener() public class HttpSessionListenerImpl implements HttpSessionListener{ @Override public void sessionCreated(HttpSessionEvent se) { HttpSession session = se.getSession(); ServletContext context = session.getServletContext(); int usercount = (int) context.getAttribute("usercount"); //从context中获取在线用户人数 context.setAttribute("usercount", usercount+1); //将在线用户人数+1 } @Override public void sessionDestroyed(HttpSessionEvent se) { HttpSession session = se.getSession(); ServletContext context = session.getServletContext(); int usercount = (int) context.getAttribute("usercount"); context.setAttribute("usercount", usercount-1); //将在线用户人数-1 } }

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>显示在线用户人数</title>
</head>
<body>
	<h2>网站当前的在线用户人数:<%=application.getAttribute("usercount") %></h2>
</body>
</html>

你可能感兴趣的:(java,javaWeb,javaEE,JavaEE练习,Java复习的作业)