Aadam
Aadam

Reputation: 1541

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

Upvotes: 7

Views: 8530

Answers (2)

Darren Forsythe
Darren Forsythe

Reputation: 11411

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.

Upvotes: 8

mehran monster
mehran monster

Reputation: 82

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!

Upvotes: 0

Related Questions