1

I have the following Controller

@RestController
@RequestMapping("/v4/base")
public class ExampleController {
   
    @PostMapping(value = "/users/{userId}")
    public ResponseEntity<List<ExampleRequest>> test(@RequestHeader HttpHeaders headers,
            @PathVariable String orgId, @RequestBody List<ExampleRequest> request) {
        ...
    }
}

I would like to extract this url from an interceptor

/v4/base/users/{userId}

With this approach,

public class MyInterceptor  implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws IOException, ServletException {

            RequestMapping requestMapping = method.getMethodAnnotation(RequestMapping.class);
            
            if (requestMapping != null) {
                String[] path = requestMapping.path();  
            }

    }

}

It gives me this in the path string[] variable above:

/users/{userId}

How can I get the full spring request mapping path?

I do not want the servlet path that looks like this: /v4/base/users/23232

Sumama Waheed
  • 3,579
  • 3
  • 18
  • 32

2 Answers2

0

Found the solution. We can extract the controller annotation like this.

Class controller = method.getBeanType();

if (controller.isAnnotationPresent(RequestMapping.class)) {
    RequestMapping controllerMapping = (RequestMapping) controller.getAnnotation(RequestMapping.class);
    if (controllerMapping.value() != null && controllerMapping.value().length > 0) {
        controllerPath = controllerMapping.value()[0];
    }
}

And then prefix that to the method annotation.

Update: The only problem with this approach is that it's not able to extract the resolved annotation value like this one:


@RequestMapping(value = "${app.version.v4}")
Sumama Waheed
  • 3,579
  • 3
  • 18
  • 32
0

Something like this will work as per your code.

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequestMapping methodAnnotation = handlerMethod.getMethodAnnotation(RequestMapping.class);
        RequestMapping classAnnotation = handlerMethod.getBeanType().getAnnotation(RequestMapping.class);
        if (methodAnnotation != null && classAnnotation != null) {
            String[] classValues = classAnnotation.value();
            String[] methodValues = methodAnnotation.value();
            String fullPath = classValues[0] + methodValues[0];
            // do something here`enter code here`
        }
    }
    return true;
}
Vipul Gupta
  • 391
  • 2
  • 11