Get HTTP Method from a joinPoint
Asked Answered
O

1

0

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?

Osy answered 14/1, 2020 at 22:56 Comment(0)
A
2

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

Annals answered 15/1, 2020 at 1:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.