I trying some things with the HTTP server of Sun JRE. After reading twice the documentation, I am still confused.
The com.sun.net.httpserver.Filter javadoc says the following
Asks this filter to pre/post-process the given exchange. The filter can :
- examine or modify the request headers
- filter the request body or the response body, by creating suitable filter streams and calling HttpExchange.setStreams(InputStream,OutputStream)
- set attribute Objects in the exchange, which other filters or the exchange handler can access.
decide to either :
- invoke the next filter in the chain, by calling Filter.Chain.doFilter(HttpExchange)
- terminate the chain of invocation, by not calling Filter.Chain.doFilter(HttpExchange)
if option 1. above taken, then when doFilter() returns all subsequent filters in the Chain have been called, and the response headers can be examined or modified. if option 2. above taken, then this Filter must use the HttpExchange to send back an appropriate response
What does not clear for me, what decides when the filter is pre- or post-process filter. As I assume, post-process filter is runs after the HttpHandler, so it can work with HttpExchange what is modified by HttpHandler. However, filter is called only once, so there must be a "magic" what decides the filter runs before or after the handler.
Please help me to make it clear.
I've wondered about this myself and I don't see how the setStreams
method can be helpful for this. The only way I could do this is by wrapping HttpExchange.
This example shows how to apply gzip compression with a Filter:
https://gist.github.com/Crydust/7e4e9228cd95febccdc58f0501c1e327