在Spring MVC中设置会话超时

JPr*_*mer 18 java session spring spring-mvc

有没有办法在Spring中指定会话超时?我无法在web.xml中指定它.因为我在控制器中使用会话范围bean如下所示

我已经通过spring xml文件配置了控制器.

class xyzController{

     ABCSessionScopeClass objectWhichWillBeStoredInSession;
}
Run Code Online (Sandbox Code Playgroud)

我也不能用它

session.setMaxInactiveInterval(60*60);
Run Code Online (Sandbox Code Playgroud)

有没有其他方法可以做到这一点.我不介意在每个会话或同时为所有会话设置超时.

Jig*_*ekh 24

解决方案使用Pure Spring MVC,sevlet context.xml

<mvc:interceptors>
    <bean class="com.xxx.SessionHandler" />
</mvc:interceptors>
Run Code Online (Sandbox Code Playgroud)

处理程序适配器

@Component
public class SessionHandler extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.getSession().setMaxInactiveInterval(60*60);
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

假设您使用弹簧安全,

对于每次成功登录,我认为最好的方法是LoginSuccessHandler为正常登录创建和指定authentication-success-handler以及remember-me.

@Service
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication) throws ServletException, IOException {
        request.getSession().setMaxInactiveInterval(60*60);
        super.onAuthenticationSuccess(request, response, authentication);
    }

}
Run Code Online (Sandbox Code Playgroud)

 

<http auto-config="true" use-expressions="true">
    <form-login login-page="/login"
        authentication-failure-url="/login.hst?error=true"
        **authentication-success-handler-ref="loginSucessHandler"** />
    <logout invalidate-session="true" logout-success-url="/home" logout-url="/logout" />
    <remember-me key="jbcp" **authentication-success-handler-ref="loginSucessHandler"**/>
    <session-management>
        <concurrency-control max-sessions="1" />
    </session-management>
</http>
Run Code Online (Sandbox Code Playgroud)


JPr*_*mer -1

我无法找到任何方法通过任何 Spring 配置文件指定会话超时值。我使用的是<aop:scoped-proxy>bean,这样我就不必管理会话的读/写值/对象。现在,我也希望在不使用 servlet API 的情况下设置会话超时值。但看起来除了 web.xml 文件之外没有其他方法可以指定它。所以最终使用servlet apirequest.getSession()来设置超时时间。我将时间值外部化,这样我就可以轻松更改它,而无需重新编译代码。如果有人发现更好的方法,请随时发帖。如果找到更好的答案,我可以接受。