首页 > 代码库 > 【JavaEE企业应用实战学习记录】sessionListener

【JavaEE企业应用实战学习记录】sessionListener

 1 package sanglp.servlet; 2  3  4 import javax.servlet.ServletContext; 5 import javax.servlet.annotation.WebListener; 6 import javax.servlet.http.HttpSession; 7 import javax.servlet.http.HttpSessionEvent; 8 import java.util.Hashtable; 9 import java.util.Map;10 11 /**12  * Created by Administrator on 2016/10/6.13  */14 @WebListener15 public class HttpSessionListener implements javax.servlet.http.HttpSessionListener {16 17     //当用户与服务之间开始session时触发该方法18     @Override19     public void sessionCreated(HttpSessionEvent httpSessionEvent) {20         HttpSession session=httpSessionEvent.getSession();21         ServletContext application=session.getServletContext();22         //获取sessionId23         String sessionId=session.getId();24         //如果是一次新的会话25         if(session.isNew()){26             String user=(String)session.getAttribute("user");27             //未登陆用户当游客处理28             user=(user==null)?"游客":user;29             Map<String,String> online=(Map<String, String>) application.getAttribute("online");30             if(online==null){31                 online=new Hashtable<String,String>();32                 //将用户在线信息放入Map中33                 online.put(sessionId,user);34                 application.setAttribute("online",online);35             }36         }37     }38 39     //当用户与服务器之间session断开时触发该方法40     @Override41     public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {42     HttpSession session=httpSessionEvent.getSession();43         ServletContext application=session.getServletContext();44         String sessionId=session.getId();45         Map<String,String> online=(Map<String,String>)application.getAttribute("online");46         if(online!=null){47             //删除该用户的在线信息48             online.remove(sessionId);49         }50         application.setAttribute("online",online);51     }52 }

 

【JavaEE企业应用实战学习记录】sessionListener