1、web.xml配置:
<listener>
<listener-class>com.wonders.util.MySessionListener</listener-class>
</listener>
<session-config>
<session-timeout>3</session-timeout>
</session-config>
2、使用Map进行<sessionid, session>的方式进行存贮的封装类MySessionContext :
public class MySessionContext {
private static HashMap mymap = new HashMap();
public static synchronized void AddSession(HttpSession session) {if (session != null) {
mymap.put(session.getId(), session);
}
}
public static synchronized void DelSession(HttpSession session) {
if (session != null) {
mymap.remove(session.getId());
}
}
public static synchronized HttpSession getSession(String session_id) {
if (session_id == null){
return null;
}else {
return (HttpSession) mymap.get(session_id);
}
}
}
3、实现session监听类,并进行业务代码的实现:
public class MySessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
MySessionContext.AddSession(httpSessionEvent.getSession());
}
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
//获取request对象
//HttpServletRequest req= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
//System.out.println(req.getHeader("user-agent"));//获取session 这里可以根据session消失进行Service调用更新日志信息
HttpSession session = httpSessionEvent.getSession();
User user = (User) session.getAttribute("currentUser");
if (user != null) {
System.out.println(user.getUserName() + "---用户session销毁!");
}
MySessionContext.DelSession(session);
}
}