CountServlet.java
@WebServlet("/CountServlet")
public class CountServlet extends HttpServlet implements HttpSessionListener,
HttpSessionAttributeListener,HttpSessionBindingListener {
private static final long serialVersionUID = 1L;
private static int sessionCounter = 0;
private static int attributeCounter = 0;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public static int getOnlineSession() {
return sessionCounter;
}
public static int getOnlineAttribute() {
return attributeCounter;
}
@Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
attributeCounter++;
System.out.println("attribute added");
}
@Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
attributeCounter--;
System.out.println("attribute removed");
}
@Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println(httpSessionBindingEvent.getName()+" replaced");
}
@Override
public void valueBound(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println(httpSessionBindingEvent.getName()+"_Bound_" + httpSessionBindingEvent.getValue());
}
@Override
public void valueUnbound(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println(httpSessionBindingEvent.getName()+"_Unbound_" + httpSessionBindingEvent.getValue());
}
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
sessionCounter++;
System.out.println("session created");
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
sessionCounter--;
System.out.println("session destroied");
}
}
web.xml
<listener>
<listener-class>servlet.CountServlet</listener-class>
</listener>
count.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="servlet.CountServlet"%>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<table>
<tr>
<td align="center" height="35">
当前在线人数: <%= CountServlet.getOnlineSession() %> 人
</td>
</tr>
</table>
</body>
</html>
网友评论