Home > database >  Spring Boot manually checking whether request object maps to a controller method
Spring Boot manually checking whether request object maps to a controller method

Time:10-02

I have an implementation of HandlerInterceptor where I perform some custom authorization, before request processing. Authorization procedure needs to be adjusted for each endpoint. I do that using HttpServletRequest::getMethod and HttpServletRequest::getRequestURI methods to deduce which endpoint is hit by the request and everything works as intended.

However I don't really like using contains and equals methods on strings to perform manual matching. Is there a more elegant way of doing this? I would prefer to be able to do something like:

boolean isMethodMatched = request.matches("FooController::getFoo");

where the matches method would compare actual request URL and HTTP method of the request object to the ones declared by getFoo method of the FooController. Basically it would be replication of routing, but without invoking method that will be invoked after interceptor does its job. Is there anything resembling this in Spring Boot?

CodePudding user response:

The handler parameter in HandlerInterceptor#preHandle() is actually an instance of HandlerMethod if the request is handled by the annotated controller method . So your best bet is to cast it to the HandlerMethod instance and play around it. For example , it allows you to get the actual Method instance that is used to process the request which is a good starting point to implement your matching logic.

public class FooHandlerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {

        if (handler instanceof HandlerMethod) {
                HandlerMethod hm = (HandlerMethod) handler;
                
               Method controllerMethod = hm.getMethod();

              //Then play around the controllerMethod at here.


       }



    } 

  • Related