您的位置:首页 > 其它

日常笔记——关于在线人数统计问题

2017-07-13 13:16 363 查看
SessionCounter.java

package com.my.count;

import javax.servlet.ServletContext;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.context.ApplicationContext;

/**
* Application Lifecycle Listener implementation class SessionCounter
*
*/
@WebListener
public class SessionCounter implements HttpSessionListener {
//total为访问总人数,onLineUser为在线人数
private static int onLineUser=0;
public static int total=82553;

public SessionCounter() {
// TODO Auto-generated constructor stub
}
@Override
public void sessionCreated(HttpSessionEvent event)
{
System.out.println("sessionCreated");
ServletContext sct = event.getSession().getServletContext();

Integer onLineUser = (Integer) sct.getAttribute("onLineUser");
if (onLineUser== null) {
onLineUser = new Integer(1);
}else {
int count = onLineUser.intValue();
onLineUser = new Integer(count+1);
}

/*Integer total = (Integer) sct.getAttribute("total");
int countTotal = total.intValue();
total = new Integer(countTotal+1);*/
//Integer total = (Integer) sct.getAttribute("total");
sct.setAttribute("onLineUser", onLineUser);
sct.setAttribute("total", total++);

}
@Override
public void sessionDestroyed(HttpSessionEvent event){
System.out.println("sessionDestroyed");
ServletContext sct = event.getSession().getServletContext();
Integer onLineUser = (Integer) sct.getAttribute("onLineUser");
if (onLineUser == null) {
onLineUser = new Integer(0);
}else {
int count = onLineUser.intValue();
onLineUser = new Integer(count-1);
System.out.println("----------------------"+onLineUser);
}
// Integer total = (Integer) sct.getAttribute("total");
sct.setAttribute("onLineUser", onLineUser);
sct.setAttribute("total", total);
//销毁session
// HttpSession session = event.getSession();
// session.invalidate();

}
public static int getCount() {
return onLineUser;
}

public static void setCount(int onLineUser) {
SessionCounter.onLineUser =onLineUser;
}

}


配置web.xml(要写在配置文件较前位置,先执行,此处写在SpringMvc的Listerner之前)

`

<listener>

<listener-class>

com.my.count.SessionCounter

</listener-class>

</listener>

///////////////////////////

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<session-config>

<session-timeout>1</session-timeout>

</session-config>

//销毁session时间配置------一分钟


销毁session时间配置——一分钟

总结:sessionDestroyed()不执行的原因

1、listener在web.xml的配置文件中放置位置不正确

2、销毁时间过长,需设置销毁时间
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Listener