2014-10-29 40 views
0

我目前從數據庫中檢索會話超時,因爲它應該是可配置的,所以我不能在web.xml中聲明它。Spring - 控制會話創建的最佳方法

在我的HttpSessionEventPublisher中,我基本上從HttpSessionEvent中檢索會話對象,並使用setMaxInactiveInterval設置了從數據庫中檢索到的會話超時值。

經過調查,無論何時訪問我網站中的POST URL,都會觸發HttpSessionEventPublisher並創建新的Session對象。我想通過只創建一個會話對象來控制這種行爲,當且僅當用戶被成功驗證(登錄,通過AuthenticationProvider)

這可能嗎?

回答

1

HttpSessionEventPublisher本身不會創建會話。它只是將servlet會話事件轉換爲spring安全性的等價事件。實際上,會話的創建不受春季安全控制,但如果需要,它可以啓動一次。

如果您只是想在認證時設置會話超時,那麼您可以擴展您使用的認證處理程序並在那裏設置超時。

例如,下面的代碼擴展SavedRequestAwareAuthenticationSuccessHandler和檢索來自應用程序屬性超時(而不是數據庫作爲你的情況)


@Component 
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { 

    @Value("#{appProperties['session.timeout']}") 
    private int sessionTimeout; 

    private final Logger logger = LoggerFactory.getLogger(AuthenticationSuccessHandler.class); 

    @Override 
    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication authentication) throws ServletException, IOException { 

     logger.debug("onAuthenticationSuccess"); 

     HttpSession session = req.getSession(); 
     session.setMaxInactiveInterval(sessionTimeout); 

     super.onAuthenticationSuccess(req, res, authentication); 
    } 
} 
+0

是啊是啊!這就是我最終做的。 :d – mpmp 2014-10-30 07:52:32

相關問題