//获得printWriterProxy
public PrintWriter getWriter() throws IOException {
PrintWriter pw = obj.getWriter();
PrintWriterProxy pwp = new PrintWriterProxy(pw);
return (PrintWriter) pwp;
}
}
PrintWriterProxy:
public class PrintWriterProxy
extends PrintWriter {
private PrintWriter pw = null;
public PrintWriterProxy(PrintWriter pw) {
super(pw);
this.pw = pw;
}
//截获写内容写入buffer
public void write(int c) {
char a = (char) c;
String s = new String(new char[] {a});
HtmlBuffer.addStr(s);
pw.write(c);
}
}
ServletOutputStreamProxy:
public class ServletOutputStreamProxy
extends ServletOutputStream {
private ServletOutputStream obj;
public ServletOutputStreamProxy(ServletOutputStream obj){
this.obj = obj;
}
//截获写内容写入buffer
public void write(int b) throws IOException {
Integer it = new Integer(b);
HtmlBuffer.addStr(new String(new byte[]{it.byteValue()}));
obj.write(b);
}
}
由于web Httpserver 是多线程执行服务端程序,所以buffer应该分线程来存取,这样大家才能不互相干扰。所以buffer需要实现TreadLocal接口。
HtmlBuffer代码简单实现如下:
public class HtmlBuffer {
private static class HtmlInfo extends ThreadLocal {
private Map values = Collections.synchronizedMap(new HashMap());
public Object initialValue() {
return new String();
}
public String getHtmlStr() {
return (String) this.get();
}
public Object get() {
Thread curThread = Thread.currentThread();
Object o = values.get(curThread);
if (o == null && !values.containsKey(curThread)) {
o = initialValue();
values.put(curThread, o);
}
return o;
}
public void set(Object newValue) {
values.put(Thread.currentThread(), newValue);
}
}
private static HtmlInfo htmlInfo = new HtmlInfo();
public static void cleanStr(){
htmlInfo.set( "");
}
public static void addStr(String htmlStr) {
String htmlstr = (String)htmlInfo.get();
if(htmlstr == null) htmlstr ="";
htmlstr += htmlStr;
htmlInfo.set( htmlstr);
}
public static String getStr() {
return (String)htmlInfo.get();
}
}