Servlet3 gzip 支持

内容简略点,关于gzip的网上资料也有很多,主要给出Servlet3.0核心部分;

第一,Filter

public class GZipFilter implements Filter {

	public void destroy() {
	}

	/**
	 * 判断浏览器是否支持GZIP
	 * 
	 * @param request
	 * @return
	 */
	private boolean acceptsGZipEncoding(HttpServletRequest httpRequest) {
		String acceptEncoding = httpRequest.getHeader("Accept-Encoding");
		return acceptEncoding != null && acceptEncoding.indexOf("gzip") != -1;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		if (acceptsGZipEncoding(httpRequest)) {
			httpResponse.addHeader("Content-Encoding", "gzip");
			GZipServletResponseWrapper gzipResponse = new GZipServletResponseWrapper(
					httpResponse);
			chain.doFilter(request, gzipResponse);
			gzipResponse.close();
		} else {
			chain.doFilter(request, response);
		}

	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}

}


第二:GZipServletOutputStream和2.0的无需改动,略过。

第三,GZipServletOutputStream, isReadyset和setWriteListener是servlet3接口的新方法

class GZipServletOutputStream extends ServletOutputStream {
	private GZIPOutputStream gzipOutputStream = null;
	private ServletOutputStream servletOutputStream = null;

	public GZipServletOutputStream(ServletOutputStream output)
			throws IOException {
		super();
		this.servletOutputStream = output;
		this.gzipOutputStream = new GZIPOutputStream(this.servletOutputStream);
	}

	@Override
	public void close() throws IOException {
		this.gzipOutputStream.close();
	}

	@Override
	public void flush() throws IOException {
		this.gzipOutputStream.flush();
	}

	@Override
	public void write(byte b[]) throws IOException {
		this.gzipOutputStream.write(b);
	}

	@Override
	public void write(byte b[], int off, int len) throws IOException {
		this.gzipOutputStream.write(b, off, len);
	}

	@Override
	public void write(int b) throws IOException {
		this.gzipOutputStream.write(b);
	}

	@Override
	public boolean isReady() {

		return servletOutputStream.isReady();
	}

	@Override
	public void setWriteListener(WriteListener writeListener) {
		servletOutputStream.setWriteListener(writeListener);
	}
}





你可能感兴趣的:(Servlet3 gzip 支持)