javaWeb作业之用监听器实现一个统计网站在线人数的功能

二:用监听器实现一个统计网站在线人数的功能。
提示:创建一个监听器类,通过ServletContextListener监听,当容器启动时,在
ServletContext中添加一个List,用来准备存放在线的用户名;
然后,可以通过HttpSessionAttributeListener监听,当用户
登录成功把用户名设置到Session中时同时将用户名存放到ServletContext
中的List列表中;最后通过HttpSessionListener监听,当会话

注销时将用户名从应用上下文范围的List列表中删除。

user类

package org.listenerdemo;

import java.io.Serializable;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class User implements HttpSessionBindingListener,Serializable{
        private String name;
        public User(){
        	
        }
        public User(String name){
        	 this.name = name;
        }
		
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
	
	
		@Override
		public void valueBound(HttpSessionBindingEvent arg0) {
			  System.out.println("User对象被绑定了...");
		}
		@Override
		public void valueUnbound(HttpSessionBindingEvent arg0) {
			  System.out.println("User对象解除绑定了...");
		}
		
}
获取监听到的session用户
package org.listenerdemo;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener
public class MyHttpSessionListener implements HttpSessionAttributeListener{

	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
			String name=event.getName();   // 获取属性名
			Object value=event.getValue();   // 获取属性值
			System.out.println("添加(add)session属性了,属性名是:"+name+";属性值是:"+value);
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent arg0) {
		
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent arg0) {
		
	}

}
每创建一个session就会被容器监听器监听

package org.listenerdemo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
@WebListener
public final class MyServletContextListener implements ServletContextListener {
     
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("进入监听容器...");
		     //通过事件源对象得到事件源
		     ServletContext application = sce.getServletContext();
		     //创建一个集合存储所有session对象
//		     final List list = new ArrayList();
		     final List list = Collections.synchronizedList(new ArrayList());
		     //把集合放到application域中
		     application.setAttribute("sessions", list);
		     //创建一个计时器对象
		     Timer t = new Timer();
		     t.schedule(new TimerTask(){

				@Override
				public void run() {
					System.out.println("开始扫描了...");
					  for (Iterator iterator = list.iterator(); iterator
							.hasNext();) {
							HttpSession session = (HttpSession) iterator.next();
							 long l = System.currentTimeMillis()-session.getLastAccessedTime();
							    if(l>5000){//如果时间大于5秒,session销毁
							    	System.out.println("session移除了"+session.getId());
							    	   session.invalidate(); //把session销毁
							    	 //  list.remove(session);//从list中移除session
							    	  iterator.remove();
							    }
					}
//                       		for (HttpSession session : list) {
//								    long l = System.currentTimeMillis()-session.getLastAccessedTime();
//								    if(l>5000){//如果时间大于5秒,session销毁
//								    	   session.invalidate(); //把session销毁
//								    	   list.remove(session);//从list中移除session
//								    }
//							}			
				}
		    	 
		     }, 2000, 5000);//延迟两秒,每间隔五秒执行一次
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		      System.out.println("监听器容器销毁了...");
	}

}
将获取到的session存到list集合中
package org.listenerdemo;


import java.util.List;


import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class MySessionListener implements HttpSessionListener {

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		  HttpSession session = se.getSession();
		  //得到application对象中的list集合
		  ServletContext application = session.getServletContext();
		//得到session对象,并放到list集合中
		  List list = (List) application.getAttribute("sessions");
		  list.add(session);
		 System.out.println("添加了"+session.getId());
		  
	}
    
	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
             System.out.println("session销毁了..");
	}

}

网页:

<%@page import="org.listenerdemo.User"%>
<%@page import="java.net.URLDecoder"%>
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>




a界面


      
用户名: 注销
<% if(request.getParameter("name")!=null) session.setAttribute("sessionInfo","会话范围的属性值"); session.setAttribute("user",new User(request.getParameter("name"))) ; %> ${u }




你可能感兴趣的:(java,servlet,javaWeb)