java Session统计在线用户,并且显示在线用户
1.http://www.jspcn.net/htmlnews/11049329478121583.html 监听器
2.session.invalidate() ,session才会destroy
3.HttpSessionListener: 这个监听取不到session里面的值
http://hi.baidu.com/tianshiyeben/blog/item/17d43923d695d042ad34de36.html
http://www.family168.com/tutorial/jsp/html/jsp-ch-04.html#jsp-ch-04-02 在线列表实例
下面的代码可以获取上线,下线的在线列表 :
public class OnlineListener implements HttpSessionListener ,HttpSessionAttributeListener{
public void sessionCreated(HttpSessionEvent event) {//只要一打开浏览器就会执行 ,没有登陆也会执行.
}
public void sessionDestroyed(HttpSessionEvent event) {//只有超时,invalidate()才会执行
HttpSession se=event.getSession();
OnlineManager.getInstance().removeSession(se); //从列表中删除
// System.out.println("remove session....................");//为什么浏览窗口关闭了,没有执行啊???
}
public void attributeAdded(HttpSessionBindingEvent event) {//如果登陆成功, 就把上线 用户添加 到列表.
HttpSession se=event.getSession();
String name=event.getName();
String value=(String)event.getValue();
if("username".equals(name)){
OnlineManager.getInstance().addSession(se); //添加
}
}
}
public class OnlineManager {
private static OnlineManager om;
private Map<String,HttpSession> sessions;
private OnlineManager(){
sessions=new HashMap<String,HttpSession>();//为什么没有共用一个sessions;
}
public static OnlineManager getInstance(){
if(om==null){
om=new OnlineManager();
}
return om;
}
public void addSession(HttpSession se){
String key=(String)se.getAttribute("username");
sessions.put(key, se);
System.out.println("add 1 : "+sessions.size());
}
public void removeSession(HttpSession se){
String key=(String)se.getAttribute("username");
//sessions.remove(key); //这个只是把key=null
sessions.remove(sessions.get(key));
System.out.println("remove 1 : " +"key:"+key+sessions.size());
System.out.println(sessions);
}
}
------------------------
第二种方法实现在线,下线:
public class BindSession implements HttpSessionBindingListener {
private String username;
public BindSession(String username){
this.username=username;
}
public void valueBound(HttpSessionBindingEvent event) {
HttpSession session = event.getSession();
// String name=(String)session.getAttribute("name");
ServletContext application = session.getServletContext();
// 把用户名放入在线列表
List onlineUserList = (List) application.getAttribute("onlineUserList");
// 第一次使用前,需要初始化
if (onlineUserList == null) {
onlineUserList = new ArrayList();
application.setAttribute("onlineUserList", onlineUserList);
}
onlineUserList.add(this.username);
System.out.println("valueBound: .........."+onlineUserList.size());
}
public void valueUnbound(HttpSessionBindingEvent event) {
HttpSession session = event.getSession();
// String name=(String)session.getAttribute("name");
ServletContext application = session.getServletContext();
// 从在线列表中删除用户名
List onlineUserList = (List) application.getAttribute("onlineUserList");
onlineUserList.remove(this.username);
System.out.println(this.username + "退出。");
}
}
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name=req.getParameter("name");
String pass=req.getParameter("password");
boolean isLogin=false;
int len=set.size();
for(int i=0;i<len;i++){
if(set.containsKey(name)&&set.containsValue(pass)){
isLogin=true;
}
}
if(isLogin){
req.getSession().setAttribute("username", name);
System.out.println("login ...username="+name);
//BindListener 的使用:
BindSession bl=new BindSession(name);
req.getSession().setAttribute("lis", bl);
resp.sendRedirect("index.jsp");
}
else{
resp.sendRedirect("login.jsp");
}
java web 在线用户统计
2011-02-16 17:24:24| 分类: FilterAndListene | 标签:public import session person td |字号大中小 订阅
看一下效果图先:
页面有点简陋,哈哈..大家将就着看吧,我美工不行啊,哈哈...
这个也是用了各种Listener实现的,看一下代码吧,相信一看都能明白了。
先看页面代码,登录页面:
<%@ page language="java" import="java.util.*,com.vo.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
PersonInfo person = (PersonInfo)session.getAttribute("person");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登录</title>
</head>
<body>
<form action="login.jsp?action=login" method="post">
用户名:<input type="text" name="username">
密码:<input type="text" name="password">
<input type="submit" value="登录">
</form>
</body>
</html>
login.jsp
<%@ page language="java" import="com.vo.*" pageEncoding="utf-8"%>
<%
String para = request.getParameter("action");
if(para!=null){
if(para.equals("login")&¶.trim().length()>0){
String username = request.getParameter("username");
String password = request.getParameter("password");
String ip = request.getRemoteAddr();
PersonInfo person = new PersonInfo();
person.setUsername(username);
person.setPassword(password);
person.setIp(ip);
session.setAttribute("person",person);
response.sendRedirect("online.jsp");
return;
}else if(para.equals("out")&¶.trim().length()>0){
session.removeAttribute("person");
response.sendRedirect(request.getRequestURI());
return;
}
}else{
response.sendRedirect("index.jsp");
return;
}
%>
online.jsp
<%@ page language="java" import="java.util.*,java.text.*,com.vo.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'online.jsp' starting page</title>
</head>
<body>
服务器启动时间:<%=DateFormat.getTimeInstance().format(ApplicationConstants.START_DATE) %><br>
累计共接待过:<%=ApplicationConstants.TOTAL_HISTORY_COUNT %>访客<br>
同时在线人数:<%=ApplicationConstants.MAX_ONLINE_COUNT %>
发生在<%=DateFormat.getDateTimeInstance().format(ApplicationConstants.MAX_ONLINE_COUNT_DATE) %><br>
目前在线人数<%=ApplicationConstants.SESSION_MAP.size() %>
登录用户<%=ApplicationConstants.CURRENT_LOGIN_COUNT %>
<table border=1>
<tr>
<td>sessionId </td>
<td>用户名</td>
<td>登录时间</td>
<td>访问次数</td>
<td>ip</td>
</tr>
<%for(String id : ApplicationConstants.SESSION_MAP.keySet()){
HttpSession sess = ApplicationConstants.SESSION_MAP.get(id);
PersonInfo person = (PersonInfo)sess.getAttribute("person");
%>
<tr>
<td><%=id %></td>
<td><%=person==null ? " " : person.getUsername() %></td>
<td><%=DateFormat.getTimeInstance().format(sess.getCreationTime()) %></td>
<td><%=sess.getAttribute("activityTimes") %></td>
<td><%=sess.getAttribute("ip") %></td>
</tr>
<%}%>
</table>
</body>
</html>
vo实体类:
package com.vo;
import java.io.Serializable;
public class PersonInfo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
private String ip;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj==null||!(obj instanceof PersonInfo)){
return false;
}
return username.equals(((PersonInfo)obj).getUsername());
}
}
ApplicationConstants 定义各种常量
package com.vo;
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 int MAX_ONLINE_COUNT = 0;//最大在线访客数量
public static Date START_DATE = new Date();//服务器启动时间
public static Date MAX_ONLINE_COUNT_DATE = new Date();//达到最大访客量的日期
}
SessionListener:
package com.listener;
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;
import com.vo.ApplicationConstants;
public class MySessionListener implements HttpSessionListener,
HttpSessionAttributeListener {
//session创建的时候调用
public void sessionCreated(HttpSessionEvent sessionEvent) {
// TODO Auto-generated method stub
//新创建的session
HttpSession session = (HttpSession)sessionEvent.getSession();
//保存session
ApplicationConstants.SESSION_MAP.put(session.getId(),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();
}
}
//session销毁的时候调用
public void sessionDestroyed(HttpSessionEvent sessionEvent) {
// TODO Auto-generated method stub
//即将被销毁的session
HttpSession session = sessionEvent.getSession();
//从map中将sesion的索引删除
ApplicationConstants.SESSION_MAP.remove(session.getId());
}
//添加属性的时候被调用
public void attributeAdded(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
//如果是person
if(event.getName().equals("person")){
//当前在线人数++
ApplicationConstants.CURRENT_LOGIN_COUNT++;
//得到session
HttpSession session = event.getSession();
//查询该账户有没有在别的机器上登录
for(HttpSession sess:ApplicationConstants.SESSION_MAP.values()){
if(event.getValue().equals(sess.getAttribute("person"))
&&sess.getId()!=session.getId()){
sess.invalidate();//销毁session
}
}
}
}
//移除属性是被调用
public void attributeRemoved(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
if(event.getName().equals("person")){
ApplicationConstants.CURRENT_LOGIN_COUNT--;//当前用户总数--
}
}
//修改的时候调用
public void attributeReplaced(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
if(event.getName().equals("person"))
{
HttpSession session = event.getSession();
//重新登录session
for(HttpSession sess:ApplicationConstants.SESSION_MAP.values()){
//如果新账号在其他机器上登录过,则一切的登录失效
if(event.getValue().equals(sess.getAttribute("person"))
&&sess.getId()!=session.getId()){
sess.invalidate();
}
}
}
}
}
ServletRequestListener:
package com.listener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class MyRequestListener implements ServletRequestListener{
//销毁request时调用
public void requestDestroyed(ServletRequestEvent arg0) {
// TODO Auto-generated method stub
}
//创建request时调用
public void requestInitialized(ServletRequestEvent requestEvent) {
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest)requestEvent.getServletRequest();
HttpSession session = request.getSession(true);
session.setAttribute("ip",request.getRemoteAddr());
String uri = request.getRequestURI();
String [] prefix = {".html",".do" ,".jsp",".action"};
for(int i=0;i<prefix.length;i++){
if(uri.endsWith(prefix[i])){//如果是制定的后缀
break;
}
if(i==prefix.length-1){
return;
}
}
Integer activityTimes = (Integer)session.getAttribute("activityTimes");
if(activityTimes==null){
activityTimes=0;
}
session.setAttribute("activityTimes", activityTimes+1);//更新访问次数
}
}
ServletContextListener :
package com.listener;
import java.util.Date;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.vo.ApplicationConstants;
public class MyContextListener implements ServletContextListener {
//服务器启动时调用
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
ApplicationConstants.START_DATE = new Date();//记录启动时间
}
//服务停止时调用
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
//清空结果也可以保存
ApplicationConstants.START_DATE = null;
ApplicationConstants.MAX_ONLINE_COUNT_DATE = null;
}
}