简体   繁体   English

在Spring MVC过滤器或拦截器中处理会话管理的最佳方法

[英]Best way to handle session management in spring mvc filters or interceptors

Requirement: 需求:

Before every action meaning every controller method ie handler I have to check if session is valid or not . 在执行每个动作之前,我必须检查会话是否有效。 If session is valid check for user login details availability in session else those details should be set in session. 如果会话有效,请检查会话中用户登录详细信息的可用性,否则应在会话中设置这些详细信息。 If session is not valid it should be redirected to login page. 如果会话无效,则应将其重定向到登录页面。

Can one let me know which suits my requirement. 可以让我知道哪个适合我的要求。

You can also configure a custom interceptor in your dispatcher servlet, 您还可以在调度程序Servlet中配置自定义interceptor

<mvc:interceptors>
    <bean class="com.CusInterceptor"/>
</mvc:interceptors>

And extend the class HandlerInterceptorAdapter and override the preHandle() method to intercept all requests. 并扩展HandlerInterceptorAdapter类,并重写preHandle()方法以拦截所有请求。

public class CusInterceptorextends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    // verify user session here and process it for further operations  
    }

Use Spring Security for that. 为此使用Spring Security It will store a security context object in the session, holding all the credentials and so on. 它将在会话中存储一个安全上下文对象,其中包含所有凭据等等。 The security filter chain will make sure, that this object sill is valid, or redirect the user to a login page, for example. 安全筛选器链将确保此对象底线有效,或者将用户重定向到登录页面。

Agree with @Stefan on that one. 在那一个上与@Stefan达成一致。 go with Spring Security (we are using the same for session authentication/validations in our mvc app). 与Spring Security一起使用(我们在mvc应用程序中将其用于会话身份验证/验证)。 But please remember that Ajax calls need a little tweaking before you can get them to redirect to login page.. otherwise you just get an error page response which you may or may not be parsing/handling at the JS (client) level 但是请记住,在使Ajax调用重定向到登录页面之前,需要进行一些调整。否则,您将收到错误页面响应,您可能会或可能不会在JS(客户端)级别上进行解析/处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM