user3573403
user3573403

Reputation: 1812

Intercept JAX-RS web service response to add JSON field

I have a JAX-RS web service that returns a Response object as shown below (it is running in WebLogic 12.2.1). It will return a JSON response to the client. Is it possible to write an interceptor or filter, such that when the web service call is returned, it will add an extra field in the JSON response?

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("LogIn")
public Response logIn(@Context HttpServletRequest request, Parameters requestParameters) {...}

Thanks in advance.

Upvotes: 1

Views: 1025

Answers (1)

Kishore Bandi
Kishore Bandi

Reputation: 5711

If using Jersey, then you can try implementing ContainerResponseFilter.

On Over-riding filter(), it provides ContainerResponseContext object which gives you access to the response that is being sent using getEntity() method.

You can modify this object and set it back in the response.

public class ResponseInterceptor implements ContainerResponseFilter{

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        Object obj = responseContext.getEntity();
        // Modify the Response obj as per need
        responseContext.setEntity(obj);
    }
}

Upvotes: 1

Related Questions