轉載:
bianbian coding life。
有時候咱們須要獲得某個jsp的輸出內容。好比說在servlet裏處理了Module Controller後,須要不一樣的jsp頁面來展現view;又或者獲得不一樣的模板內容(jsp自己能夠做爲模板語言)並將其緩衝到內存裏。
利用 javax.servlet.http.HttpServletResponseWrapper 能夠很好地實現咱們所須要的功能。下面是使用方法:java
- ....
- public static String getJspOutput(String jsppath, HttpServletRequest request, HttpServletResponse response)
- throws Exception
- {
- WrapperResponse wrapperResponse = new WrapperResponse(response);
- request.getRequestDispatcher(jsppath).include(request, wrapperResponse);
- return wrapperResponse.getContent();
- }
能夠看到,使用起來仍是挺方便的。getJspOutput(」/view/header.jsp」, request, response) 就完成了對」/view/header.jsp」的輸出內容獲取,以後能夠進行其餘操做。
附WrapperResponse類代碼:app
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.io.UnsupportedEncodingException;
-
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpServletResponseWrapper
- /**
- * @see http://bianbian.sunshow.net/
- * @author dannyzhu, bianbian
- * @version 1.0
- */
- public class WrapperResponse extends HttpServletResponseWrapper
- {
- private PrintWriter tmpWriter;
- private ByteArrayOutputStream output;
- private ByteArrayServletOutputStream servletOutput;
-
- public WrapperResponse(HttpServletResponse httpServletResponse)
- {
- super(httpServletResponse);
- output = new ByteArrayOutputStream();
- tmpWriter = new PrintWriter(output);
- servletOutput = new ByteArrayServletOutputStream(output);
- }
-
- public void finalize() throws Throwable
- {
- super.finalize();
- servletOutput.close();
- output.close();
- tmpWriter.close();
- }
-
- public String getContent()
- {
- try{
- String s = output.toString("UTF-8");
- reset();
- return s;
- } catch(UnsupportedEncodingException e) {
- return "UnsupportedEncoding";
- }
- }
-
- public PrintWriter getWriter() throws IOException
- {
- // return servletResponse.getWriter();
- return tmpWriter;
- }
-
- public ServletOutputStream getOutputStream() throws IOException
- {
- return servletOutput;
- }
-
- public byte[] toByteArray()
- {
- return output.toByteArray();
- }
-
- public void flushBuffer() throws IOException
- {
- tmpWriter.flush();
- servletOutput.flush();
- }
-
- public void reset()
- {
- output.reset();
- }
-
- public void close() throws IOException
- {
- tmpWriter.close();
- }
-
- private static class ByteArrayServletOutputStream extends ServletOutputStream
- {
-
- ByteArrayOutputStream baos;
-
- public ByteArrayServletOutputStream(ByteArrayOutputStream baos)
- {
- this.baos = baos;
- }
-
- public void write(int i) throws IOException
- {
- baos.write(i);
- }
-
- }
- }
轉載:bianbian coding life。jsp