如何管理会话超时已过期

时间:2016-11-17 16:30:09

标签: java spring spring-security

我有以下麻烦。我的spring应用程序按以下方式配置:

应用程序上下文安全性

<http use-expressions="true" pattern="/ext/**" entry-point-ref="loginUrlAuthenticationEntryPoint">

    //Others configuration

    <session-management invalid-session-url="/sessionExpired">
    </session-management>
</http>

我的控制器:

@RequestMapping(value="/sessionExpired", method = RequestMethod.GET)
public String sessionExpired(ModelMap model, HttpSession session) {
    return "login";
}

现在我的问题是在sessionExpired方法中,我应该能够区分我的用户的某些属性,例如:

  @RequestMapping(value="/sessionExpired", method = RequestMethod.GET)
public String sessionExpired(ModelMap model, HttpSession session) {

     //Test1
     Authentication auth = SecurityContextHolder.getContext().getAuthentication();
     MyUser u = (MyUser) authentication.getPrincipal();

     //Test2 
     MyUser u = session.getAttribute("user");

     if(u.isItalian())
        return "loginA"
    else 
        return "loginB"

    return "login";
}

我认为sping安全性已经清理了session,request和SecurityContextHolder。那我怎么解决这种情况呢?

1 个答案:

答案 0 :(得分:-2)

SessionExpired表示没有会话,因为它已过期。 一个选项是在事件被销毁之前捕获一个事件的Session。 幸运的是,我找到了这个解决方案/方法:

http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpSessionListener.html

看起来像这样:

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

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