import java.util.ArrayList; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import Entity.User; import SessionUtil.SessionUtil; @WebListener public class MyHttpSession implements HttpSessionListener { private int number = 0; @Override public void sessionCreated(HttpSessionEvent arg0) { number++; arg0.getSession().getServletContext().setAttribute("Number", number); } @Override public void sessionDestroyed(HttpSessionEvent arg0) { number--; arg0.getSession().getServletContext().setAttribute("Number", number); ArrayList<User> userlist = null;//在线用户List userlist = (ArrayList<User>) arg0.getSession().getServletContext() .getAttribute("userlist"); String sessionid = arg0.getSession().getId(); if (SessionUtil.getUserBySessionId(userlist,sessionid)!=null) { userlist.remove(SessionUtil.getUserBySessionId(userlist, sessionid)); System.out.println("删除的sessionId为:"+sessionid); } } }
public class MyServletRequest implements ServletRequestListener { private ArrayList<User> userlist; @Override public void requestDestroyed(ServletRequestEvent arg0) { } public void requestInitialized(ServletRequestEvent arg0) { //不是第一次登录就可以从上下文中获取userlist userlist = (ArrayList<User>)arg0.getServletContext().getAttribute("userlist"); //第一次登录 if(userlist==null){ userlist = new ArrayList<User>(); } HttpServletRequest request = (HttpServletRequest) arg0.getServletRequest(); //得到session id String sessionIdString = request.getSession().getId(); //如果userlist有改id 则不加入userlist 没有则创建一个user 加入userlist中 if(SessionUtil.getUserBySessionId(userlist,sessionIdString)==null){ User user = new User(); user.setSessionIdString(sessionIdString); user.setSessionTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); user.setUserurl(request.getRemoteAddr()); userlist.add(user); System.out.println("加入的用户sessionId为:"+sessionIdString); } //添加userList到application(ServletContext的对象 arg0.getServletContext().setAttribute("userlist",userlist); } }
jsp页面:
<body> 当前在线用户人数:${Number }<br/> <% ArrayList<Entity.User> userlist = (ArrayList<Entity.User>)request.getServletContext().getAttribute("userlist"); if(userlist!=null){ for(int i = 0 ; i < userlist.size() ; i++){ Entity.User user = userlist.get(i); %> IP:<%=user.getSessionIdString() %>,FirstTime:<%=user.getSessionTime() %>,SessionId:<%=user.getUserurl() %> <br/> <%} } else{ out.println("无用户"); }%> </body>
public class SessionUtil { public static Object getUserBySessionId(ArrayList<User> userList, String sessionIdString) { for (int i = 0; i < userList.size(); i++) { User user = userList.get(i); if (user.getSessionIdString().equals(sessionIdString)) { return user; } } return null; } }
MyServletRequest这个类没有监听
你用注解的方式注册了监听器啊
好吧 尴尬了 我没有注册request那个监听器