Home > database >  Spring extract @RequestMapping annotation in HandlerInterceptor of Controller and Method to form ful
Spring extract @RequestMapping annotation in HandlerInterceptor of Controller and Method to form ful

Time:01-24

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

CodePudding user response:

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.

  • Related