简体   繁体   English

servlet中的printWriter()

[英]printWriter() in servlet

I have servlet to retrieve image from an oracle database inside doGet() and it works fine but when using printwriter() the code does not work. 我有servlet可以从doGet()的oracle数据库中检索图像,它可以正常工作,但是当使用printwriter() ,代码不起作用。

protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
     response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();

     String id = request.getParameter("submit");
    try {

        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "APP_DB", "1234");
        PreparedStatement ps = con.prepareStatement("select photo from photos where id = ?");
        ps.setString(1, id);
        ResultSet rs = ps.executeQuery();
        rs.next();
        Blob b = rs.getBlob("photo");
        response.setContentType("image/jpeg");
        response.setContentLength((int) b.length());
        InputStream is = b.getBinaryStream();
        OutputStream os = response.getOutputStream();
        byte buf[] = new byte[(int) b.length()];
        is.read(buf);
        os.write(buf);
         os.close();
        out.print("<a href='DisplyExcServlet'>visit</a>");//does not work            

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }

It is illegal to use both getServletOutputStream() and getWriter() in the same call. 在同一调用中同时使用getServletOutputStream()getWriter()是非法的。 You should use only one. 您只能使用一个。

This is what Java Doc says : 这就是Java Doc所说的:

getOutputStream... 的getOutputStream ...

ServletOutputStream getOutputStream() throws IOException ServletOutputStream getOutputStream()引发IOException

Returns a ServletOutputStream suitable for writing binary data in the response. 返回适合于在响应中写入二进制数据的ServletOutputStream。 The servlet container does not encode the binary data. Servlet容器不对二进制数据进行编码。

Calling flush() on the ServletOutputStream commits the response. 在ServletOutputStream上调用flush()会提交响应。 Either this method or getWriter() may be called to write the body, not both. 可以调用此方法或getWriter()来编写正文,而不能同时调用两者。

Returns: a ServletOutputStream for writing binary data Throws: IllegalStateException - if the getWriter method has been called on this response 返回:用于写入二进制数据的ServletOutputStream 抛出:IllegalStateException-如果已在此响应上调用getWriter方法。

You must no close the outputstream when you want to do further writing to it. 要进一步写入输出流,必须不要关闭它。 change 更改

    os.close();
    out.print("<a href='DisplyExcServlet'>visit</a>");

to

    out.print("<a href='DisplyExcServlet'>visit</a>");
    os.close(); // now you can close it ^^

and it should work. 它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM