Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get request mapping object in spring interceptor, to get actual url string pattern

It might be hard to explain why, but I have this situation where I need to get the request url mapping string of currently requested url.

Like if I have a GET URL as "/Test/x/{number}" 
I want to get "/Test/x/{number}" not "/Test/x/1"

can I get the actual declared url string in interceptor?

If this is possible how can I achieve this

like image 825
Aadam Avatar asked Jul 15 '18 21:07

Aadam


1 Answers

You can implement a HanderInterceptor to intercept, pre or post, request and introspect the method being called.

public class LoggingMethodInterceptor implements HandlerInterceptor {
    Logger log = LoggerFactory.getLogger(LoggingMethodInterceptor.class);

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

        HandlerMethod method = (HandlerMethod) handler;

        GetMapping mapping = method.getMethodAnnotation(GetMapping.class);

        log.info("URL is {}", Arrays.toString(mapping.value()));

        return true;
    }
}

This will output, URL is [/hello/{placeholder}]

Full example can be found here, https://github.com/Flaw101/spring-method-interceptor

You could add more logic to introspect only certain methods, certain types of requests etc. etc.

like image 134
Darren Forsythe Avatar answered Oct 05 '22 02:10

Darren Forsythe