Barney Stinson
Barney Stinson

Reputation: 1002

Java Servlet retrieve Spring RequestMapping Url

I wrote a Request Interceptor to add some Information to Requests in Test-Environment.

public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response, Object handler)
        throws Exception {
    ...
}

public void postHandle(
        HttpServletRequest request, HttpServletResponse response,
        Object handler, ModelAndView modelAndView)
        throws Exception {
        ...
}

Currently I'm retrieving the URLs like this:

String url = request.getServletPath();

For a Controller like this:

@RequestMapping(value = "/{id}",
        method = RequestMethod.GET)
public ResponseEntity<?> getByID(@PathVariable long ID) {
    ...
}

And for a Request like /1/ url would be /1/

Is there any way to get the Request-Mapping-Value ==> /{id}

Thanks in advance

Upvotes: 0

Views: 144

Answers (1)

Ken Chan
Ken Chan

Reputation: 90497

@RequestMapping and its composed annotation methods (i.e. @GetMapping , @PostMapping etc.) are handled by HandlerMethod. So cast the handler object to it and you can access the @RequestMapping information that you want:

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

    if (handler instanceof HandlerMethod) {
        HandlerMethod hm = (HandlerMethod) handler;
        RequestMapping mapping = hm.getMethodAnnotation(RequestMapping.class);
        if (mapping != null) {
            for(String val : mapping.value()) {

                //***This is the mapping value of @RequestMapping***
                System.out.println(val);
            }
        } 
    }
}

Upvotes: 1

Related Questions