Dheerendra
Dheerendra

Reputation: 1568

Java: Get output of other servlet as a string without modifying response object

I want to include the data from other servlet in my current servlet with slight modifications. I want to get output of other servlet as String.

Most of the solutions referred to request.getRequestDispatcher('/path/to/servlet/').include(request, response). But this is modifying the response of this servlet too. How can I get output of other servlet without modifying output of current servlet?

Upvotes: 1

Views: 832

Answers (1)

You can, as A4L mentions, use a wrapped output writer (or stream, if the called servlet uses that), to capture the intermediate results as a string with a StringWriter. It might look as this:

    protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        RequestDispatcher dispatcher =
            request.getRequestDispatcher("/other-servlet");
        StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        HttpServletResponse responseWrapper =
            new HttpServletResponseWrapper(response) {
                @Override
                public PrintWriter getWriter() throws IOException {
                    return pw;
                }
            };
      dispatcher.include(request, responseWrapper);
    out.println(this + ": The other servlet also wrote: " + sw.toString());
    out.close();
}

However, you should be careful about using this technique on large data, as collecting stream data in strings kills performance. If you need it to work on large responses, consider writing a decorating PrintWriter, which performs the modifications of response stream on the fly.

Upvotes: 1

Related Questions