Distinguish multiple requests in Jersey Request Filter

1k views Asked by At

I have a class which implements ContainerRequestFilter and ContainerResponseFilter. I am using this class to log the request and the corresponding response to it.I note the start_time in request filter and propagate this to the response filter using MDC.put("start-time",start_time). I can see that since the response filter takes the ContainerRequestContext as the argument , it is able to map the response to the correct request.

But I am not able to see how the logging filter class is able to distinguish between multiple request calls which would be coming simultaneously. Does each request make a different instance of the logging filter class ?

1

There are 1 answers

2
Paul Samsotha On BEST ANSWER

Does each request make a different instance of the logging filter class ?

No. So trying to store member state is not an option. What you should do is use the ContainerRequestContext to set a property on the request side. On the response side just get the property from the same context.

// request filter
filter(ContainerRequestContext request) {
  request.setProperty("key", value);
}

// response filter
filter(ContainerRequestContext request, ContainerResponseContext response) {
    Object value = request.getProperty("key");
}

Each request will get its own Container(Request|Response)Context.