javaspringspring-mvcspring-securitystruts

Doing pre-checks before calling controller in Spring MVC


I recently started working on a Spring MVC project which uses Spring Security.

I had to do some pre-checks before user's request gets to the controller.

This is what I want to achieve, like I have worked a lot with Struts Framework. And in Struts we can extend all the action classes to a superclass let's say BaseAction and then write some validation here so that they gets called before calling the subclass methods.

I would like to achieve same thing here but don't know how to start.

I cannot use filters as I need to make database calls and web-service calls in pre-checks.

I just need some advice.


Solution

  • You can implement an interceptor using HandlerInterceptorAdapter.

    http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-handlermapping-interceptor

    Configuring the applicationContext in XML.

    <mvc:interceptors>
        <bean class="my.package.MyInterceptor" />
    </mvc:interceptors>
    

    The interceptor.

    public class MyInterceptor extends HandlerInterceptorAdapter {
    
        public boolean preHandle(
            HttpServletRequest request, 
            HttpServletResponse response, Object handler) {
    
            // your logic
            return true;
        }
    }
    

    Returns true if the execution chain should proceed with the next interceptor or the handler itself. Else, DispatcherServlet assumes that this interceptor has already dealt with the response itself.