JavaWeb(Servlet)中实现监听器
1.实现listener接口(当然有很多类型):
package com.tang.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class javaListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
ServletContext sct = se.getSession().getServletContext();
Integer onlineCount = (Integer) sct.getAttribute("OnlineCount");
if(onlineCount == null){
onlineCount = new Integer(1);
}
else {
int count = onlineCount.intValue();
onlineCount = new Integer(count+1);
}
sct.setAttribute("OnlineCount",onlineCount);
}
@Override
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 count = onlineCount.intValue();
onlineCount = new Integer(count-1);
}
sct.setAttribute("OnlineCount",onlineCount);
}
}
2、在web.xml中注册监听器才能使用:
<listener>
<listener-class>com.tang.listener.javaListener</listener-class>
</listener>
浙公网安备 33010602011771号