监听器:用于监听web应用中某些对象、信息的建立、销毁等动做,服务器会自动调用相应的方法进行处理。经常使用于统计在线人数,初始化系统参数等。java
Javaweb监听器主要监听对象有ServletContext、HttpSession、ServletRequest。web
下面是贴上一个统计登陆人信息的栗子:服务器
在web.xml 中配置监听器:session
<!--用户登陆监听器--> <listener> <listener-class>com.xxx.listener.SessionListener</listener-class> </listener>
建立监听器:ide
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); } } } } }