Skip to content

Instantly share code, notes, and snippets.

@valotas
Created September 25, 2011 12:09
Show Gist options
  • Save valotas/1240545 to your computer and use it in GitHub Desktop.
Save valotas/1240545 to your computer and use it in GitHub Desktop.
Get the output of an the web container as string
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
public class CharArrayWriterResponse extends HttpServletResponseWrapper {
private final CharArrayWriter charArray = new CharArrayWriter();
public CharArrayWriterResponse(HttpServletResponse response) {
super(response);
}
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(charArray);
}
public String getOutput() {
return charArray.toString();
}
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class ServletUsingCustomResponse extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String template = req.getParameter("tmpl");
CharArrayWriterResponse customResponse = new CharArrayWriterResponse(resp);
req.getRequestDispatcher(template).forward(req, customResponse);
System.out.println(String.format("The output of %s is %s", template, customResponse.getOutput()));
}
}
@tejassheth
Copy link

I tried your Approach but it did not work
Can you provide full code ?
Thanks 👍

@davidrcuervo
Copy link

It worked for me. It is very helpful to send emails. Now, I can write my emails by using all the advantages that JSP offers.

Thanks a lot.

@mxracer
Copy link

mxracer commented Aug 22, 2019

Works great, thanks for sharing. Saved me a lot of time researching which classes do use to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment