GZIP压缩代码
public class GzipFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException("non-HTTP request or response");
}
MyHttpServletResponse mresponse = new MyHttpServletResponse(response);
chain.doFilter(request, mresponse);
byte b[] = mresponse.getBytes();//原始数据:关键
System.out.println("原始大小:"+b.length);
//判断客户端支持gzip吗
if(request.getHeader("Accept-Encoding").contains("gzip")){
//压缩输出
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gout = new GZIPOutputStream(out);
gout.write(b);
gout.close();
b = out.toByteArray();//压缩后的数据
System.out.println("压缩后大小:"+b.length);
//告知客户端压缩方式
response.setHeader("Content-Encoding", "gzip");
response.setContentLength(b.length);
}
ServletOutputStream sos = response.getOutputStream();
sos.write(b);
}
public void destroy() {
}
}
class MyHttpServletResponse extends HttpServletResponseWrapper{
private ByteArrayOutputStream baos = new ByteArrayOutputStream();//临时仓库:存放原始数据的
private PrintWriter pw;
public MyHttpServletResponse(HttpServletResponse response) {
super(response);
}
//字节流
public ServletOutputStream getOutputStream() throws IOException {
return new MyServletOutputStream(baos);
}
//字符流
public PrintWriter getWriter() throws IOException {
pw = new PrintWriter(new OutputStreamWriter(baos, super.getCharacterEncoding()));
return pw;
}
public byte[] getBytes(){
try {
if(pw!=null){
pw.close();
}
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
return baos.toByteArray();
}
}
class MyServletOutputStream extends ServletOutputStream{
private ByteArrayOutputStream baos;
public MyServletOutputStream(ByteArrayOutputStream baos){
this.baos = baos;
}
public void write(int b) throws IOException {
baos.write(b);
}
}
我刚学到过滤器,这GZIP压缩的代码我看着好晕,我知道有装饰设计模式,但是里面的好多流晕着我了,怎么办啊?另外,在class MyServletOutputStream中既然继承了ServletOutputStream这个抽象类,但是没有将之实现全部的方法,IDEA报错,但是我看视频里可以运行啊。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
流学习记住几个规则
out开头的必是写
input开头的必是读
xxxstream一般是字节流
xxxreader xxxwriter是字符流读写
字节流字符流转化工具命名一般是xxxstreamreader