@WebFilter(urlPatterns = {"/sqlAnalysis/sqlModel/getAll"}, filterName = "authFilter")
public class GzipFilter implements Filter{
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
MyResponse mResp = new MyResponse(resp); // 包装响应对象 resp 并缓存响应数据;
chain.doFilter(req, mResp);
byte[] bytes = mResp.getBytes(); // 获取缓存的响应数据
ByteArrayOutputStream bout = new ByteArrayOutputStream();
GZIPOutputStream gzipOut = new GZIPOutputStream(bout); // 创建 GZIPOutputStream 对象
gzipOut.write(bytes); // 将响应的数据写到 Gzip 压缩流中
gzipOut.close(); // 将数据刷新到 bout 字节流数组
byte[] bts = bout.toByteArray();
resp.setHeader("Content-Encoding", "gzip"); // 设置响应头信息
resp.getOutputStream().write(bts); // 将压缩数据响应给客户端
}
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("+++启动压缩。");
}
}
然后启动类上添加@ServletComponentScan