jsp简单实现统计在线人数
通过重写HttpSessionListener接口实现
1 //session操作类 2 public class SessionMap { 3 4 private static Map<String,HttpSession> sesMap = new HashMap<String,HttpSession>(); 5 6 private static final Object flag = new Object(); 7 8 private SessionMap(){ 9 10 } 11 12 private static class MapUtilsN{ 13 private static SessionMap sessionMap = new SessionMap(); 14 } 15 16 public static SessionMap getInstance(){ 17 return MapUtilsN.sessionMap; 18 } 19 20 public void addMap(String sessionId,HttpSession session){ 21 synchronized (flag) { 22 if(!sesMap.containsKey(sessionId)){ 23 sesMap.put(sessionId, session); 24 } 25 } 26 } 27 28 public void removeMap(String sessionId){ 29 synchronized (flag) { 30 sesMap.remove(sessionId); 31 } 32 } 33 34 public int getSize(){ 35 synchronized (flag) { 36 return sesMap.size(); 37 } 38 } 39 40 public HttpSession getSession(String key){ 41 synchronized (flag) { 42 return sesMap.get(key); 43 } 44 } 45 } 46 47 48 //监听session创建及销毁 49 public class MySessionListner implements HttpSessionListener{ 50 51 public void sessionCreated(HttpSessionEvent arg0) { 52 SessionMap.getInstance().addMap(arg0.getSession().getId(), arg0.getSession()); 53 } 54 55 public void sessionDestroyed(HttpSessionEvent arg0) { 56 SessionMap.getInstance().removeMap(arg0.getSession().getId()); 57 } 58 59 }
//web.xml中配置监听器
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 </welcome-file-list> 10 <!-- 配置监听器 --> 11 <listener> 12 <listener-class> 13 practice.listner.MySessionListner 14 </listener-class> 15 </listener> 16 <!-- 设置session超时时间 --> 17 <session-config> 18 <session-timeout>10</session-timeout> 19 </session-config> 20 </web-app>
不定期会发布一些实用的Java开发文章