0

I want to build a library that will save the Json content of request and response on annotated Spring controller.

So i've build my own annotation @Foo and put it on some controllers:

    @Foo
    @RequestMapping(method = RequestMethod.POST, value = "/doSomeThing", produces = {
            MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_XML_VALUE,
            MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<T> doSomething(/*some parameters*/) {
        T t = doSomeJob(T.class);
        return new ResponseEntity<T>(t, HttpStatus.OK);
}

I have no guarantee that request and response are in Contrellor's parameters! And i'm catching the call on any Controller having that annotation within an @AfterReturning AOP pointcut.

@Component
@Aspect
public class XYInterceptor
@AfterReturning(
            pointcut = "execution(@my.annotation.Foo)")
            public void doSomethingWithJsonContent(JoinPoint joinPoint) throws Throwable {

            //How can i get json value of request and response here?    
}   

How can I get request and response content formatted in json (such as it is send/returned to the client) ?

Thanx for your help!

Lucas.de
  • 555
  • 8
  • 17

1 Answers1

0

Well, you need request and response somehow accessible from your controller method, either via an injected class member, method parameter or method return value. It has got to be somewhere. Because you did not explain where you intend to get it from, I can just post a general answer showing how to determine method arguments and return value from an @AfterReturning advice. If you update the question with more detailed information, I can also update the answer accordingly.

My pointcut (the commented-out one also works, choose your favourite one) binds the return value to a parameter and just assumes that both request and response are of String type. Feel free to replace by your favourite. Furthermore, you can bind a parameter from your intercepted method (no matter where it is in the signature) to a typed advice method parameter if you know that the parameter exists and also know its (super) type. This way you can get rid of the slow and ugly loop over getArgs().

//@AfterReturning(pointcut = "execution(@my.annotation.Foo * *(..))", returning = "response")
@AfterReturning(pointcut = "@annotation(my.annotation.Foo)", returning = "response")
public void interceptRequest(String response, JoinPoint thisJoinPoint) {
    System.out.println(thisJoinPoint);
    for (Object arg : thisJoinPoint.getArgs()) {
        if (arg instanceof String)
            System.out.println("  request = " + arg);
    }
    System.out.println("  response = " + response);
}
kriegaex
  • 63,017
  • 15
  • 111
  • 202