Is there a way to handle only response in a filter .
Is the code written below correct ?
public void doFilter(request , response , chain) {
//code to handle request
chain.doFilter(request, response);
//code to handle response .
}
It depends on what you want. In general, your sample is not correct though. After chain.doFilter
has returned, it's too late to do anything with the response. At this point, entire response was already sent to the client and your code has no access to it.
What you need to do is to wrap request
and/or response
into your own classes, pass these wrappers into doFilter
method and handle any processing in your wrappers.
To make it easier, there are already wrappers available in servlet api: see HttpServletRequestWrapper
and HttpServletResponseWrapper
classes. If you want to process output that is actually sent to client, you also need to write custom OutputStream or Writer wrappers, and return those from your HttpServletResponse wrapper. Yeah, lot of wrapping :)
Some simpler filters can work without wrapping request or response: e.g. before calling doFilter
, you can already access request headers or you can send custom response without calling doFilter
. But if you want to process request body, you cannot just read it, otherwise it won't be available to the rest of the chain. In this case you need to use the wrapping technique again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With