在线人数

思路:使用session的监听器

参拷:http://xace.iteye.com/blog/424250

监听器类

package com.chinacache.utils;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.chinacache.entity.User;

public class OnLineUtil implements HttpSessionListener, HttpSessionAttributeListener, ServletContextListener {

	private ServletContext application = null;
	private Map<String, User> allUser = null;

	@Override
	/**
	 * session 创建时会调用这个方法
	 */
	public void sessionCreated(HttpSessionEvent se) {
		allUser = (Map<String, User>) application.getAttribute("userMap");
		String sessionId = se.getSession().getId();
		if (allUser.get(sessionId) == null) {
			allUser.put(sessionId, null);
		}

	}

	@Override
	/**
	 * 调用session.invalidate()时被调用
	 */
	public void sessionDestroyed(HttpSessionEvent se) {
		String sessionId = se.getSession().getId();
		if (allUser != null && allUser.get(sessionId) != null) {
			allUser.remove(sessionId);
		}

	}

	@Override
	/**
	 * 应用启动时调用
	 */
	public void contextInitialized(ServletContextEvent sce) {
		application = sce.getServletContext();
		application.setAttribute("userMap", new HashMap<String, User>());
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub

	}

	@Override
	/**
	 * session 中属性被增回时
	 */
	public void attributeAdded(HttpSessionBindingEvent se) {
		String sessionId = se.getSession().getId();
		if (allUser != null) {
			User user = (User) se.getSession().getAttribute("currUser");
			if (user.getUser_name() != null) {
				allUser.put(sessionId, user);
			}
		}

	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub
	}

	@Override
	/**
	 * session 中属性更改时
	 */
	public void attributeReplaced(HttpSessionBindingEvent se) {
		HttpSession session = se.getSession();
		String id = session.getId();
		if (allUser != null) {
			User user = (User) session.getAttribute("currUser");
			if (user.getUser_name() != null) {
				allUser.put(id, user);
			}
		}
	}

}

  web.xml

<listener>
		<listener-class>com.chinacache.utils.OnLineUtil</listener-class>
	</listener>

 jsp展示(使用了ztree)

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<%@ page import="com.chinacache.entity.User"%>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
	href="${projectPath}/resources/ztree/zTreeStyle/zTreeStyle.css"
	type="text/css">
<script type="text/javascript"
	src="${projectPath}/resources/ztree/jquery.ztree.core-3.5.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Welcome to Starscream!</title>
</head>
<body>
	<div class="container">
	<div class="zTreeDemoBackground left">
		<ul id="treeDemo" class="ztree"></ul>
	</div>
	</div>

</body>

<SCRIPT type="text/javascript">

		var zNodes =<%
	Map<String, User> l = (Map<String, User>)application.getAttribute("userMap"); 
		Map<String,List<String>> users=new HashMap<String,List<String>>();
	        for(String id : l.keySet()){  
	           String cgf=l.get(id).getCfg_value();  
	           String username=l.get(id).getUser_name();
	           if(users.get(cgf)==null){
	        	   users.put(cgf, new ArrayList<String>());
	           }
	           users.get(cgf).add(username);
	           }
	        StringBuilder node= new StringBuilder("[{ name:'在线人员(").append(l.size()).append("人)'");
	        if(users.size()>0){
	        	node.append(", open:true");
	        	node.append(", children: [");
	        	for(String cgf:users.keySet()){
	        		List<String> usernames=	users.get(cgf);
                    node.append(String.format("{ name:'%s(%s人)',",cgf,usernames.size()));
                    if(usernames.size()>0){
                    	node.append("children: [");
        		        for(String name:usernames){
        		        	node.append("{ name:'").append(name).append("'},");
        		        }
        		        node.deleteCharAt(node.length()-1);
                    }else{
                    	node.append(", isParent:true");
                    }
        	        node.append("]},");
	             }
	             node.deleteCharAt(node.length() - 1);
	            node.append("]");
			} else {
		       node.append(", isParent:true");
			}
		node.append("}]");
		out.println(node.toString());
%>;
		var setting = {	};
		$(document).ready(function(){
			$.fn.zTree.init($("#treeDemo"), setting, zNodes);
		});
		
	</SCRIPT>
</html>

 LoginController.java

package com.chinacache.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.chinacache.entity.User;

@Controller
@SessionAttributes({ "currUser", "projectPath", "funcMap" })
public class LoginController {

	private static Logger logger = Logger.getLogger(LoginController.class);

	@RequestMapping("/")
	public String showLoginPage(Model model) {
		logger.info("showLoginPage is call!");
		return "login";
	}

	@RequestMapping(value = "/user", method = RequestMethod.POST)
	public String userLogin(@RequestParam(value = "user", required = false) User user, HttpServletRequest request, Model model) {
		model.addAttribute("currUser", user);
		return "forward:/home";
	}
	
	@RequestMapping(value = "/logout")
	public String LogOut(HttpServletRequest request,Model model){
		HttpSession session = request.getSession();
		if(session!=null){
			model.addAttribute("currUser",new User());  
			
			session.removeAttribute("currUser");
			
			session.invalidate();
		}
		return "login";
	}
}

由于使用@SessionAttributes把model里的属性赋值给session中,在调用LogOut后跳到login页(此时model里还存放着user信息,会自动赋给新session),所以把model里的值User赋值空user,在判断当前session中的user中的属性(如username)是否为null,如果为null表示还没有登入即不会放到在线列表中

 

转的:http://xace.iteye.com/blog/424250

javax.servlet.http.HttpSession 这个类是很常用的,每当我们浏览网站,不论有没有登陆,都会产生1个session,它记录了和浏览者相关的数据; 

下面介绍session的2个监听器接口: 

1)javax.servlet.http.HttpSessionBindingListener; 

实现这个接口的类,每当被存放到session或从session中移除都会出发接口中相应的方法,从而实现监听的效果;

2)javax.servlet.http.HttpSessionListener; 

实现这个接口的类,本身就是1个监听器,每当有session生成或消亡时,都触发接口中相应的方法,从而实现监听器的效果; 

HttpSessionListener 的实现类本身就是一个监听器,要使用它需要在 web.xml 中启动这个监听器,例如 

Xml代码     收藏代码
  1. <listener>  
  2.  <listener-class>packname.classname</listener-class>  
  3. </listener>  



3)这2个监听器是有区别的 

前者的触发取决于 session 中加入的属性; 

后者的触发取决于 session 本身的产生和消亡; 



与shangshu 之类似的还有 
对ServletContext的监听和对Request监听 

应用:当前在线人数列表 
在线人数列表是对所有人起作用,数据应放到application中。即ServletContext对象 

OnLineDemo.java 

Java代码     收藏代码
  1. package demo;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import javax.servlet.ServletContext;  
  7. import javax.servlet.ServletContextEvent;  
  8. import javax.servlet.ServletContextListener;  
  9. import javax.servlet.http.HttpSessionAttributeListener;  
  10. import javax.servlet.http.HttpSessionBindingEvent;  
  11. import javax.servlet.http.HttpSessionEvent;  
  12. import javax.servlet.http.HttpSessionListener;  
  13.   
  14. /* 
  15.  * <listener> <listener-class>demo.OnLineDemo</listener-class> 
  16.  * </listener> 
  17.  */  
  18.   
  19. public class OnlineDemo implements ServletContextListener, HttpSessionListener,  
  20.         HttpSessionAttributeListener {  
  21.     // 声明一个ServletContext对象  
  22.     private ServletContext application = null;  
  23.   
  24.     public void contextInitialized(ServletContextEvent sce) {  
  25.         // 容器初始化时,向application中存放一个空的容器  
  26.         this.application = sce.getServletContext();  
  27.         this.application.setAttribute("alluser"new ArrayList());  
  28.     }  
  29.   
  30.     public void contextDestroyed(ServletContextEvent sce) {  
  31.     }  
  32.   
  33.     public void sessionCreated(HttpSessionEvent se) {  
  34.     }  
  35.   
  36.     public void sessionDestroyed(HttpSessionEvent se) {  
  37.         // 将用户名称从列表中删除  
  38.         List l = (List) this.application.getAttribute("alluser");  
  39.         String value = (String) se.getSession().getAttribute("uname");  
  40.         l.remove(value);  
  41.         this.application.setAttribute("alluser", l);  
  42.     }  
  43.   
  44.     public void attributeAdded(HttpSessionBindingEvent se) {  
  45.         // 如果登陆成功,则将用户名保存在列表之中  
  46.         List l = (List) this.application.getAttribute("alluser");  
  47.         l.add(se.getValue());  
  48.         this.application.setAttribute("alluser", l);  
  49.     }  
  50.   
  51.     public void attributeRemoved(HttpSessionBindingEvent se) {  
  52.     }  
  53.   
  54.     public void attributeReplaced(HttpSessionBindingEvent se) {  
  55.     }  
  56. }  




online.jsp 

Html代码     收藏代码
  1. <%@ page contentType="text/html;charset=gb2312"%>  
  2. <%@ page import="java.util.*"%>  
  3. <form action="online.jsp" method="post">  
  4. 用户名:  
  5. <input type="text" name="name">  
  6. <input type="submit" value="登陆">  
  7. <a href="logout.jsp">注销</a>  
  8. </form>  
  9. <!-- 向session接收输入的用户名 -->  
  10. <%  
  11.     if(request.getParameter("name")!=null)  
  12.         session.setAttribute("uname",request.getParameter("name")) ;  
  13. %>  
  14. <h2>在线人员</h2>  
  15. <hr>  
  16. <%  
  17.     List l = (List)application.getAttribute("allUser");  
  18.     for(Object o : l)  
  19.         out.println(o);  
  20. %>  



logout.jsp 

Html代码     收藏代码
  1. <%  
  2.     session.invalidate() ;  
  3. %>  

 

你可能感兴趣的:(在线人数)