Session统计系统当前在线用户数

第1步 准备session监听器处理类。

package com.ane56.common.util;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;


/**
 * Created by liyang on 2016/11/28.
 */
public class SessionListener implements HttpSessionAttributeListener {
    /**
     * 定义监听的session属性名.
     */
    public final static String LISTENER_NAME = "_login";

    /**
     * 定义存储客户登录session的集合.
     */
    private static List sessions = new ArrayList();

    /**
     * 加入session时的监听方法.
     *
     * @param sbe
     *            session事件
     */
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        if (LISTENER_NAME.equals(sbe.getName())) {
            sessions.add(sbe.getValue());
        }
    }

    /**
     * session失效时的监听方法.
     *
     * @param sbe
     *            session事件
     */
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        if (LISTENER_NAME.equals(sbe.getName())) {
            sessions.remove(sbe.getValue());
        }
    }

    /**
     * session覆盖时的监听方法.
     *
     * @param sbe
     *            session事件
     */
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
    }

    /**
     * 返回客户登录session的集合.
     *
     * @return
     */
    public static List getSessions() {
        return sessions;
    }
}

中的_login就是设定的特殊session属性,当然你可以改成别的名字。 

第2步 将session监听器配置到web.xml中.

 <!-- 通过listener来统计在线人数-->
    <listener>
        <listener-class>com.common.util.SessionListener</listener-class>
    </listener >

第3步 当用户登录时监听用户。

//记入session监听器  
session.setAttribute(com.stephen.filter.SessionListener.LISTENER_NAME,
    new OnlineSession(request.getRemoteAddr(),userName,new Date().toString()));  

注意在上面的代码中使用了新的OnlineSession类,OnlineSession类封装了登录用户的信息(如用户ip,用户名,登录时间等). 

/**
 * Created by liyang on 2016/11/28.
 */
public final class OnlineSession {


    /**
     * 客户计算机的ip.
     */
    private String ip = null;
    /**
     * 客户登录名.
     */
    private String loginId = null;
    /**
     * 客户登录系统时间.
     */
    private String onlineTime = null;

    private String timeCompare = null;

...

第4步 显示在线用户的情况。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";
%>
<html>
<head>
<title>user manage</title>
<%@ include file="../common/common.jsp"%>
    <script type="application/javascript">
		function date2str(x, y) {
			var z = {
				y: x.getFullYear(),
				M: x.getMonth() + 1,
				d: x.getDate(),
				h: x.getHours(),
				m: x.getMinutes(),
				s: x.getSeconds()
			};
			return y.replace(/(y+|M+|d+|h+|m+|s+)/g, function(v) {
				return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-(v.length > 2 ? v.length : 2))
			});
		}
		function fmt_time(value){
			var unixTimestamp = new Date(value);
			return date2str(unixTimestamp, "yyyy-MM-d h:m:s")
		}
    </script>
</head>
    <body>
        <table id="listener" class="easyui-datagrid" style="width:100%;height:100%" data-options="fit:true,rownumbers:true,singleSelect:true,url:'../user/sessionListener',method:'POST',pagination:true,pageSize:20">
            <thead>
            <tr>
                <th data-options="field:'loginId',width:100,sortable:true,align:'center'" >工号</th>
                <th data-options="field:'ip',width:80,sortable:true,align:'center'"  >登录IP</th>
                <th data-options="field:'onlineTime',width:240,sortable:true,align:'center',formatter:fmt_time" >登录时间</th>
				<th data-options="field:'timeCompare',width:240,sortable:true,align:'center'" >登录时长</th>
            </tr>
            </thead>
        </table>
    </body>
</html>

第5步 在线用户登出,清除session记录。

	@RequestMapping("logout")
	public void logout(HttpSession session) {
        //清楚session相关记录
		
        session.removeAttribute(com.ane56.common.util.SessionListener.LISTENER_NAME);
	}

 

转载于:https://my.oschina.net/ytliyang/blog/803579

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值