简体   繁体   中英

How to preprocess all requests in Spring Web application?

I have a RESTful Spring application, which can process various request with various controllers and various @RequestMapping -s.

Now I wish each request contain additionally a user/password pair, user as user GET parameter ?user=username and password in password POST parameter.

Is it possible to "preprocess" all requests before they go to controllers and check credentials and possible return authentication error?

Is this a mechanism, which is caller "filters" or not?

There are couple of ways for intercepting the requests before they land into controllers.

  1. Using Servlet Filters:
    @WebFilter(urlPatterns = "path-to-intercept", filterName = "your-filter-name")
    public class MyRequestFilter implements Filter {
        init(...);
        doFilter(...);
        destroy(); 
    }
  1. Using Spring HandlerIntecptors:
    public class MyRequestInterceptor extends HandlerInterceptorAdapter{

        preHandle(...); //called before the request lands to the controller.
        postHandle(...); //called after the controller method finishes execution.
        afterCompletion(...); //called before the response is sent.
    }

And in your configuration:

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/yourInterceptingPath/" />
            <bean class="path-to-your-Interceptor.MyRequestInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors> 

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