简体   繁体   中英

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.

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. You should use only one.

This is what Java Doc says :

getOutputStream...

ServletOutputStream getOutputStream() throws IOException

Returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data.

Calling flush() on the ServletOutputStream commits the response. Either this method or getWriter() may be called to write the body, not both.

Returns: a ServletOutputStream for writing binary data

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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