0

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

5
  • id is a path variable so if you request /1 in url would be /1 and 1 ->id . change "/{id}" to "/{id}*" for accepting /1, /1/ Commented Jan 8, 2019 at 9:55
  • inside the interceptor i want to retriev /{id}/ as String i dont care about the id itself (1) Commented Jan 8, 2019 at 10:04
  • Inside preHandle use request.getRequestURL().toString() or equest.getQueryString() to retriev /{id}/ as string Commented Jan 8, 2019 at 10:16
  • getRequestURL returns the full link localhost:8080/1, querystring is null but i want /{id} Commented Jan 8, 2019 at 10:56
  • you can't achieve this because /{id} you have define in controller for path variable. Interceptor intercept what ever you pass in url like you pass /1 so how it will map with {id}. Commented Jan 8, 2019 at 11:45

1 Answer 1

1

@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);
            }
        } 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.