调用response.getOutputStream()后,Jasper Reports servlet停止工作

时间:2011-08-29 01:52:21

标签: java servlets jasper-reports

我的代码如下。该计划在servletOutputStream = response.getOutputStream();行停止工作。我不知道怎么解决这个问题?有人可以帮我解决这个问题吗?

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

        out.println ("<html>");
        out.println ("    <head>");
        out.println ("        <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
        out.println ("        <title>JSP Page</title>");
        out.println ("    </head>");
        out.println ("    <body>");
        out.println ("        <h1>Hello iReport!</h1>");

        String resourceName = "D:/classic.jrxml";         
        response.setContentType("application/pdf");
        ServletOutputStream servletOutputStream = null;
        servletOutputStream = response.getOutputStream(); // <--
        InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream(resourceName);
        try {
                Driver driver = new org.gjt.mm.mysql.Driver();
                DriverManager.registerDriver(driver);
                String conString = "jdbc:mysql://localhost:3306/quanlynhasach";
                Properties info = new Properties(); 
                info.setProperty("characterEncoding", "utf8");
                info.setProperty("user", "root"); 
                info.setProperty("password", ""); 
                Connection con =  DriverManager.getConnection(conString, info);               
                JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream,new HashMap<Object, Object>(), con);
                con.close();

        }catch(Exception e){
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
             e.printStackTrace(printWriter);
            response.setContentType("text/plain");
            response.getOutputStream().print(stringWriter.toString());
        }
        out.println ("    </body>");
        out.println ("</html>");

    } finally {     

        out.close();
    }
}  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/** 
 * Handles the HTTP <code>GET</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        try {
            processRequest(request, response);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(iReport.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(iReport.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (SQLException ex) {
        Logger.getLogger(iReport.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JRException ex) {
        Logger.getLogger(iReport.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        try {
            processRequest(request, response);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(iReport.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(iReport.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (SQLException ex) {
        Logger.getLogger(iReport.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JRException ex) {
        Logger.getLogger(iReport.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/** 
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

2 个答案:

答案 0 :(得分:5)

看这里:

PrintWriter out = response.getWriter();
// *snip*
servletOutputStream = response.getOutputStream();

您从响应中获得 WriterOutputStream。这是不允许的。阅读他们的javadocs:

  

getOutputStream()

ServletOutputStream getOutputStream() throws java.io.IOException
     

返回适合在响应中写入二进制数据的ServletOutputStream。 servlet容器不对二进制数据进行编码。

     

flush()上调用ServletOutputStream会提交回复。 可以调用此方法或getWriter()来编写正文,而不是两者。

  

getWriter()

java.io.PrintWriter getWriter() throws java.io.IOException
     

返回可以将字符文本发送到客户端的PrintWriter对象。 PrintWriter使用getCharacterEncoding()返回的字符编码。如果未按getCharacterEncoding中所述指定响应的字符编码(即,该方法仅返回默认值ISO-8859-1),则getWriter将其更新为ISO-8859-1。

     

flush()上调用PrintWriter会提交回复。

     

可以调用此方法或getOutputStream()来编写正文,而不是两者。

(强调我的)

问题在于你的特殊情况,但问题要大得多。您试图在HTML响应中的这些HTML标记之间内联Jasper报告的PDF结果。在编写代码时我不确定你的想法或吸烟,但这绝对不会起作用。您需要以这种方式重写servlet,以便返回PDF而不是那堆HTML噪声。您应该将所有HTML从servlet移到某个JSP文件中。然后,您可以通过JSP中的简单下载链接调用该servlet

<a href="yourServletUrl">Download PDF</a>

或在<iframe>内(是的,在JSP中)

<iframe src="yourServletUrl" style="width: 500px; height: 300px;"></iframe>

或在<object>中(也在这里,仅在JSP中)

<object data="yourServletUrl" type="application/pdf" width="500" height="300" />

只需将该HTML放在JSP页面中,在浏览器中打开JSP,webbrowser就会注意调用servlet,并按照您的意图表示PDF。

你的另一个问题是异常处理不是很好。由于未重置响应缓冲区,因此您将完全看不到任何方式。你应该做一个

} catch (Exception e) {
    throw new ServletException("descriptive message here", e);
}

因为容器完全知道如何处理异常。

你的doGet()doPost()所做的完全相同也是一种设计气味。您在那里使用的JDBC驱动程序已完全过时并已弃用。你如何注册驱动程序是笨拙的。在finally中未关闭数据库连接容易导致资源泄漏。好的,我会停止......

答案 1 :(得分:0)

我认为您收到了IllegalStateException,因为您在同一回复中呼叫getWriter()getOutputStream()。你不允许这样做。