7

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

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @Darren
This doesnot works when you have custom header implemented for each endpoint
0

I think that you can get it with reflection and getting @RequestMapping anotations. for example when you use @RequestMapping(value = "/Test/x/{number}", method = RequestMethod.GET)

the value is what you are looking for if I got it right!

You only must find the controller class type. Its possible I think but I didn't test it.

Check this:

In a Spring-mvc interceptor, how can I access to the handler controller method?

First it may be solved if the HandlerMethod was right but if you get cast error then you must get the controller class [I think]. When you get the controller class then you can looking for the method with according @RequestMapping annotation.

So

1- Find the controller class type

2- Search all methods with in the class by reflection

3- Check method annotations with specified url and specified method [GET / POST]

4- select the best candidate

If you have more than two URL parameter this method is not good!

1 Comment

When you intercept the request you can do it at a point where it is already mapped to the target method. All you need to do is walk up the chain and introspect the method it's calling for the annotation path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.