通过session统计当前在线人数
Posted john。
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过session统计当前在线人数相关的知识,希望对你有一定的参考价值。
<!-- 监听器配置 --> <listener> <listener-class>com.oracle.com.MyListener</listener-class> </listener>
配置
package com.oracle.com; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class MyListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent event) { // System.out.println("创建了"); HttpSession session = event.getSession();// 获得Session对象 // 通过Session获得servletcontext对象 ServletContext servletContext = session.getServletContext(); /** * 1.获取num值 * 2.加1 * 3.存入servletcontext */ Object object = servletContext.getAttribute("num"); if (object == null) { servletContext.setAttribute("num", 1); } else { Object num = servletContext.getAttribute("num"); int num1 = (int) num; servletContext.setAttribute("num", num1 + 1); } } @Override public void sessionDestroyed(HttpSessionEvent event) { // System.out.println("销毁了"); HttpSession session = event.getSession();// 获得Session对象 // 通过Session获得servletcontext对象 ServletContext servletContext = session.getServletContext(); /** * 1.获取num值 * 2.减1 * 3.存入servletcontext */ servletContext.setAttribute("num", (long) servletContext.getAttribute("num") - 1); } }
统计
package com.oracle.com; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class servletDemo5 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); HttpSession session = req.getSession();// 创建Session // session.setMaxInactiveInterval(10);//设置失效时间10秒 不是销毁 PrintWriter writer = resp.getWriter(); ServletContext servletContext = getServletContext(); Object num = servletContext.getAttribute("num"); writer.write("在线人数:" + num); } }
以上是关于通过session统计当前在线人数的主要内容,如果未能解决你的问题,请参考以下文章
监听器实现案例----自定义session扫描器和统计在线用户人数及用户信息
简单版 -- 通过Session统计用户对某一JSP页面的在线人数