版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/twilight_karl/article/details/73744940
案例一
使用监听器获得当前在线的人数。用变量count表示当前在线人数。在HttpSessionListener每次调用sessionCreated方法时更新count,并保存在ServletContext中。之后需要使用时从ServletContext中获取即可。
@WebListener
public class MySessionListener implements HttpSessionListener {
private int count = 0 ;
@Override
public void sessionCreated(HttpSessionEvent se) {
count++;
se.getSession().getServletContext().setAttribute("count", count);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
count--;
se.getSession().getServletContext().setAttribute("count", count);
}
}
案例二
下面这个例子,除了获得在线的人数,还可以需要获得一些其他信息
ServletRequestListener监听器,对于每一次请求,获得请求的相关信息,并保存在ArrayList中。
package listener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import util.SessionUtil;
import entity.User;
@WebListener
public class MyServletRequestListener implements ServletRequestListener {
ArrayList<User> userList = null ;
@Override
public void requestDestroyed(ServletRequestEvent arg0) {
}
@Override
public void requestInitialized(ServletRequestEvent arg0) {
HttpServletRequest request = (HttpServletRequest)arg0.getServletRequest();
HttpSession session = request.getSession();
userList = (ArrayList<User>)arg0.getServletContext().getAttribute("userList");
if(userList == null){
userList = new ArrayList();
}
String sessionId = session.getId();
String Ip = request.getLocalAddr();
String time = new SimpleDateFormat("yy-MM-dd hh:mm:ss").format(new Date());
User user = new User();
user.setFirstTime(time);
user.setIp(Ip);
user.setSessionID(sessionId);
if(SessionUtil.getSessionByID(userList, sessionId)==null){
userList.add(user);
}
arg0.getServletContext().setAttribute("userList", userList);
}
}
HttpSessionListener监听器,更新count的值,并在用户退出时删除ArrayList中的用户数据
package listener;
import java.util.ArrayList;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import util.SessionUtil;
import entity.User;
@WebListener
public class MyHttpSessionListener implements HttpSessionListener {
private int count = 0 ;
@Override
public void sessionCreated(HttpSessionEvent arg0) {
count++;
arg0.getSession().getServletContext().setAttribute("count", count);
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
count--;
arg0.getSession().getServletContext().setAttribute("count", count);
String id = arg0.getSession().getId();
ArrayList<User> userList = (ArrayList<User>)arg0.getSession().getServletContext().getAttribute("userList");
if(SessionUtil.getSessionByID(userList, id) != null){
User user = SessionUtil.getSessionByID(userList,id);
userList.remove(user);
}
}
}
效果如下: