Droog 关于HttpServletResponseWrapper的一个疑问
问题如下:
1.实现了一个HttpServletResponseWrapper包装器;用于Filter处理容器返回的Response流;
包装器代码如下:
问题:
1.我在实现的包装器中,用CharArrayWriter charWriter处理ServletResponse流;
但是我在构造Wrapper的构造函数以及其他方法中,没有显示的将ServletResponse
传递给CharArrayWriter charWriter,而最终还是可以说的ServletResponse,这是为什么呢?
/**
* 2013-4-4
*
*/
package cn.hrmzone.study;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* @author [email protected]
*
*/
public class ResponseWrapper extends HttpServletResponseWrapper {
private CharArrayWriter charWriter=null;
public ResponseWrapper(HttpServletResponse response) {
super(response);
// TODO Auto-generated constructor stub
charWriter=new CharArrayWriter();
}
@Override
public PrintWriter getWriter() throws IOException {
// TODO Auto-generated method stub
return new PrintWriter(charWriter);
}
public String toString() {
return charWriter.toString();
}
public char[] toCharArray() {
return charWriter.toCharArray();
}
}
在Filter中,可以通过CharArrayWriter charWriter获得Response流对象:
/**
* 2013-4-4
*
*/
package cn.hrmzone.study;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
/**
* @author [email protected]
*
*/
public class ResponseFilter implements Filter {
/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletResponse resp=(HttpServletResponse) arg1;
ResponseWrapper wrapper=new ResponseWrapper(resp);
arg2.doFilter(arg0, wrapper);
String wrapperString=wrapper.toString();
System.out.println("Response has been wrapered by ResponseWrapper:"+wrapperString);
}
/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
星空清理者
10 years, 12 months ago