Categories: Snippets

Get jsp response as a string inside servlet

To get jsp response as a string inside servlet is possible by wrapping the HttpServletResponse and overriding getWriter methods.

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>

 

Recent Posts

Read Input from User

In Java, there are three different ways for reading input from the user in the…

6 years ago

Find Upper Case & Lower Case

Given a string, bellow it shows the boolean condition to find Lowercase characters, Uppercase characters.…

6 years ago

Sorting HashMap by values in ascending and descending order

The below example shows Java program to sort a Map by values in ascending and…

6 years ago