[英]Spring extract @RequestMapping annotation in HandlerInterceptor of Controller and Method to form full path
I have the following Controller我有以下 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我想从拦截器中提取这个 url
/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:它在上面的路径 string[] 变量中给了我这个:
/users/{userId}
How can I get the full spring request mapping path?如何获取完整的 spring 请求映射路径?
I do not want the servlet path that looks like this: /v4/base/users/23232我不想要看起来像这样的 servlet 路径:/v4/base/users/23232
Found the solution.找到了解决方案。 We can extract the controller annotation like this.
我们可以像这样提取 controller 注释。
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.然后将其作为方法注释的前缀。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.