Get HTTP Method from a joinPoint

廉价感情. 提交于 2021-02-05 09:24:49

问题


I need to get the http method like POST/PATCH/GET/etc from a joinPoint in an aspect.

@Before("isRestController()")
    public void handlePost(JoinPoint point) {
        // do something to get for example "POST" to use below 
        handle(arg, "POST", someMethod::getBeforeActions);
    }

From point.getThis.getClass(), I get the the controller that this call is intercepted. Then if I get the method from it and then annotations. That should be good enough right?

So point.getThis().getClass().getMethod(point.getSignature().getName(), ???) How do i get Class paramaterTypes?


回答1:


Following code gets the required controller method annotation details

    @Before("isRestController()")
public void handlePost(JoinPoint point) {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();

    // controller method annotations of type @RequestMapping
    RequestMapping[] reqMappingAnnotations = method
            .getAnnotationsByType(org.springframework.web.bind.annotation.RequestMapping.class);
    for (RequestMapping annotation : reqMappingAnnotations) {
        System.out.println(annotation.toString());
        for (RequestMethod reqMethod : annotation.method()) {
            System.out.println(reqMethod.name());
        }
    }

    // for specific handler methods ( @GetMapping , @PostMapping)
    Annotation[] annos = method.getDeclaredAnnotations();
    for (Annotation anno : annos) {
        if (anno.annotationType()
                .isAnnotationPresent(org.springframework.web.bind.annotation.RequestMapping.class)) {
            reqMappingAnnotations = anno.annotationType()
                    .getAnnotationsByType(org.springframework.web.bind.annotation.RequestMapping.class);
            for (RequestMapping annotation : reqMappingAnnotations) {
                System.out.println(annotation.toString());
                for (RequestMethod reqMethod : annotation.method()) {
                    System.out.println(reqMethod.name());
                }
            }
        }
    }
}

Note : This code can be further optimized. Shared as an example to demonstrate the possibilities



来源:https://stackoverflow.com/questions/59742937/get-http-method-from-a-joinpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!