监听器
配置
举例网站显示在线人数
@WebListener
public class ContextListener implements ServletContextListener{
//监听项目的启动,自动执行
@Override
public void contextInitialized(ServletContextEvent sce){
sce.getServletContext().setAttribute("onlineCount",0);
}
//监听项目的停止
@Override
public void contextDestroyed(ServletContextEvent sce){
}
}
@WebListener
public class SessionListener implements HttpSessionListener{
//监听session的创建
@Override
public void sessionCreated(HttpSessionEvent se){
int onlineCount = (Integer)se.getSession().getServletContext().getAttribute("onlineCount");
se.getSession().getServletContext().setAttribute("onlineCount",onlineCount+1);
}
//监听session的销毁
@Override
public void sessionDestroyed(HttpSessionEvent se){
int onlineCount = se.getSession().getServletContext().getAttribute("onlineCount");
se.getSession().getServletContext().setAttribute("onlineCount",onlineCount-1);
}
}
JSP显示在线人数
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
%>
<html>
<head>
<title>Title</title>
</head>
<body>
在线人数${applicationScope.onlineCount}
</body>
</html>