1

I am building a REST service using spring boot. My controller is annotated with @RestController. For debugging purposes I want to intercept the ResponseEntity generated by each of the controller methods (if possible). Then I wish to construct a new ResponseEntity that is somewhat based on the one generated by the controller. Finally the new generated ResponseEntity will replace the one generated by the controller and be returned as part of the response.

I only want to be able to do this when debugging the application. Otherwise I want the standard response generated by the controller returned to the client.

For example I have the controller

@RestController
class SimpleController

    @RequestMapping(method=RequestMethod.GET, value="/getname")
    public NameObject categories()
    {
        return new NameObject("John Smith");
    }
}

class NameObject{
    private String name;
    public NameObject(name){
        this.name = name;
    }
    public String getName(){ return name; }
}

This will generate the response:

{"name" : "John Smith"}

But I would like to change the response to include status info of the actual response e.g:

{"result": {"name" : "John Smith"}, "status" : 200 }

Any pointers appreciated.

Mfswiggs
  • 307
  • 1
  • 6
  • 16
  • Your best bet will probably be creating a custom `HttpMessageConverter` to intercept your response and wrap it in another object with the status code. For example: http://stackoverflow.com/questions/21349030/how-to-create-a-custom-http-message-converter-spring-mvc-3-1-2 – woemler Jul 09 '15 at 13:21

2 Answers2

2

The way I would try to achieve such a functionality is first by creating an Interceptor. And example can be found here

Second, I would employ Spring profiles to ensure that interceptor is loaded only in profile that I needed it in. Detail here. It's not exaclty debugging, but might do the trick.

Milan
  • 1,780
  • 1
  • 16
  • 29
0

You can do this with spring AOP, something like:

@Aspect
@Component
public class ResponseEntityTamperer {
    @Around("execution(* my.package.controller..*.*(..))")
    public Object tamperWithResponseEntity(ProceedingJoinPoint joinPoint)
                  throws Throwable {
        Object retVal = joinPoint.proceed();
        boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean()
                             .getInputArguments().toString()
                             .contains("jdwp");

        if(isDebug && retVal instanceof ReponseEntity) {
            // tamper with the entity or create a new one
        }
        return retVal;
    }
}

The "find out if we're in debug mode" code is from this answer.

Community
  • 1
  • 1
beerbajay
  • 19,652
  • 6
  • 58
  • 75