session、application事件监听器实现在线用户列表

前台

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<script type="text/javascript">
window.onunload =function(){
     
}
</script>
<body>
<form action="Login?zhang=login" method="post">
    <ul>
       <li>用户名:<input type="text" name="userName"/></li>
       <li><input type="submit" value="登陆"/></li>
       <li><a href="Login?zhang=logout">用户注销</a></li>
    </ul>
    <ul>
       <li>当前在线用户</li>
       <c:forEach items="${userList}" var="userList">
        <li>${userList }</li>
       </c:forEach>
    </ul>
   </form>
</body>
</html>

监听器

package com.greendog.jiantingqi;

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;
/**
* 在线用户列表
* @author zhq
*
*/
public class Online implements ServletContextListener,
   HttpSessionListener, HttpSessionAttributeListener {
//声明一个servletContext对象
ServletContext application=null;
//用户若登陆后,又输入用户登陆,则下面的变量派上用场了
String lastUserName;
public String getLastUserName() {
   return lastUserName;
}
public void setLastUserName(String lastUserName) {
   this.lastUserName = lastUserName;
}
public void contextDestroyed(ServletContextEvent arg0) {
   System.out.println("*****容摧毁");
}
public void contextInitialized(ServletContextEvent arg0) {
   application = arg0.getServletContext();
   application.setAttribute("userList", new ArrayList());
   System.out.println("*****初始化容器,向application对象中加入一个list对象");
}
public void attributeAdded(HttpSessionBindingEvent arg0) {
   List userList=(List)application.getAttribute("userList");
   //String userName=(String)arg0.getValue();
   String userName=(String)arg0.getSession().getAttribute("userName");
   userList.add(userName);
   application.setAttribute("userList", userList);
   System.out.println("*****用户成功登陆-->"+userName);
   this.setLastUserName(userName);
}
public void attributeRemoved(HttpSessionBindingEvent arg0) {
  
}
public void attributeReplaced(HttpSessionBindingEvent arg0) {  
   String userName=(String)arg0.getSession().getAttribute("userName");
   List userList=(List)application.getAttribute("userList");
   userList.remove(this.getLastUserName());
   userList.add(userName);
   application.setAttribute("userList", userList);
   System.out.println("*****用户重写用户名了,"+getLastUserName()+"改为了-->"+userName);
   this.setLastUserName(userName);
}
public void sessionCreated(HttpSessionEvent se) {
   System.out.println("*****建立新的session连接,ID="+se.getSession().getId());
}
public void sessionDestroyed(HttpSessionEvent se) {
   String userName=(String)se.getSession().getAttribute("userName");
   List userList=(List)application.getAttribute("userList");
   userList.remove(userName);
   application.setAttribute("userList", userList);
   System.out.println("*****用户退出,用户名"+userName);
}

}

servlet

package com.greendog.servlet;

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

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Login extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
   this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
   String zhang=request.getParameter("zhang");
   if("login".equals(zhang)){
    this.login(request, response);
   }else if("logout".equals(zhang)){
    this.logout(request, response);
   }
}
public void login(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
   String userName=request.getParameter("userName");
   HttpSession session=request.getSession();
   session.setAttribute("userName", userName);
   ServletContext application=getServletContext();
   List userList=(List)application.getAttribute("userList");  
   request.setAttribute("userList", userList);
   request.getRequestDispatcher("login.jsp").forward(request, response);
}
public void logout(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
   HttpSession session=request.getSession();
   session.invalidate();
   ServletContext application=getServletContext();
   List userList=(List)application.getAttribute("userList");  
   request.setAttribute("userList", userList);
   request.getRequestDispatcher("login.jsp").forward(request, response);
}
}

监听器在web.xml中的配置

<listener>
<listener-class>com.greendog.jiantingqi.Online</listener-class>
</listener>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实验:内置对象使用 一、实验目的 1、掌握各个内置对象的含义; 2、理解并熟练应用sessionapplication对象。 二、实验内容 1、设计聊天室,在聊天室,需要通过JSP内置对象application来实时保存特定数量的当前聊天信息。 聊天室的设计包括:用户进行登录,选择聊天室,进行聊天,退出聊天室。 在聊天室用户只需输入一个用户名就可以进入聊天室,但是如果当前有人在使用用户名,那么就必须换一个唯一的用户名。 具体要求:  用户登录成功后,程序会要求用户选择聊天室。可以不设置用户自行建立聊天室的功能,而且在聊天途不能从一个聊天室切换到另一个聊天室。  进入聊天室后,用户可以从用户信息窗口看到该聊天室所有用户用户名,也可以在聊天窗口看到随时更新的聊天信息。用户可以给所有人或某一个聊天用户发送公共的聊天信息,这个聊天内容大家都可以看到。用户也可以给某个用户发送私人的聊天信息,这种信息属于私聊信息,只有发送者和接收者可以看到。此外,聊天窗口还会出现一些系统公告,比如某某上站、某某离开等消息,另外用户还可以自己定义聊天信息和聊天用户信息刷新的时间间隔。  在用户单击“退出”按钮后,页面关闭,同时applicationsession保存的信息都将丢失。 三、实验方法 1、用户登录信息使用request对象getParameter()方法得到用户登陆的一些信息; 2、公聊信息可以使用application对象,私聊信息使用session对象。 3、聊天的信息要不断刷新页面,使用户实时看到聊天信息。 4、用户退出时,有两种情况需要考虑:一是用户点击“退出”按钮,二是关闭浏览,强制退出窗口,可查阅windows感知浏览关闭的事件的相应方法。
以下是一个简单的Java Web应用程序使用Servlet监听统计在线用户的示例代码: 首先,需要创建一个Servlet监听,在该监听实现ServletContextListener接口,并在contextInitialized()方法初始化application对象,如下所示: ```java public class OnlineUserListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); List<String> onlineUsers = new ArrayList<String>(); context.setAttribute("onlineUsers", onlineUsers); } public void contextDestroyed(ServletContextEvent sce) { // do nothing } } ``` 在上面的代码,我们实现了ServletContextListener接口,并在contextInitialized()方法初始化了一个名为onlineUsers的List对象,并将其保存到application对象。这个List对象将用于保存在线用户的信息。 接下来,我们可以在用户登录时,将他的用户名添加到onlineUsers列表: ```java public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取用户信息 String username = request.getParameter("username"); String password = request.getParameter("password"); // 验证用户是否合法 // ... // 如果用户合法,将他的信息添加到在线用户列表 ServletContext context = request.getServletContext(); List<String> onlineUsers = (List<String>) context.getAttribute("onlineUsers"); onlineUsers.add(username); context.setAttribute("onlineUsers", onlineUsers); // 设置Session属性 HttpSession session = request.getSession(); session.setAttribute("username", username); // 跳转到用户主页 // ... } } ``` 在上面的代码,我们首先从ServletContext对象获取在线用户列表,并将用户用户名添加到列表。最后,我们将更新后的在线用户列表保存到application对象,并设置Session属性保存用户信息。 当用户退出时,我们可以从onlineUsers列表删除他的用户名,如下所示: ```java public class LogoutServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取Session属性 HttpSession session = request.getSession(); String username = (String) session.getAttribute("username"); // 从在线用户列表删除该用户 ServletContext context = request.getServletContext(); List<String> onlineUsers = (List<String>) context.getAttribute("onlineUsers"); onlineUsers.remove(username); context.setAttribute("onlineUsers", onlineUsers); // 注销Session session.invalidate(); // 跳转到登录页面 // ... } } ``` 在上面的代码,我们首先从Session获取当前用户用户名,然后从ServletContext对象获取在线用户列表,并从列表删除该用户。最后,我们将更新后的在线用户列表保存到application对象,并注销Session。 通过上述代码,我们可以在Java Web应用程序使用Servlet监听统计在线用户,并实现用户登录和退出的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值