哪位兄弟知道如何保证一个系统中只能让一个用户号同时只能一人在线使用 .
我指的是在BS结构的系统中, 用数据库记录当前在线用户是一个办法,但如果用户突然死机怎么办 本来我想把每个用户的SESSION ID记录在数据库中,如果用户重复登陆,就把他前面的SESSION失效,但不知具体代码如何写
我指的是在BS结构的系统中, 用数据库记录当前在线用户是一个办法,但如果用户突然死机怎么办 本来我想把每个用户的SESSION ID记录在数据库中,如果用户重复登陆,就把他前面的SESSION失效,但不知具体代码如何写
最后MyHttpSessionListener; 2、在web.xml中增加listener的部署声明,如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<listener> <listener-class>org.newsfan.research.session.MyHttpSessionListener</listener-cla
ss>
</listener>
</web-app> 我这里将session的timeout设为1分钟,那是为了显示结果的更加快一点。如果是缺省的20
或者30分钟,那真要等到花儿也谢了。 3、显示结果:
[2004-05-08 11:01:14]Session is created now. the session id
is:55E603CCBADFCF39285E4034F1EBD18C
[2004-05-08 11:01:59]Session is created now. the session id
is:BF63B13A5F326CA73DB52C6A1D518CCD
[2004-05-08 11:02:16]Session is created now. the session id
is:3182A2C4A2428B8BFCC115B8189897D8
[2004-05-08 11:02:18]Session is destroyed now. the session id
is:55E603CCBADFCF39285E4034F1EBD18C
[2004-05-08 11:03:18]Session is destroyed now. the session id
is:3182A2C4A2428B8BFCC115B8189897D8
[2004-05-08 11:03:18]Session is destroyed now. the session id
is:BF63B13A5F326CA73DB52C6A1D518CCD 4、补充说明:session的销毁并不是掐着秒表的,可以说是看web container的。因此在
session失效的时间点上,可能会有一定的误差。但是这种误差是可以接受的。如若要统计
在线人数,只需要在此listener中增加一个LinkedList对象或者Hashtable对象即可。也可
以直接写数据库。 5、所有代码在tomcat 5.0.18上测试通过。 附:MyHttpSessionListener.java的源代码
======================================================================= /*
* The newsfan Software License, Version 1.0
*
* Copyright (c) 2002-2003 The newsfan Software Group. All rights reserved.
*/ package org.newsfan.research.session; import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
import java.text.SimpleDateFormat;
import java.util.Date; /**
* <b>测试session创建、被销毁的动作响应</b>
*
* 为了让本侦听类确实起效,需要在web.xml,即发布xml中的listener中声明本类。
*
* @author Bred Tan
* @version 1.0
* @since 2004-5-8 9:21:28
*/
public class MyHttpSessionListener implements HttpSessionListener
{
/**
* 当session被创建时,web container自动调用此方法。
* @param event
*/
public void sessionCreated(HttpSessionEvent event)
{
System.out.println(getTimeStamp()
+ "Session is created now. the session id is:"
+ event.getSession().getId());
} /**
* 当session被销毁时,web container将会调用此方法。
* @param event
*/
public void sessionDestroyed(HttpSessionEvent event)
{
System.out.println(getTimeStamp()
+ "Session is destroyed now. the session id is:"
+ event.getSession().getId());
} /**
* 方便输出显示
* @return 时间戳,格式为:[年-月-日 小时:分钟:秒]
*/
protected String getTimeStamp()
{
SimpleDateFormat f = new SimpleDateFormat("[yyyy-MM-dd hh:mm:ss]");
return f.format(new Date(System.currentTimeMillis()));
}
} 编译的时候加入j2ee.jar到classpath中去。HttpSessionListener是属于j2ee的,而非
j2se。 是的。WEB-INF\,WEB-INF\classes\,web.xml等具体请参考任意一个servlet教程。