如何在java中进行会话超时?

时间:2016-11-30 12:54:29

标签: java spring spring-mvc session

这里我想在30 doen之前进行注销调用。我想在DataBase中存储注销时间。如何在java中维护会话。这是我的控制器方法将在注销之前执行。

@RequestMapping(value="/logout")
    public String showLoggedout(HttpServletRequest request,HttpSession session){

        UserInformation userInformation = (UserInformation) session
                .getAttribute("userInfo");

        java.util.Date date = new java.util.Date();
        long t = date.getTime();
        java.sql.Date sqlDate = new java.sql.Date(t);
        java.sql.Time sqlTime = new java.sql.Time(t);
        java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(t);

        String userAgent = (request).getHeader("User-Agent");
        UserAudit userAudit = new UserAudit();
        userAudit.setUserid(userInformation.getUserId());
        userAudit.setLogoutdatetime(sqlTimestamp);
        userAudit.setLoginstatus("Logout");
        BrowserInfo browserInfo = new BrowserInfo();
        String browserInformation = browserInfo.getBrowserInfo(userAgent);
        userAudit.setDeviceInfo(browserInformation);

        appServiceManager.saveUserAudit(userAudit);

        session.invalidate();

        return "loginform";
    }

2 个答案:

答案 0 :(得分:1)

根据评论编辑

根据我的理解,您希望在会话超时时执行一些数据库或其他处理。

您可以定义一个自定义HttpSessionListener实现,它在开始/结束时提供回调挂钩,如下所示:

class MyCustomSessionListener implements HttpSessionListener {

    private static final int SESSION_INACTIVE_TIME = 1*60;

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        event.getSession().setMaxInactiveInterval(SESSION_INACTIVE_TIME);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        //do here your checks/cleanup at the end
    }
}

并将其注册在web.xml中:

//..
<listener>
    <listener-class>my.path.to.MyCustomSessionListener</listener-class>
</listener>
//..

答案 1 :(得分:0)

你可以在你的web.xml中完成(它需要20分钟)

HttpSession session = request.getSession();

session.setMaxInactiveInterval(20*60);

或在特定会话的java代码中(它将输入作为秒)

<web-app ...>
        <listener>
        <listener-class>com.example.sessiontracker </listener-class>
    </listener>
</web-app>

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

public class sessiontracker 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");
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
    totalActiveSessions--;
    System.out.println("sessionDestroyed - deduct one session from counter");
  }
}
  
    

监控会话创建和您必须注册的其他内容     web.xml中的sessionlistner

  
<select>