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.
source share