Mfswiggs
Mfswiggs

Reputation: 347

Intecepting Rest Controller responses

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.

Upvotes: 1

Views: 1165

Answers (2)

Milan
Milan

Reputation: 1920

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.

Upvotes: 2

beerbajay
beerbajay

Reputation: 20300

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.

Upvotes: 0

Related Questions