2015-05-08 52 views
0

我有Servlet從doGet()內的oracle數據庫中檢索圖像,它工作正常,但使用printwriter()時代碼不起作用。servlet中的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()); 
    } 
+2

請詳細說明了「不工作」的一部分。 – CptBartender

回答

0

當您想進一步寫入輸出流時,您不能關閉輸出流。改變

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

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

,它應該工作。

1

在同一個呼叫中同時使用getServletOutputStream()getWriter()是非法的。你應該只使用一個。

這就是Java文檔說:

的getOutputStream ...

ServletOutputStream的的getOutputStream()拋出IOException異常

返回適合於在響應寫入二進制數據的ServletOutputStream的。 servlet容器不編碼二進制數據。

調用ServletOutputStream上的flush()提交響應。 可以調用此方法或getWriter()來寫入主體,而不是兩者。

返回:寫入二進制數據 拋出一個ServletOutputStream的:IllegalStateException - 如果的getWriter方法被調用此響應