jsp简单实现统计在线人数
2018-07-20 来源:open-open
通过重写HttpSessionListener接口实现
//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>
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐