javaee 使用监听器统计当前在线用户列表

本文展示了如何使用ServletContextListener监听服务器启动和关闭事件,初始化应用数据。同时,通过HttpSessionBindingListener监听用户登录和登出,管理在线用户列表。当用户登录时,如果不在在线列表中则添加,反之则移除,实现了简单的用户在线状态跟踪。
摘要由CSDN通过智能技术生成

在这里插入图片描述在这里插入图片描述
ServletContextListener 和 HttpSessionBindingListener 需要配和使用

TestServletContextListener

package com.yyy.listener;

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

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.yyy.po.Users;

/**
 * Application Lifecycle Listener implementation class TestServletContextListener
 *
 */
@WebListener
public class TestServletContextListener implements ServletContextListener {

    /**
     * Default constructor. 
     */
    public TestServletContextListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("服务器关闭了");
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
    	// TODO Auto-generated method stub
    			//初始化数据 变量  数据库连接信息  连接池的信息
    			ServletContext application=  arg0.getServletContext();
    			
    			application.setAttribute("count", 0);
    			
    			//存放所有登录的用户
    			List<Users> onLineUserList=new ArrayList<Users>();
    			
    			application.setAttribute("onLineUserList", onLineUserList);
    			
    			
    			System.out.println("服务器启动了");
    }
	
}

TestHttpSessionBindingListener

package com.yyy.listener;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import com.yyy.po.Users;

/**
 * Application Lifecycle Listener implementation class TestHttpSessionBindingListener
 *
 */
@WebListener
public class TestHttpSessionBindingListener implements HttpSessionBindingListener {
	private Users user;
	private List<Users> onLineUserList;
    /**
     * Default constructor. 
     */
	public TestHttpSessionBindingListener() {
        // TODO Auto-generated constructor stub
    }
    public TestHttpSessionBindingListener(Users user) {
    	this.user=user;
        // TODO Auto-generated constructor stub
    }
    public boolean isUserExists()
	{
		for(Users myuser:onLineUserList)
		{
			if(myuser.getUname().equals(user.getUname()))
				return true;
		}
		
		return false;
	}
    public void printUserList()
	{
		 System.out.println("当前用户列表:");
		 for(Users user:onLineUserList)
		 {
			 System.out.println(user.getUname());
		 }
	}

	/**
     * @see HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
     */
    @Override
    public void valueBound(HttpSessionBindingEvent arg0)  { 
         // TODO Auto-generated method stub
    	// TODO Auto-generated method stub
    			ServletContext application= arg0.getSession().getServletContext();
    			onLineUserList=  (List<Users>) application.getAttribute("onLineUserList");
    			
    			//判断当前用户是否在用户列表中,不存在  则添加到在线列表中		
    			if(!isUserExists())
    			{
    				onLineUserList.add(user);
    				
    				System.out.println("用户:"+user.getUname()+"上线了");
    				
    				//存回到application变量
    				application.setAttribute("onLineUserList", onLineUserList);
    				
    				//打印用户列表
    				printUserList();
    			}
    }

	/**
     * @see HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
     */
    @Override
	public void valueUnbound(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub
		ServletContext application= arg0.getSession().getServletContext();
		if(isUserExists())
		{
			onLineUserList.remove(user);
			
			System.out.println("用户:"+user.getUname()+"下线了");
			
			//存回到application变量
			application.setAttribute("onLineUserList", onLineUserList);
			
			//打印用户列表
			printUserList();
		}
		
	}
	
}

LoginServlet

package com.yyy.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.yyy.listener.TestHttpSessionBindingListener;
import com.yyy.po.Users;
import com.yyy.util.DbHelper;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
				//response.getWriter().append("Served at: ").append(request.getContextPath());
			
				//获得用户信息
				String uname=request.getParameter("uname");
				String pwd=request.getParameter("pwd");
				//判断是否登录成功
				String sql="select * from user where uname=? && upwd=?";
				List<Object> paramList=new ArrayList<Object>();
				paramList.add(uname);
				paramList.add(pwd);	
				DbHelper dbHelper=new DbHelper();
				List<Map<String, Object>> map=  dbHelper.executeQuery(sql, paramList);
				if(map!=null && map.size()>0)
				{
				   
					
						Users user=new Users();
						user.setUname(uname);
						user.setUpwd(pwd);
						//登录成功
						//创建一个HttpSessionBindingListener对象用来监听当前用户
						TestHttpSessionBindingListener httpSessionBingingListener=new TestHttpSessionBindingListener(user);
					
						HttpSession session=request.getSession();
						
						session.setAttribute("user", httpSessionBingingListener);
						
					
						response.sendRedirect("index.jsp");
					
				}
				else
					response.getWriter().println("用户名或密码出错");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值