簡體   English   中英

使用輸出流在Java servlet中打印出變量

[英]Print out a variable in a Java servlet using output stream

public class DemoServlet extends HttpServlet {

    public void service(HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {

        //prints out my string
        resp.getOutputStream().write("Hello from servlet\n".getBytes());

        String variable ="VAR";
        //trying to print out variable by this way but doesn't work
        resp.getOutputStream().write("%s\n".getBytes(),variable);
        //doesn't work this way either
        resp.getOutputStream().write("variable is:"+ variable +"something else\n".getBytes());
    }
}

首先,我使用的是PageWriter out= resp.getWriter(); 但后來我切換到ServletOutputStream因為我想打印圖像。 其他一切都還可以,但是:

public void makedbconnection() {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Dbcon = DriverManager.getConnection("jdbc:mysql://localhost/test");
    } catch(Exception idc) {
       //ON THIS LINE, out is ServletOutputStream.
       idc.printStackTrace(out);
    }
    //System.out.println("connection made");
}

顯然你可以使用ServletOutputStream#print但你也可以使用PrintWriter

resp.getWriter().print(yourvariable)

out是一個ServletOutputStream 它有一組豐富的重載print()方法。 只是用

out.print(variable);

ServletOutputStreamServletOutputStream print(...)方法。 打印文本時,最好使用它們而不是 write(...)

此外,請注意,您可以使用printwrite 多次

out.print("Hello, the variable is ");
out.print(variable);
out.println(". Something else?");

請注意,不是在字符串的末尾添加\\n ,而是使用println

暫無
暫無

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

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