`
dpsnet
  • 浏览: 7697 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

动态代理实现filter

    博客分类:
  • java
阅读更多

想什么来什么,终于g到动态代理实现filter的代码

 

package cn.itcast.web.filter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GzipFilter2 implements Filter {

public void destroy() {
   // TODO Auto-generated method stub

}

public void doFilter(ServletRequest req, ServletResponse resp,
    FilterChain chain) throws IOException, ServletException {

   HttpServletRequest request = (HttpServletRequest) req;
   HttpServletResponse response = (HttpServletResponse) resp;
  
   //利用代理类,生成代理对象
   ResponseProxy proxy = new ResponseProxy(response);
   chain.doFilter(request, proxy.getResponse());

   byte source[] = proxy.getBuffer();
   System.out.println(new String(source));
}

public void init(FilterConfig filterConfig) throws ServletException {
   // TODO Auto-generated method stub

}
}

// 写一个类来创建response代理对象
class ResponseProxy {
//1.创建被代理对象.
HttpServletResponse response;

ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintWriter writer = null;

//构造方法中传入被代理的对象.
public ResponseProxy(HttpServletResponse response) {
   this.response = response;
}

//获取被代理对象的方法
public HttpServletResponse getResponse() {//利用Proxy.newProxyInstance来创建被代理的对象
   return (HttpServletResponse) Proxy.newProxyInstance(ResponseProxy.class
     .getClassLoader(), response.getClass().getInterfaces(),
     new InvocationHandler() {
      //内部类实现InvocationHandler的方法,
      public Object invoke(Object proxy, Method method,
        Object[] args) throws Throwable {

       if (method.getName().equals("getWriter")) {
        writer = new PrintWriter(new OutputStreamWriter(
          out, response.getCharacterEncoding()));
        return writer;
       }
       if (method.getName().equals("getOutputStream")) {
        return new YouServletOutputStream(out);
       }
       return method.invoke(response, args);
      }

     });
}

public byte[] getBuffer() {
   if (writer != null) {
    writer.flush();
   }
   return out.toByteArray();
}
}

class YouServletOutputStream extends ServletOutputStream {
ByteArrayOutputStream out;

public YouServletOutputStream(ByteArrayOutputStream out) {
   this.out = out;
}

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics