How to enable session and set session timeout in Spring Security

后端 未结 5 2195
轮回少年
轮回少年 2020-12-14 00:53

I am new to Spring Security and I am working on a login, logout, and session timeout feature. I have configured my code by referring to this document. My code looks below:

5条回答
  •  旧巷少年郎
    2020-12-14 01:43

    If you are using JavaConfig and do not want to use XML you can create a HttpSessionListener and use getSession().setMaxInactiveInterval(), then in the Initializer add the listener in onStartup():

    public class SessionListener implements HttpSessionListener {
    
        @Override
        public void sessionCreated(HttpSessionEvent event) {
            System.out.println("session created");
            event.getSession().setMaxInactiveInterval(15);
        }
    
        @Override
        public void sessionDestroyed(HttpSessionEvent event) {
           System.out.println("session destroyed");
        }
    }
    

    Then in the Initializer:

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.addListener(new SessionListener());
    }
    

提交回复
热议问题