使用监听器统计当前的在线用户数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ITdevil/article/details/77895670

准备工作:

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

在使用监听器完成统计当前在线用户数功能时,应该首先明确使用哪些监听器。这里我们使用的监听器是:

1:ServletContextListener 

       它的作用:监听ServletContext对象的创建和销毁,既然我们要监听ServletContext对象,我们就要知道它什么时候创建和什么时候销毁(即ServletContext的生命周期)

       生命周期---创建:web应用在服务器上成功部署运行的时候,服务器会为每个web应用创建一个ServletContext。

                       ---销毁:服务器正常关闭或是web应用在服务器上被移除。

       方法:contextInitialized(ServletContextEvent arg0):监听ServletContext对象的初始化

                  contextDestroyed(ServletContextEvent arg0):监听ServletContext对象的销毁



2:HttpSessionListener

      它的作用:监听HttpSession创建和销毁,同要也要知道其生命周期,下面就不再重复

      生命周期:---创建:在java代码中,可以认为第一次调用request.getSession()的时候,或着在jsp中,可以认为第一次访问项目下的任何一个jsp页面

                          ---销毁:服务器非正常关闭,超时,手动销毁调用 session.invalidate()

      方法:sessionCreated(HttpSessionEvent arg0):监听session对象的创建

                  sessionDestroyed(HttpSessionEvent arg0):监听session对象的销毁


3:HttpSessionAttributeListener

      它的作用:监听HttpSession中属性的变化。具体讲就是,当我们往session中添加一些属性的时候,我们的监听器就可以监听到session中的属性变化,比如及进行如下操作

session.setAttribute("username"),监听器就知道了我们向session中添加一个用户名。

      方法:attributeAdded(HttpSessionBindingEvent arg0):监听session中是否有属性添加进来

                  attributeReplaced(HttpSessionBindingEvent arg0):监听session中的属性被替换

                  attributeRemoved(HttpSessionBindingEvent arg0):监听session中的某些属性是否被移除


demo测试:

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

思路:

监听第一步:在我们项目部署在tomcat上启动成功时,就会创建一个servletContext对象,这时我们的监听器就会监听到,我们会在这个servletContext对象中放置一个集合,用于存储用户名。

监听第二步:首先我们在前台页面完成一个form表单,用于提交我们的请求,请求中携带者参数--用户名。当请求到达servlet中以后,我们要将用户名添加到session中,这是监听器又会监听到session中的属性发生变化,session存入了一个用户名.然后我们会将新登录的用户的用户名存入到list集合中,当再有用户登录时,依次将用户名存入集合。

监听第三布:当用户点击注销登录时,会请求到注销登录的servlet中,在该servlet中,手动销毁了session,销毁以后,监听器就可以监听到session对象的销毁。然后再从servletContext对象中的集合中把该登录的用户移除。


重点:监听器

import java.util.ArrayList;
import java.util.List;

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

/**
 * 在线人数统计监听实现类
 *
 */
public class OnlineListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
    
	private ServletContext application=null;
	
	public void contextInitialized(ServletContextEvent arg0)  { 
        //初始化一个applcation对象
		this.application=arg0.getServletContext();
		//设置一个列表属性,用于保存在线用户名
		this.application.setAttribute("online", new ArrayList<String>());
		System.out.println("监听到了application对象的创建。。。。");
		
    }
    
    public void contextDestroyed(ServletContextEvent arg0)  { 
        
    }
	
    
    public void attributeRemoved(HttpSessionBindingEvent arg0)  { 
    }
    
    
     //往会话中添加属性(用户名)时会监听到
    public void attributeAdded(HttpSessionBindingEvent arg0)  { 
    	//获取用户列表          	
    	List<String> online=(List<String>)this.application.getAttribute("online");
        //如果存到session的是用户名,不是其他
    	if("username".equals(arg0.getName())){
        	//将当前用户名添加到列表中
    		online.add((String)arg0.getValue());
        }
    	//将添加后的用户名重新设置到servletContext的用户列表中
    	this.application.setAttribute("online",online);
    	System.out.println("监听到了session中添加了属性。。。。");
    }
    
    public void attributeReplaced(HttpSessionBindingEvent arg0)  { 
        
    }
	
	
    public void sessionCreated(HttpSessionEvent arg0)  { 
        
    }

	//会话销毁时会调用的方法
    public void sessionDestroyed(HttpSessionEvent arg0)  { 
        List<String> online =(List<String>)this.application.getAttribute("online");
        //取得当前的用户名
        String username=(String)arg0.getSession().getAttribute("username");
        //将此用户名从列表中删除
        online.remove(username);
        //将删除后的列表重新添加daoapplication中
        this.application.setAttribute("online",online);
    }




前端登录页面:(提交请求,到LoginServlet中)
<body>
    <h1>监听器</h1> 
      <form action = "login" method = "post">  
                                   用户名:<input type ="text" name = "username"/>  
   			<input type = "submit" value = "登录"/><br/><br/>   
   			<a href="${pageContext.request.contextPath}/Logout.jsp">注销页面</a>    
      </form>  
</body>

LoginServlet:处理请求(将从请求中拿到的用户名保存到session对象当中),并向浏览器做出相应,跳转到展示信息页面

public class LoginServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 request.setCharacterEncoding("utf-8");//设置相应内容类型  
         
	        String username= request.getParameter("username");//获取请求参数中的用户名  
	          
	        //往session中添加属性,会触发HttpSessionListener中的attributeAdded方法  
	        if(username != null && !username.equals("")) {     
	            request.getSession().setAttribute("username",username);    
	            System.out.println("将username放到了session中。。。。");
	        }  
	        response.sendRedirect(request.getContextPath()+"/show.jsp");
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}


当点击注销时,会进入到该servlet中,手动销毁session对象,会话结束。

public class LogoutServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");  
        
        //销毁会话,会触发SessionLinstener中的sessionDestroyed方法  
        request.getSession().invalidate();   
          
        response.sendRedirect(request.getContextPath()+"/show.jsp");  
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}


show.jsp页面(展示当前在线用户数和用户名)

<body>
      <h3>在线用户:</h3>
      <hr>
      <%
            List<String> online = (List<String>)getServletContext().getAttribute("online");
				      %>
				      <li><%=online.size()%></li>
				   <%
		      Iterator<String> it = online.iterator();
		      
		      while(it.hasNext()){
			     %>
			        <li><%=it.next() %></li>
			     <%
		      }
      %>
      
</body>


                  

 


猜你喜欢

转载自blog.csdn.net/ITdevil/article/details/77895670