标签:
//session操作类 public class SessionMap { private static Map<String,HttpSession> sesMap = new HashMap<String,HttpSession>(); private static final Object flag = new Object(); private SessionMap(){ } private static class MapUtilsN{ private static SessionMap sessionMap = new SessionMap(); } public static SessionMap getInstance(){ return MapUtilsN.sessionMap; } public void addMap(String sessionId,HttpSession session){ synchronized (flag) { if(!sesMap.containsKey(sessionId)){ sesMap.put(sessionId, session); } } } public void removeMap(String sessionId){ synchronized (flag) { sesMap.remove(sessionId); } } public int getSize(){ synchronized (flag) { return sesMap.size(); } } public HttpSession getSession(String key){ synchronized (flag) { return sesMap.get(key); } } } //监听session创建及销毁 public class MySessionListner implements HttpSessionListener{ public void sessionCreated(HttpSessionEvent arg0) { SessionMap.getInstance().addMap(arg0.getSession().getId(), arg0.getSession()); } public void sessionDestroyed(HttpSessionEvent arg0) { SessionMap.getInstance().removeMap(arg0.getSession().getId()); } } //web.xml中配置监听器 <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置监听器 --> <listener> <listener-class> practice.listner.MySessionListner </listener-class> </listener> <!-- 设置session超时时间 --> <session-config> <session-timeout>10</session-timeout> </session-config> </web-app>
标签:
原文地址:http://my.oschina.net/u/878259/blog/362691