1

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

Yans
  • 177
  • 1
  • 1
  • 8

1 Answers1

0

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");
    }
}
geoand
  • 60,071
  • 24
  • 172
  • 190
  • Thnx, but what I'm looking for a way to set property inside the controller (in a method is annotated with @Path) where application logic resides, coz the value I'm about set derives only at that stage. – Yans Feb 05 '22 at 01:33
  • You'll have to set an HTTP header and use a `ContainerResponseFilter` to convert it – geoand Feb 07 '22 at 06:46