[英]Spring extract @RequestMapping annotation in HandlerInterceptor of Controller and Method to form full path
我有以下 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) {
...
}
}
我想從攔截器中提取這個 url
/v4/base/users/{userId}
通過這種方法,
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();
}
}
}
它在上面的路徑 string[] 變量中給了我這個:
/users/{userId}
如何獲取完整的 spring 請求映射路徑?
我不想要看起來像這樣的 servlet 路徑:/v4/base/users/23232
找到了解決方案。 我們可以像這樣提取 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];
}
}
然后將其作為方法注釋的前綴。
這樣的事情將按照您的代碼工作。
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.