博客已迁移到CSDN《https://blog.csdn.net/qq_33375499》
监听器:用于监听web应用中某些对象、信息的创建、销毁等动作,服务器会自动调用相应的方法进行处理。常用于统计在线人数,初始化系统参数等。
Javaweb监听器主要监听对象有ServletContext、HttpSession、ServletRequest。
下面是贴上一个统计登录人信息的栗子:
在web.xml 中配置监听器:
<!--用户登录监听器--> <listener> <listener-class>com.xxx.listener.SessionListener</listener-class> </listener>
创建监听器:
import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import java.util.*; public class SessionListener implements HttpSessionListener,ServletRequestListener { // 定义监听类对象,用于存储所有用户的登录信息 private static Map<String,String> userList = new HashMap<String, String>(); // 定义session map对象 private static Map<String,HttpSession> sessionMap = new HashMap<String, HttpSession>(); private HttpServletRequest request = null; @Override public void sessionCreated(HttpSessionEvent httpSessionEvent) {// 监听 session 创建 } @Override public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {// 监听 session 销毁 HttpSession httpSession = httpSessionEvent.getSession(); // 获取登录用户名 String username = (String) httpSession.getAttribute("username"); if(username != null){ Iterator iterator = userList.entrySet().iterator(); Map map = null; String logmsg = null; // 遍历 userList:将userlist中的用户信息删除 while (iterator.hasNext()){ map = (Map) iterator.next(); if(map.get(username) != null){ logmsg = (String) map.get(username); if(logmsg.indexOf(request.getLocalAddr()) > -1){ userList.remove(username); sessionMap.remove(username); break; } } } } } @Override public void requestDestroyed(ServletRequestEvent servletRequestEvent) {// 监听 request 销毁 } @Override public void requestInitialized(ServletRequestEvent servletRequestEvent) {// 监听 request 创建 this.request = (HttpServletRequest) servletRequestEvent.getServletRequest(); HttpSession httpSession = this.request.getSession(); // 获取登录用户名 String username = (String) httpSession.getAttribute("username"); if(username != null){ // 如果 userList为空直接 put if(userList.isEmpty()){ userList.put(username,"IP: " + request.getLocalAddr() + " ,logtime:" + ProUtil.getStrDatetime(new Date())); sessionMap.put(username,httpSession); return; } String logmsg = null; if(userList.get(username) == null){ userList.put(username,"IP: " + request.getLocalAddr() + " ,logtime:" + ProUtil.getStrDatetime(new Date())); sessionMap.put(username,httpSession); }else { logmsg = userList.get(username); if(logmsg.indexOf(request.getLocalAddr()) > -1){ userList.put(username,"IP: " + request.getLocalAddr() + " ,logtime:" + ProUtil.getStrDatetime(new Date())); sessionMap.put(username,httpSession); }else { userList.put(username,"IP: " + request.getLocalAddr() + " ,logtime:" + ProUtil.getStrDatetime(new Date())); sessionMap.get(username).setAttribute("logError","该账号已经在其他地方登录!!!"); sessionMap.put(username,httpSession); } } } } }