简体   繁体   中英

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,

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

And extend the class HandlerInterceptorAdapter and override the preHandle() method to intercept all requests.

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. 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. go with Spring Security (we are using the same for session authentication/validations in our mvc app). 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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