如何使用HttpSessionListener监听器

发布时间:2022-03-17 15:05:24 作者:iii
来源:亿速云 阅读:239

这篇“如何使用HttpSessionListener监听器”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“如何使用HttpSessionListener监听器”文章吧。

HttpSessionListener监听器

定义监听器

package lee; 
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;import java.util.*;
@WebListener
public class OnlineListener
    implements HttpSessionListener
{
    // 当用户与服务器之间开始session时触发该方法
    public void sessionCreated(HttpSessionEvent se)
    {
        HttpSession session = se.getSession();
        ServletContext application = session.getServletContext();
        // 获取session ID
        String sessionId = session.getId();
        // 如果是一次新的会话
        if (session.isNew())
        {
            String user = (String)session.getAttribute("user");
            // 未登录用户当游客处理
            user = (user == null) ? "游客" : user;
            Map<String , String> online = (Map<String , String>)
                application.getAttribute("online");
            if (online == null)
            {
                online = new Hashtable<String , String>();
            }
            // 将用户在线信息放入Map中
            online.put(sessionId , user);
            application.setAttribute("online" , online);
        }
    }
    // 当用户与服务器之间session断开时触发该方法
    public void sessionDestroyed(HttpSessionEvent se)
    {
        HttpSession session = se.getSession();
        ServletContext application = session.getServletContext();
        String sessionId = session.getId();
        Map<String , String> online = (Map<String , String>)
            application.getAttribute("online");
        if (online != null)
        {
            // 删除该用户的在线信息
            online.remove(sessionId);
        }
        application.setAttribute("online" , online);
    }
}

测试JSP

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> 用户在线信息 </title>
    <meta name="website" content="http://www.crazyit.org" />
</head>
<body>
在线用户:
<table width="400" border="1">
<%
Map<String , String> online = (Map<String , String>)application
    .getAttribute("online");
for (String sessionId : online.keySet())
{%>
<tr>
    <td><%=sessionId%>
    <td><%=online.get(sessionId)%>
</tr>
<%}%>
</body>
</html>

测试结果

如何使用HttpSessionListener监听器

HttpSessionListener监听器应用场景

如何使用HttpSessionListener监听器

应用场景:用来统计当前在线人数

实现HttpSessionListener

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MyHttpSessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println("httpsession被创建");
    }
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("httpsession被销毁"); 
    } 
}

登陆界面去创建HttpSessionListenter

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <%
    <%--    创建HttpSessionListenter--%>
    request.getSession();
  %>
  </body>
</html>

登出销毁HttpSessionListenter

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <%
<%--    销毁HttpSessionListener--%>
    request.getSession().invalidate();
  %>
<h2>已退出</h2>
  </body>
</html>

实现统计登陆人数(多线程并发)

web.xml中配置监听

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <listener>
        <listener-class>MyHttpSessionListener</listener-class>
    </listener>
    <listener>
        <listener-class>myServletContextListener</listener-class>
    </listener>
</web-app>

统计人数实在最大ServletContextListener这个域当中

因为HttpSessionListener监听器只在当前会话中有效

(1)创建ServletContextListener监听器并设置初始值为0

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class myServletContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext sc = servletContextEvent.getServletContext();
        sc.setAttribute("count", 0);
    }
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) { 
    }
}

2)变更在线人数

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MyHttpSessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println("httpsession被创建");
        countPersion( httpSessionEvent.getSession().getServletContext(), true);
    }
 
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("httpsession被销毁");
        countPersion(httpSessionEvent.getSession().getServletContext(), false);
    }  
    /*
    * 变更在线的人数
    * */
    public void countPersion(ServletContext sc, boolean isAdd) {
        // 为了防止多线程并发问题加锁
        synchronized (sc) {
            // 获得当前的在线人数
            Integer count = (Integer) sc.getAttribute("count");
            if(isAdd) {
                sc.setAttribute("count", ++count);
            } else  {
                sc.setAttribute("count", --count);
            }
        }
    }
}

(3)前端页面上去获取显示

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <%
<%--    创建HttpSessionListenter--%>
    request.getSession();
  %>
  <h2>欢迎登陆</h2>
  <hr>
  当前的在线人数 ${count}
  <a href="logout.jsp" rel="external nofollow" >退出</a>
  </body>
</html>

以上就是关于“如何使用HttpSessionListener监听器”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

推荐阅读:
  1. 怎么在java中使用监听器统计在线人数
  2. 如何在Spring中使用ApplicationListener监听器

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

httpsessionlistener

上一篇:如何使用C++实现简单校园导游系统

下一篇:如何使用原生JS获取URL链接参数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》