有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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) 个答案

  1. # 1 楼答案

    out是一个ServletOutputStream。它有一组丰富的重载print()方法。使用

    out.print(variable);
    
  2. # 2 楼答案

    ServletOutputStream有大量的print(...)方法。打印文本时,最好使用而不是而不是write(...)文本

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

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

    请注意,与其在字符串末尾添加\n,不如使用println

  3. # 3 楼答案

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

    resp.getWriter().print(yourvariable)