首页 > 代码库 > 通过session统计当前在线人数
通过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统计当前在线人数
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。