java - servlet 中的 printWriter()

标签 java jakarta-ee servlets web

我有 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/

相关文章:

java - 字符编码过滤器,韩文字符编码问题

ssl - 错误 "ERR_INVALID_REDIRECT"到表单登录

java - 观察文件夹结构的变化并相应地处理文件

java - 如何在 RecyclerView.Adapter 中打开片段以让用户转到其他用户的个人资料

java - 将对象传递给网络服务

jsp - Tomcat:获取文件路径

java - JSP include 指令,jsp :include action, 相对路径与绝对路径

java - Tomcat 在哪里附加/到目录路径?

java.net.MalformedURLException : unknown protocol: rsrc

java - 如何在 big-o 中找到算法的运行时间