首页 > 代码库 > 通过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统计当前在线人数