我有 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());
}
最佳答案
在同一调用中同时使用 getServletOutputStream()
和 getWriter()
是非法的。您应该只使用一个。
这就是 Java 文档所说的:
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 Throws: IllegalStateException - if the getWriter method has been called on this response
关于java - servlet 中的 printWriter(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30134517/