监听器(统计在线人数)
监听器是GUI中常用的功能,Javaweb中使用场景不是很多,可以使用监听器实现统计网站访问人数;
实现原理:
服务器回味每个客户端创建一个session,通过监听服务器中session的创建和销毁便可以记录当前访问网站的人数;
实现步骤:
实现HttpSessionListener类
package com.kangzhu.listener;import javax.servlet.ServletContext;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;public class OnlineCountListener implements HttpSessionListener {public void sessionCreated(HttpSessionEvent se) {ServletContext servletContext = se.getSession().getServletContext();Integer count = (Integer) servletContext.getAttribute("count");if (count == null) {count = 1;}else {count += 1;}servletContext.setAttribute("count", count);}public void sessionDestroyed(HttpSessionEvent se) {ServletContext servletContext = se.getSession().getServletContext();Integer count = (Integer) servletContext.getAttribute("count");if (count == null) {count = 0;}else {count -= 1;}servletContext.setAttribute("count", count);}}
对Session的监听需要实现两个方法,Session的创建和销毁,需要注意的是需要将统计的在线人数存放在ServletContext对象中;
在web.xml中进行注册
<listener><listener-class>com.kangzhu.listener.OnlineCountListener</listener-class></listener>
前端获取访问人数
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>$Title$</title></head><body><h1>当前网站的有<%=request.getSession().getServletContext().getAttribute("count")%>人访问</h1></body></html>