• 事件监听之统计当前在线人数案例


     1 import javax.servlet.ServletContext;
     2 import javax.servlet.ServletContextEvent;
     3 import javax.servlet.ServletContextListener;
     4 import javax.servlet.annotation.WebListener;
     5 import javax.servlet.http.HttpSessionAttributeListener;
     6 import javax.servlet.http.HttpSessionEvent;
     7 import javax.servlet.http.HttpSessionListener;
     8 import javax.servlet.http.HttpSessionBindingEvent;
     9 
    10 @WebListener()
    11 public class CountListener implements HttpSessionListener {
    12     private int count=0;
    13     public void  sessionCreated(HttpSessionEvent hse) {
    14         count++;
    15         ServletContext context = hse.getSession ().getServletContext ();
    16         context.setAttribute ("count",new Integer (count));
    17     }
    18 
    19     @Override
    20     public void sessionDestroyed(HttpSessionEvent hse) {
    21         count--;
    22         ServletContext context = hse.getSession ().getServletContext ();
    23         context.setAttribute ("count",new Integer (count));
    24     }
    25 }

    index.jsp

     1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     2 <html>
     3   <head>
     4     <title>$Title$</title>
     5   </head>
     6   <body>
     7     <h3>
     8       当前在线人数为:<%=application.getAttribute("count")%>
     9     </h3>
    10     <a href="<%=response.encodeURL ("logout.jsp")%>">退出系统</a>
    11   </body>
    12 </html>

    logout.jsp

     1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     2 <html>
     3 <head>
     4     <title>Title</title>
     5 </head>
     6 <body>
     7   <%session.invalidate();%>
     8     <h3>您已退出系统</h3>
     9 </body>
    10 </html>

    采用不同的浏览器访问,防止公用一个session对象 

     

  • 相关阅读:
    测试
    python+selenium
    selenium使用execute_script方法执行JavaScript
    Selenium之动作链(ActionChains)
    angular组件数据
    angular
    数据库sql查询习题
    django
    集合框架Collection
    sql语句中select、 from、 where、 group by 、having、 order by的执行顺序分析
  • 原文地址:https://www.cnblogs.com/gdwkong/p/7635054.html
Copyright © 2020-2023  润新知