【问题标题】:Print out a variable in a Java servlet using output stream使用输出流打印出 Java servlet 中的变量
【发布时间】:2011-08-10 09:55:09
【问题描述】:
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");
}

【问题讨论】:

  • 请下次解释您对文本的问题,而不仅仅是代码。此外,当您对答案感到满意时,接受它。谢谢!

标签: java servlets stream


【解决方案1】:

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

resp.getWriter().print(yourvariable)

【讨论】:

    【解决方案2】:

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

    out.print(variable);
    

    【讨论】:

      【解决方案3】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-25
        • 1970-01-01
        • 2020-02-11
        • 1970-01-01
        相关资源
        最近更新 更多