java web笔记之Listener显示在线用户

1.静态属性类

package com.wang.online;

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

import javax.servlet.http.HttpSession;

public class ApplicationConstants {
	
	public static Map<String,HttpSession> SESSION_MAP = new HashMap<String,HttpSession>();//索引所有的session
	
	public static int CURRENT_LOGIN_COUNT = 0;//当前登录的用户总数
	
	public static int TOTAL_HISTORY_COUNT = 0;//历史访客总数
	
	public static Date START_DATE = new Date();//服务器启动事件
	
	public static Date MAX_ONLINE_COUNT_DATE = new Date();//最高在线时间
	
	public static int MAX_ONLINE_COUNT = 0;//最高在线人数
	

}

2.使用ServletContextListener监听器来监听服务器的启动和关闭。

package com.wang.online;

import java.util.Date;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyContextListener implements ServletContextListener {

    public MyContextListener() {
        // TODO Auto-generated constructor stub
    }

    public void contextInitialized(ServletContextEvent event)  { 
         // 服务器启动时被调用
    	ApplicationConstants.START_DATE = new Date();//记录启动时间
    }
    public void contextDestroyed(ServletContextEvent event)  { 
         // 服务器被关闭时调用
    	ApplicationConstants.START_DATE = null;//清空结果,也可以保存
    	
    	ApplicationConstants.MAX_ONLINE_COUNT_DATE = null;
    }
	
}

3.当Session的personInfo属性发生变化的时候,维护用户的登录与注销。

package com.wang.online;

import java.util.Date;

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;

public class MySessionListener implements HttpSessionListener,HttpSessionAttributeListener {

    public MySessionListener() {
        // TODO Auto-generated constructor stub
    }

    public void sessionCreated(HttpSessionEvent sessionEvent)  { 
         //Session创建时被调用
    	HttpSession session = sessionEvent.getSession();
    	ApplicationConstants.SESSION_MAP.put(session.getId(), session);//保存session
    	ApplicationConstants.TOTAL_HISTORY_COUNT++;//访问人数增加
    	
    	//如果当前在线人数超过历史记录
    	if(ApplicationConstants.SESSION_MAP.size()>ApplicationConstants.MAX_ONLINE_COUNT){
    		ApplicationConstants.MAX_ONLINE_COUNT = ApplicationConstants.SESSION_MAP.size();//更新最大在线人数
    		ApplicationConstants.MAX_ONLINE_COUNT_DATE = new Date();//更新时间
    	}
    	
    }

    public void sessionDestroyed(HttpSessionEvent sessionEvent)  { 
         // session被销毁时调用
    	HttpSession session = sessionEvent.getSession();
    	ApplicationConstants.SESSION_MAP.remove(session.getId());//移除session记录
    }

	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		// 添加属性时被调用
		if(event.getName().equals("personInfo")){
			ApplicationConstants.CURRENT_LOGIN_COUNT++;
			
			HttpSession session = event.getSession();
			//查找该账号有么有在其他机器上登录
			for (HttpSession sess : ApplicationConstants.SESSION_MAP.values()) {
				//如果该账号已经在其他机器上登录了,则以前的登录失效
				if(event.getValue().equals(sess.getAttribute("personInfo")) && session.getId()!= sess.getId()){
					sess.invalidate();//使session失效
				}
				
			}
		}
		
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		// 移除属性时被调用
		if(event.getName().equals("personInfo")){
			ApplicationConstants.CURRENT_LOGIN_COUNT--;
			
		}
		
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		// 修改属性时被调用
				if(event.getName().equals("personInfo")){
					HttpSession session = event.getSession();
					//查找该账号有么有在其他机器上登录
					for (HttpSession sess : ApplicationConstants.SESSION_MAP.values()) {
						//如果该账号已经在其他机器上登录了,则以前的登录失效
						if(event.getValue().equals(sess.getAttribute("personInfo")) && session.getId()!= sess.getId()){
							sess.invalidate();//使session失效
						}
						
					}
				}
		
	}
	
}

4.监听request主要是记录客户的ip地址、访问次数等。也可以记录用户访问的url。

package com.wang.online;

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

public class MyRequestLitener implements ServletRequestListener {

    public MyRequestLitener() {
        // TODO Auto-generated constructor stub
    }
    public void requestDestroyed(ServletRequestEvent arg0)  { 
         // TODO Auto-generated method stub
    }

    public void requestInitialized(ServletRequestEvent event)  { 
         // 创建request时被调用
    	HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
    	HttpSession session = request.getSession(true);//对应的session
    	session.setAttribute("ip", request.getRemoteAddr());//记录ip地址
    	
    	String uri = request.getRequestURI();
    	String[] suffix = {".html",".do",".jsp",".action"};//指定后缀
    	
    	for (int i = 0; i < suffix.length; i++) {
    		if(uri.endsWith(suffix[i])){
    			break;//程序继续运行
    		}
    		if(i ==suffix.length -1){
    			return;//否则返回
    		}
			
		}
    	Integer activeTimes = (Integer) session.getAttribute("activeTime");
    	if(activeTimes == null){
    		activeTimes = 0;
    	}
    	session.setAttribute("activeTimes", activeTimes+1);//更新访问次数
    }
	
}
5.online.jsp

<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@page import="com.wang.online.ApplicationConstants"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <jsp:directive.page import="com.wang.singleton.PersonInfo"/>
    <jsp:directive.page import="com.wang.online.ApplicationConstants"/>
      <jsp:directive.page import="java.util.Date"/>
       <jsp:directive.page import="java.text.DateFormat"/>
   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>
</head>
<body>
   服务器启动时间:
   <%=DateFormat.getDateTimeInstance().format(ApplicationConstants.START_DATE)%>,
   累计共接待过<%=ApplicationConstants.TOTAL_HISTORY_COUNT %> 访客<br/>
      同时在线人数最多为<%=ApplicationConstants.MAX_ONLINE_COUNT%> 人<br/>
      发生在 <%=DateFormat.getDateTimeInstance().format(ApplicationConstants.MAX_ONLINE_COUNT_DATE)%>.<br/>
      目前在线总数:<%=ApplicationConstants.SESSION_MAP.size() %>,登录用户:
      <%=ApplicationConstants.CURRENT_LOGIN_COUNT %>.<br/>
	 <table border=1>
	 	<tr>
	 		<th>jsessionid</th>
	 		<th>account</th>
	 		<th>creationTime</th>
	 		<th>lastAccessedTime</th>
	 		<th>new</th>
	 		<th>activeTimes</th>
	 		<th>ip</th>
	 	</tr>
	 	<%
	 		for(String id:ApplicationConstants.SESSION_MAP.keySet()){
	 			HttpSession sess = ApplicationConstants.SESSION_MAP.get(id);
	 			PersonInfo personInfo =(PersonInfo)sess.getAttribute("personInfo");
	 	%>
	 	<tr <%=session == sess ?"bgcolor=#DDDDDD":"" %>>
	 		<td><%=id%></td>
	 		<td><%=personInfo==null?" ":personInfo.getAccount()%></td>
	 		<td><%=DateFormat.getDateTimeInstance().format(sess.getCreationTime())%></td>
	 		<td><%=DateFormat.getDateTimeInstance().format(sess.getLastAccessedTime())%></td>
	 		<td><%=sess.isNew()%></td>
	 		<td><%=sess.getAttribute("activeTimes")%></td>
	 		<td><%=sess.getAttribute("ip")%></td>
	 	
	 	</tr>
	 	<%}%>
	 
	 </table>

</body>
</html>
6.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>loginListener</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <listener>
    <listener-class>com.wang.singleton.LoginSessionListener</listener-class>
  </listener>
  <listener>
    <listener-class>com.wang.online.MyContextListener</listener-class>
  </listener>
  <listener>
    <listener-class>com.wang.online.MySessionListener</listener-class>
  </listener>
  <listener>
    <listener-class>com.wang.online.MyRequestLitener</listener-class>
  </listener>
</web-app>
源代码地址: http://download.csdn.net/detail/wangxuewei111/8530549



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值