在网上找了一些实现取得response返回流进行修改的例子,也试验成功了,但是有个地方还有些疑惑,重写了HttpServletResponseWrapper(WrapperResponse)中的PrintWriter(现在叫WrapperWriter)后,然后在自己的WrapperResponse想获取重写后的WrapperWriter返回的ServletOutputStream时用的是ByteArrayOutputStream bout;来接收返回的outputstream可是我在myWriter.flush()(实例化后的WrapperWriter myWriter,且有myWriter=new WrapperWriter(bout))无法在WrapperResponse中通过bout直接获得返回流,而必须通过在WrapperWriter中重写getOutputStream()来获取返回流,疑惑也就出现在这,明明已经通过myWriter.flush();来将返回流刷到bout了(我认为myWriter=new WrapperWriter(bout)这一句做到了)为什么要通过我上面说的方法来获取呢?如果有兴趣可以看下下面代码
public class ResponseWrapper extends HttpServletResponseWrapper{
private ByteArrayOutputStream bout=null;
private WrapperOutputStream myOut=null;
private WrapperWriter pw=null;
public ResponseWrapper(HttpServletResponse response) {
super(response);
bout=new ByteArrayOutputStream();
myOut=new WrapperOutputStream(bout);
pw=new WrapperWriter(bout);
}
public ServletOutputStream getOutputStream(){
return myOut;
}
class WrapperOutputStream extends ServletOutputStream{
private ByteArrayOutputStream baout=null;
public WrapperOutputStream(ByteArrayOutputStream baout){
this.baout=baout;
}
@Override
public void write(int b) throws IOException {
baout.write(b);
}
public ByteArrayOutputStream getByteArrayOutputStream(){
return this.baout;
}
}
class WrapperWriter extends PrintWriter{
private ByteArrayOutputStream out=null;
public WrapperWriter(ByteArrayOutputStream out) {
super(out);
this.out=out;
}
public ByteArrayOutputStream getByteArrayOutputStream(){
return this.out;
}
}
public String getData(){
String a = null;
/*if(pw!=null){
pw.flush();
try {
a=pw.getByteArrayOutputStream().toString("utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(myOut!=null){*/
try {
myOut.flush();
} catch (IOException e) {
System.out.println("出错了这儿!");
e.printStackTrace();
}
try {
a=myOut.getByteArrayOutputStream().toString("utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//}
return a;
}
public PrintWriter getWriter(){
return this.pw;
}
}