sup*_*oom 15 java jsp servlets printwriter
我正在使用JSP生成动态页面,我想将此动态生成的完整页面保存为文件存档.
在JSP中,所有内容都写入 PrintWriter out  = response.getWriter();
在页面的末尾,在向客户端发送响应之前,我想要保存此页面,无论是在文件中还是在缓冲区中作为字符串,以便以后处理.
如何保存Printwriter内容或转换为String?
wes*_*ton 21
要从a的输出中获取字符串PrintWriter,可以通过构造函数StringWriter将a 传递给a PrintWriter:
@Test
public void writerTest(){
    StringWriter out = new StringWriter();
    PrintWriter writer = new PrintWriter(out);
    // use writer, e.g.:
    writer.print("ABC");
    writer.print("DEF");
    writer.flush(); // flush is really optional here, as Writer calls the empty StringWriter.flush
    String result = out.toString();
    assertEquals("ABCDEF", result);
}
Alv*_*unk 11
为什么StringWriter不用呢?我认为这应该能够满足您的需求.
例如:
StringWriter strOut = new StringWriter();
...
String output = strOut.toString();
System.out.println(output);
它取决于:如何构造然后使用PrintWriter.
如果将PrintWriter构造为1st,然后传递给写入它的代码,则可以使用Decorator模式,该模式允许您创建Writer的子类,将PrintWriter作为委托,并将调用转发给委托,但是还会保留您可以存档的内容副本.
public class DecoratedWriter extends Writer
{
   private final Writer delegate;
   private final StringWriter archive = new StringWriter();
   //pass in the original PrintWriter here
   public DecoratedWriter( Writer delegate )
   {
      this.delegate = delegate;
   }
   public String getForArchive()
   { 
      return this.archive.toString();
   } 
   public void write( char[] cbuf, int off, int len ) throws IOException
   {
      this.delegate.write( cbuf, off, len );
      this.archive.write( cbuf, off, len );
   }
   public void flush() throws IOException
   {
      this.delegate.flush();
      this.archive.flush();
   } 
   public void close() throws IOException
   {
      this.delegate.close();
      this.archive.close();
   }
}
| 归档时间: | 
 | 
| 查看次数: | 39980 次 | 
| 最近记录: |