Spring mvc 如何在SpringJava配置中全局设置会话超时

Spring mvc 如何在SpringJava配置中全局设置会话超时,spring-mvc,Spring Mvc,嗨,我正在尝试为我的整个spring mvc应用程序全局设置会话超时。之前我们在web.xml中配置了会话超时,如下所示 <web-app ...> <session-config> <session-timeout>20</session-timeout> </session-config> </web-app> 20 如何在SpringJava配置中做到这一点 您可以实现一个Http

嗨,我正在尝试为我的整个spring mvc应用程序全局设置会话超时。之前我们在web.xml中配置了会话超时,如下所示

<web-app ...>
    <session-config>
        <session-timeout>20</session-timeout>
    </session-config>
</web-app>

20

如何在SpringJava配置中做到这一点

您可以实现一个
HttpSessionListener
监听器:

public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        System.out.println("Session creation.");
        event.getSession().setMaxInactiveInterval(1000);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.println("Session termination.");
    }
}

方法setMaxInactiveInterval需要几秒钟的输入时间。

您也可以从属性文件加载该值

@Override
        public void sessionCreated(HttpSessionEvent event) {
            try {
                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                InputStream stream = classLoader.getResourceAsStream("bimspring.properties");
                Properties properties = new Properties();
                properties.load(stream);
                String sessionTimeout = properties.getProperty("sessionTimeout ", "No Value Found");
                event.getSession().setMaxInactiveInterval(Integer.parseInt(sessionTimeout));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

这也是我同样做的,看看我的答案和从属性文件加载会话超时是否有更好的方法加载属性文件值是的,如果您在spring上下文中(即:类是Springbean)您可以使用
@value
注释注入值。如何在httplisetener类中使用@value,例如:
@value(${bimspring.properties.sessionTimeout}”)私有整数超时