使用输出流在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\");
}
    
已邀请:
显然,您可以使用
ServletOutputStream#print
,但也可以使用PrintWriter。
resp.getWriter().print(yourvariable)
    
ѭ6是ServletOutputStream。它具有丰富的重载
print()
方法集。只需使用
out.print(variable);
    
ServletOutputStream
具有大量的
print(...)
方法。打印文本时,最好使用而不是
write(...)
。 另外,请注意,您可以多次使用
print
write
out.print(\"Hello, the variable is \");
out.print(variable);
out.println(\". Something else?\");
请注意,与其在字符串末尾添加ѭ15,不如使用ѭ16。     

要回复问题请先登录注册