get jsp response as a string inside servlet

Marko Vranjkovic picture Marko Vranjkovic · Dec 5, 2012 · Viewed 15.2k times · Source

Is there a way to get response from a jsp file as a String inside servlet. Something like

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     String section1 = getResponseFromJSP();
     // do something else ...
     sendMailToUser(section1);
}

I'm using Servlet API 2.4 and java 1.4

Answer

Jörn Horstmann picture Jörn Horstmann · Dec 5, 2012

A better solution might be to use another template engine like freemarker or velocity, which are independent of the servlet api and more suited for text-based emails.

However, this is possible by wrapping the HttpServletResponse and overriding getWriter methods. The code below works for me on glassfish.

Servlet:

public class TestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response) {
            private final StringWriter sw = new StringWriter();

            @Override
            public PrintWriter getWriter() throws IOException {
                return new PrintWriter(sw);
            }

            @Override
            public String toString() {
                return sw.toString();
            }
        };
        request.getRequestDispatcher("test.jsp").include(request, responseWrapper);
        String content = responseWrapper.toString();
        System.out.println("Output : " + content);
        response.getWriter().write(content);
    }
}

JSP:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Hello world</title>
    </head>
    <body>
        <h1><%= "Hello world from a JSP!" %></h1>
    </body>
</html>