监听器
实现一个监听器的接口;(有N种监听器)
实例:统计网站在线人数 (统计session)
public class ListenerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.getWriter().write("哈哈哈");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
//统计网站在线人数 : 统计session
public class OnlineCountListener implements HttpSessionListener {
@Override
//创建session监听: 看你的一举一动
//一旦创建Session就会触发一次这个事件!
public void sessionCreated(HttpSessionEvent se) {
ServletContext sct = se.getSession().getServletContext();
System.out.println(se.getSession().getId());
Integer onlineCount = (Integer) sct.getAttribute("OnlineCount");//创建一个值
if (onlineCount==null){
onlineCount = new Integer(1);
}else {
int i = onlineCount.intValue();
onlineCount = new Integer(i + 1);
}
sct.setAttribute("OnlineCount",onlineCount);
}
@Override
//销毁session监听
//一旦销毁Session就会触发一次这个事件!
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext sct = se.getSession().getServletContext();
Integer onlineCount = (Integer) sct.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(0);
}else {
int i = onlineCount.intValue();
onlineCount = new Integer(i - 1);
}
sct.setAttribute("OnlineCount",onlineCount);
}
/*
Session销毁:
1. 手动销毁 getSession().invalidate();
2. 自动销毁
*/
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<H1>当前有<span><%=this.getServletConfig().getServletContext().getAttribute("OnlineCount")%></span>人在线</H1>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>lis</servlet-name>
<servlet-class>com.node.Servlet.ListenerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>lis</servlet-name>
<url-pattern>/lis</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.node.Servlet.OnlineCountListener</listener-class>
</listener>
</web-app>