使用输出流在Java servlet中打印出变量

时间:2011-04-21 15:22:41

标签: java servlets 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");
}

3 个答案:

答案 0 :(得分:5)

显然,您可以使用ServletOutputStream#print,但也可以使用PrintWriter

resp.getWriter().print(yourvariable)

答案 1 :(得分:4)

outServletOutputStream。它有一组丰富的重载print()方法。只需使用

out.print(variable);

答案 2 :(得分:0)

ServletOutputStream有一大堆print(...)方法。打印文本时,最好使用代替 write(...)个。

另请注意,您可以使用printwrite 多次次:

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

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