簡體   English   中英

如何使用返回類型為void的方法將servlet的輸出打印到JSP頁面上

[英]How can I print output from a servlet onto JSP page using method with return type as void

我正在開發一個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方法的輸出重定向到String,然后使用該String,類似於我上面提供的示例以顯示輸出。

我想我找到了一個竅門。 再次感謝stackOverflow。

這里是鏈接: 將控制台輸出重定向到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輸出可以另存為String,並且通常可以在JSP中與JSTL一起正常使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM