Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write response filter?

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 .
  }
like image 265
Vinoth Kumar C M Avatar asked Dec 01 '22 03:12

Vinoth Kumar C M


1 Answers

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.

like image 137
Peter Štibraný Avatar answered Dec 07 '22 22:12

Peter Štibraný