首頁 > 軟體

使用HttpSessionListener監聽器實戰

2022-03-17 13:00:17

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

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();
  %>
<h1>已退出</h1>
  </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();
  %>
  <h1>歡迎登陸</h1>
  <hr>
  當前的線上人數 ${count}
  <a href="logout.jsp" rel="external nofollow" >退出</a>
  </body>
</html>

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。 


IT145.com E-mail:sddin#qq.com