'Setting properties to the request context

How to set a property to the current request context? I'm trying to persist an audit trail (that contains request specific information) for all requests/response.

I was trying to do it in an implementation of ContainerResponseFilter (to avoid handling it in all the req methods) as below:

public void filter(ContainerRequestContext reqCtx, ContainerResponseContext respCtx){
        ReqInfo info = (ReqInfo)reqCtx.getProperty("info_key");
        //..persist.
}

and setting this info in the Controller as shown below;

@Context
ContainerRequestContext reqCtx;

@POST
@Path("/some/path")
public Response foo(){
        ...
        ReqInfo info = new ReqInfo();
        reqCtx.setProperty("info_key", info);
        ...
}

But this doesn't seems to work, as I'm getting Unable to find contextual data of type: ...ContainerRequestContext error.

Is there anyway to set some properties to the request so that in can be accessed in the interceptor/Filter later?

Thanks



Solution 1:[1]

You can do something like this to set the property for each request:

@Provider
public class DummyContainerRequestFilter implements ContainerRequestFilter {


    @Override
    public void filter(ContainerRequestContext requestContext) {
        requestContext.setProperty("foo", "bar");
    }
}

And then access the property after the resource method has completed by calling:

@Provider
public class DummyContainerResponseFilter implements ContainerResponseFilter {


    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        requestContext.getProperty("foo");
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 geoand