简体   繁体   English

Java:以字符串形式获取其他servlet的输出,而无需修改响应对象

[英]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. 我想对其他Servlet中的数据进行一些修改,然后将其包含在当前Servlet中。 I want to get output of other servlet as String. 我想将其他servlet的输出作为String。

Most of the solutions referred to request.getRequestDispatcher('/path/to/servlet/').include(request, response) . 大多数解决方案都引用了request.getRequestDispatcher('/path/to/servlet/').include(request, response) But this is modifying the response of this servlet too. 但这也正在修改该servlet的响应。 How can I get output of other servlet without modifying output of current servlet? 如何在不修改当前servlet输出的情况下获取其他servlet的输出?

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. 正如A4L所提到的,您可以使用包装的输出编写器(或流,如果被调用的servlet使用它),则使用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. 如果您需要它来处理较大的响应,请考虑编写一个装饰性的PrintWriter,它可以动态执行响应流的修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM