1

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?

1
  • 1
    construct new request and response objects and pass them to include? Commented Nov 22, 2014 at 19:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.