在JSP / Java中将用户活动存储在数据库中

时间:2014-06-22 12:18:58

标签: jsp login admin logout

我目前正在开发一个JSP项目。如何存储用户登录信息&注销时间和当前没有。用户在线数据库?另外,我想将其作为管理员而不是用户进行检查?

2 个答案:

答案 0 :(得分:2)

  

如何存储用户登录信息&注销时间和当前没有。用户在线数据库?

这是一个简单的HttpSessionListener示例,用于跟踪Web应用程序中活动会话的总数。如果您想继续监视会话的创建和删除行为,请考虑此侦听器。

示例代码:

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionCounterListener implements HttpSessionListener {

  private static int totalActiveSessions;

  public static int getTotalActiveSession(){
    return totalActiveSessions;
  }

  @Override
  public void sessionCreated(HttpSessionEvent arg0) {
    totalActiveSessions++;
    System.out.println("sessionCreated - add one session into counter");
    // database call to log the log in event of the user with current time
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
    totalActiveSessions--;
    System.out.println("sessionDestroyed - deduct one session from counter");
    // database call to log the log out event of the user with current time
  } 
}

的web.xml

<web-app ...>
    <listener>
        <listener-class>com.x.y.z.SessionCounterListener</listener-class>
    </listener>
</web-app>

它是如何工作的?

  • 如果创建了新会话,例如request.getSession();,则会执行监听器的sessionCreated()
  • 如果会话被销毁,例如会话超时或session.invalidate(),则会执行监听器的sessionDestroyed()

示例代码:

HttpSession session = request.getSession(); //sessionCreated() is executed
...
session.invalidate();  //sessionDestroyed() is executed

有关详细信息,请访问此示例所在的mkyong.com

答案 1 :(得分:0)

您必须创建一个表like log_events(id, event_type, when),并在发生时存储登录和注销事件。

相关问题