获取sevlet response值

调用:

PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
SimpleWrapper wrapper = new SimpleWrapper(response);
/* サーブレットから出力される HTML を取得 */
String outHtml = wrapper.toString();

System.out.println("=" + outHtml);

try {
wrapper.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

 

实现:

------------------------------------------------------------------------

SimpleWrapper.java

package com.autocredit.web.filter;

import java.io.CharArrayWriter;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class SimpleWrapper extends HttpServletResponseWrapper {

private CharArrayWriter caw = null;

public SimpleWrapper(HttpServletResponse response) {
super(response);
caw = new CharArrayWriter();
}

public String toString() {
/* CharArrayWriter の toString を呼び出します */
return caw.toString();
}

public PrintWriter getWriter() {
/* CharArrayWriter で PrintWriter を返却します。 */
return new PrintWriter(caw);
}

public ServletOutputStream getOutputStream() {
/* SampleServletOutputStream を返却します。 */
return new SampleServletOutputStream(caw);
}

class SampleServletOutputStream extends ServletOutputStream {

private CharArrayWriter buffer = null;

public SampleServletOutputStream(CharArrayWriter charArrayWriter) {
super();
buffer = charArrayWriter;
}

public void write(int c) {
buffer.write(c);
}

@Override
public boolean isReady() {
// TODO Auto-generated method stub
return false;
}

@Override
public void setWriteListener(WriteListener writeListener) {
// TODO Auto-generated method stub

}
}
}

posted on 2016-01-14 15:27  adolfmc  阅读(493)  评论(0编辑  收藏  举报