<filter>
<filter-name>ZGIPFilter</filter-name>
<filter-class>com.ztesoft.zsmart.web.filter.ZGIPFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ZGIPFilter</filter-name>
<url-pattern>*.js</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>ZGIPFilter</filter-name>
<url-pattern>*.css</url-pattern>
</filter-mapping>
public class ZGIPFilter extends HttpServlet implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
// 判断是否包含了 Accept-Encoding 请求头部
HttpServletRequest s = (HttpServletRequest) request;
String header = s.getHeader("Accept-Encoding");
if (header != null && header.toLowerCase().contains("gzip")) {
HttpServletResponse resp = (HttpServletResponse) response;
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
HttpServletResponseWrapper hsrw = new HttpServletResponseWrapper(resp) {
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(new OutputStreamWriter(buffer, getCharacterEncoding()));
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
buffer.write(b);
}
};
}
};
chain.doFilter(request, hsrw);
byte[] gzipData = gzip(buffer.toByteArray());
resp.addHeader("Content-Encoding", "gzip");
resp.setContentLength(gzipData.length);
ServletOutputStream output = response.getOutputStream();
output.write(gzipData);
output.flush();
}
else {
chain.doFilter(request, response);
}
}
// 用 GZIP 压缩字节数组
private byte[] gzip(byte[] data) {
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(10240);
GZIPOutputStream output = null;
try {
output = new GZIPOutputStream(byteOutput);
output.write(data);
}
catch (IOException e) {
}
finally {
try {
output.close();
}
catch (IOException e) {
}
}
return byteOutput.toByteArray();
}
}
GZIP前

GZIP后
结论:如果服务器端未采用gzip格式压缩,可以通过这样的配置实现。由上图看出来,文件压缩之后大小由原来的94890变成33673,将近减小了三分之二,还是可观的。这里只配置了JS和CSS的压缩,HTML静态页面应可以使用,图片使用GZIP压缩会有点问题(以png为例,大小由原来的480605变成了480736,反而变大了)。