如何使用返回类型为 void 的方法将 servlet 的输出打印到 JSP 页面上



我正在开发一个Web应用程序,其中我使用各种字符串操作方法,返回类型为字符串或Java 类的列表。我在我的servlet中调用这些方法并使用JSTL,我成功地将输出打印到我的JSP页面。因此,JSTL语法或基本的Servlet-JSP交互没有问题。下面是一个示例:

我的基类具有所有这些函数:

public class MethodClass {
// Skipping unwanted code and only providing example
    public static List<String> method1 (String input) {
         // Returns List of Strings
    }
    public static String method2 (String input) {
        // Returns a string
    }
    public static void method3 (String input) {
       // This method has to print text on console. I can't redirect that to a String.
       System.out.println(input);
    }
}

下面是我的 Servlet 代码(仅限相关代码段)

            listMethod1 = MethodClass.method1(input);
            request.setAttribute("Myresults", listMethod1);
            request.getRequestDispatcher("/results.jsp").forward(request, response);

在我的 JSP 中,我正在使用以下内容:

<c:forEach items="${Myresults}" var="result">       
    <tr>
        <td>${result.frameNum}</td>
        <td>${result.number}</td>
        <td>${result.name}</td>
        <td>${result.length}</td>
    </tr>
</c:forEach>

到目前为止没有问题。我的问题是如何将 method3 的输出打印到文本区域中。AFAIK,response.getWriter()的out.println函数可用于直接在JSP上打印,而无需提供打印到某个字段,如某个JSP文件的文本区域或文本框。我是否可以遵循任何其他方法,我可以以某种方式将控制台上打印的 void 方法的输出重定向到字符串,然后使用该类似于我上面提供的示例的字符串来显示输出。

我想

我找到了一个技巧。再次感谢堆栈溢出。

这是链接:将控制台输出重定向到 java 中的字符串

以下是我使用的相关代码片段:

// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
// IMPORTANT: Save the old System.out!
PrintStream old = System.out;
// Tell Java to use your special stream
System.setOut(ps);
// Print some output: goes to your special stream
System.out.println("Foofoofoo!");
// Put things back
System.out.flush();
System.setOut(old);
// Show what happened
System.out.println("Here: " + baos.toString());

现在,您的System.out输出可以保存为字符串,并且可以在JSP中与JSTL一起使用。

最新更新