How to write an answer filter?

Is there a way to handle only the response in the filter.

Is the code below written correctly?

public void doFilter(request , response , chain) { //code to handle request chain.doFilter(request, response); //code to handle response . } 
0
source share
4 answers

It depends on what you want. In general, your sample is not correct, though. After returning chain.doFilter , it's too late to do anything with the answer. At the moment, the entire response has already been sent to the client, and your code does not have access to it.

What you need to do is wrap the request and / or response in your own classes, pass these wrappers to the doFilter method, and handle any processing in your wrappers.

To make things easier, there are already wrappers in the api servlet: see HttpServletRequestWrapper and HttpServletResponseWrapper . If you want to process the output that is actually sent to the client, you also need to write your own OutputStream or Writer shells and return them from your HttpServletResponse shell. Yes, lots of wraps :)

Some simpler filters may work without wrapping a request or response: for example. before calling doFilter you can already access the request headers or you can send a custom response without calling doFilter . But if you want to process the request body, you cannot just read it, otherwise it will not be available to the rest of the chain. In this case, you need to use the packaging technique again.

+8
source

The code that you show is not entirely correct, but with the necessary simplification of terminology, it is. You can “process” the request even after chain.doFilter(..) (and the response before it).

What chain.doFilter(..) means is that the process is passed to the desired target, and when the method returns, the target has completed its output.

So, more precisely - this is the "before" and "after" the request is processed and the response is generated.

+2
source

Your code looks fine.

If you want to process the response, you can simply put your code in the //Code to handle response . section //Code to handle response . and do whatever you like.

If you want to do something with the output, you will have to provide a special response wrapper that processes the output stream in the response, where it can record the servlet (and other filters).

0
source

The request and responses are readonly. Therefore, they have no configuration methods to change the contents of this. But with the help of the classes "HttpServletRequestWrapper and HttpServletResponseWrapper" provided by the built-in java, we can change its contents. We encapsulate the original request and response objects with wrapper objects, by changing the wrapper objects we can really change the original request and response objects.

0
source

All Articles