GZIP compression for web resources is optional, so you can't compress all of them and then hope that every web client is able to handle it. That's why it's usually enabled at runtime when the client (might be a web browser) says "gzip is OK for me" with the Accept-Encoding: gzip, deflate
header. See https://en.wikipedia.org/wiki/HTTP_compression
On the server side, the magic is handles by a HTTP Filter which intercepts the request, notes the header, then sends the request on to the rest of the app, intercepts the response and compresses accordingly.
JBoss has some built-in support: Enabling gzip compression for Jboss
If you want to do it yourself, you need to write a Filter
and configure it in your web.xml
.
Java2s has an implementation:
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
if (req instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String ae = request.getHeader("accept-encoding");
if (ae != null && ae.indexOf("gzip") != -1) {
GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(response);
chain.doFilter(req, wrappedResponse);
wrappedResponse.finishResponse();
return;
}
chain.doFilter(req, res);
}
}
or you can use a performance optimization library like WebUtilities to enable compression as described here https://github.com/rpatil26/webutilities/wiki/Enable-Compression
See also: