当resultset为null时,JasperRunManager.runReportToPdfStream返回空白pdf

时间:2014-09-12 09:27:22

标签: javascript jquery ajax jasper-reports

如果我运行查询并且它返回null 结果集,那么 JasperRunManager.runReportToPdfStream 会返回一个空白的pdf,但我想显示错误消息而不是打开下载弹出。

我的java代码是:

Connection con = null;  Statement stmt = null;  ResultSet rs = null;
OutputStream outStream = resourceResponse.getPortletOutputStream();
try{
    JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);
    InputStream reportStream = getPortletConfig().getPortletContext().getResourceAsStream(jasperPath);
    Class.forName("com.ibm.db2.jcc.DB2Driver");
    con=DriverManager.getConnection("jdbc:db2://localhost:50000/wpsdb", db2username, db2password);

    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("select row_number() over(order by f.created_date) as \"SerialNo\"" +
                            ", f.name as \"File\", f.created_by as \"CreatedBy\", f.created_date as " +
                            "\"CreatedOn\", c.name as \"Category\",t.name as \"Tag\" " +
                            "from DMS.File f, DMS.Category c, DMS.Tag t where c.id=f.catid and t.id=f.tagid");

    stmt = con.createStatement();
    rs = stmt.executeQuery(stringBuffer.toString());

    if( !rs.next() ) {
                //handle the code to redirect to same page and display data not found message
    }
    else {
        JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(rs);

                resourceResponse.setContentType("application/pdf");
                resourceResponse.setProperty("Content-disposition", "attachment; filename=\"DMS_File_Report.pdf\"");
                resourceResponse.setCharacterEncoding("UTF-8");
                JasperRunManager.runReportToPdfStream(reportStream, outStream, new HashMap(), resultSetDataSource); 
}catch(Exception e){
    e.printStackTrace();
}

使用ajax我无法打开弹出窗口,所以我使用了window.location.href。这是我的javascript部分:

function genReport(){
         url = "<portlet:resourceURL id='generateReport'></portlet:resourceURL>";
         url +="?param1="+param1;
         window.location.href=url;
}

我不想保存文件,我希望它能够在不保存到底层磁盘的情况下即时生成和下载。

1 个答案:

答案 0 :(得分:0)

您可以在报告和该部分中设置一个组&#34; ERROR MESSAGE&#34;然后在&#39;打印时表达&#39; put(Psuedocode)$ F {rowNumber} == 0或检查如果resultSet为&gt;则不应为null的内容。 0.因此,当resultSet&gt; 0时,此部分将不会显示。否则它会显示出来。

对于第二部分,你可以这样做:

HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext
            .getCurrentInstance().getExternalContext().getResponse();

    httpServletResponse.setContentType("application/pdf");
    httpServletResponse.addHeader("Content-Disposition", "attachment; filename="+name+".pdf");

    JasperPrint print = JasperFillManager
            .fillReport(path+name + ".jasper",parameters,beanCollectionDataSource);


    JasperExportManager.exportReportToPdfStream(print,httpServletResponse.getOutputStream());

    FacesContext.getCurrentInstance().responseComplete();