从Servlet调用Jasper iReport

时间:2012-10-03 12:15:37

标签: java jsp servlets jasper-reports ireport

我正在开发基于JSP和MySql的Web应用程序。基本要求是 - 我需要在用户单击超链接时显示报告,并提供将报告导出到Excel的选项。

我使用NetBeans 7.1.2作为我的IDE。我已将iReportDesigner-4.5.0安装为NetBeans中的插件。我创建了一个示例报告,并将.jrxml和.jasper文件存储在我的项目文件夹中。现在我试图使用servlet调用报告。我在项目库中包含了以下JAR文件 -

  1. MySQL的连接器的Java-5.1.18-bin.jar
  2. 公地BeanUtils的-1.8.2.jar
  3. 公地集合-3.2.1.jar
  4. Groovy的全1.7.5.jar
  5. 的iText-2.1.7.jar
  6. 的JasperReports-4.5.0.jar
  7. 公地消化器-1.7.jar
  8. 共享记录-1.1.jar
  9. jfreechart的-1.0.12.jar
  10. 公地javaflow-20060411.jar
  11. 任何人都可以提供一些代码来从servlet调用iReport 吗?

3 个答案:

答案 0 :(得分:2)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bitsperu.academia.reporte;


import com.bitsperu.academia.utilidades.DAO.DAO;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;

/**
 *
 * @author carlos
 */
public class Matricula extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/pdf");
        ServletOutputStream out = response.getOutputStream();
        Connection cn = DAO.getConexion();

        try {
            JasperReport reporte = (JasperReport) JRLoader.loadObject(getServletContext().getRealPath("app/matricula/matricula_byid.jasper"));

            Map parametros = new HashMap();
            parametros.put("id", request.getParameter("id"));
            //parametros.put("ot_entidad_id", request.getSession().getAttribute("ot_entidad_id"));
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, cn);

            JRExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
            exporter.exportReport();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

答案 1 :(得分:1)

这是我用来从servlet填充jasper报告的一些代码。这有点定制,但应该帮助你。

public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException {
    HttpSession httpSession = req.getSession();     
    String errorMessage = null;
    String forwardTo = null;
    String reportName = req.getParameter("reportName");
    String cameFrom = req.getParameter("cameFrom");
    if (StringUtils.isEmpty(reportName)) { // direct to report menu
        String type = req.getParameter("type");
        forwardTo = "/WEB-INF/jsp/reports.jsp?cameFrom=" + cameFrom + ((StringUtils.isEmpty(type)) ? "" : "&type=" + type);
    } else { // direct to specific report
        forwardTo = "/WEB-INF/jsp/jasperreport.jsp?cameFrom=" + cameFrom;
        JasperPrint jasperPrint = null;
        Connection conn = null;
        int page = -1;
        try {
            page = new Integer(StringUtils.defaultIfEmpty(req.getParameter("page"), "-1"));
        } catch (NumberFormatException ignore) {}
        boolean isFirstTime = (page == -1);
        boolean isCSV = (page == -99);
        String reportTitle = req.getParameter("reportTitle");
        String jasperPath = (String)httpSession.getServletContext().getAttribute("jasperpath");
        String reportPath = jasperPath + "/" + reportName + ".jasper";
        File reportFile = new File(reportPath);
        if (reportFile == null || !reportFile.exists())
            throw new IOException("File " + reportPath + " not found. The report design must be compiled first.");


        try {   
            if (isFirstTime) { // Clear any leftover report session attributes.
                httpSession.removeAttribute("jasperPrint");
                httpSession.removeAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE);
                httpSession.removeAttribute("reportTitle");
                httpSession.removeAttribute("reportName");
                httpSession.removeAttribute("jasperError");
                Integer nParms = (Integer) httpSession.getAttribute("nParms");
                if (nParms == null) nParms = 0;
                httpSession.removeAttribute("nParms");
                for (int ixParm = 1; ixParm < nParms + 1; ++ixParm) {
                    httpSession.removeAttribute("parmName_" + ixParm);
                    httpSession.removeAttribute("parmValue_" + ixParm);
                }
            }
            httpSession.setAttribute("reportName", reportName);

            if (isFirstTime || isCSV) {
                JasperReport jasperReport = (JasperReport)JRLoader.loadObject(reportPath);

                conn = ReportServiceImpl.getDBConnectionForReports();

                @SuppressWarnings("rawtypes")
                Map<String, Comparable> parameters = new HashMap<String, Comparable>();
                parameters.put("SUBREPORT_DIR", String.valueOf(reportFile.getParentFile()) + java.io.File.separator);
                parameters.put("ReportTitle", reportTitle);
                parameters.put("BaseDir", reportFile.getParentFile());

                // Get report-specific parameters (if any).
                int nParms = 0;
                try {
                    if (isFirstTime) {
                        nParms = new Integer(StringUtils.defaultIfEmpty(req.getParameter("nParms"), "0"));
                        httpSession.setAttribute("nParms", nParms);
                    } else nParms = (Integer)httpSession.getAttribute("nParms");
                } catch (NumberFormatException ignore) {}
                for (int ixParm = 1; ixParm < nParms + 1; ++ixParm) {
                    String _parmName = null;
                    String _parmValue = null;
                    if (isFirstTime) { // get parms from request and place in session
                        _parmName = req.getParameter("parmName_" + ixParm);
                        _parmValue = req.getParameter("parmValue_" + ixParm);
                        httpSession.setAttribute("parmName_" + ixParm, _parmName);
                        httpSession.setAttribute("parmValue_" + ixParm, _parmValue);
                    } else { // get parms from session
                        _parmName = (String) httpSession.getAttribute("parmName_" + ixParm);
                        _parmValue = (String) httpSession.getAttribute("parmValue_" + ixParm);
                    }
                    if (!StringUtils.isEmpty(_parmName)) { // if date range not specified, use defaults
                        if (_parmName.equals("START_TIME_MS") || _parmName.equals("END_TIME_MS")) {
                            BigDecimal dateMillis = new BigDecimal(0l);
                            if (_parmValue.length() == 0) {
                                if (_parmName.equals("START_TIME_MS")) dateMillis = new BigDecimal(0l);
                                else dateMillis = new BigDecimal(System.currentTimeMillis());
                            } else {
                                if (_parmValue.contains("/"))
                                    dateMillis = new BigDecimal(ReportServiceImpl.getDateInMillis(_parmValue));
                                else dateMillis = new BigDecimal(_parmValue);
                            }
                            parameters.put(_parmName, dateMillis);
                        } else parameters.put(_parmName, _parmValue);
                    }
                }

                jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
                httpSession.setAttribute("reportTitle", reportTitle);
                httpSession.setAttribute((isCSV) ? "jasperPrintCSV" : "jasperPrint", jasperPrint);
                if (isFirstTime)
                    httpSession.setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
            }
        } catch (LoadingException le) {
            le.printStackTrace();
            errorMessage = "Problem reading db connection properties.";
        } catch (SQLException e) {
            e.printStackTrace();
            errorMessage = "Problem opening db connection.";
        } catch (JRException jre) {
            jre.printStackTrace();
            errorMessage = "Jasper problem loading/filling report: " + reportPath;
        } catch (DatabaseException de) {
            de.printStackTrace();
            errorMessage = "Problem retrieving hibernate session.";
        } catch (HibernateException he) {
            he.printStackTrace();
            errorMessage = "Problem getting hibernate transaction or database connection.";
        } catch (IllegalArgumentException iae) {
            errorMessage = "No data found for report: \"" + reportTitle + "\"";
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) ReportServiceImpl.closeDBConnectionForReports();
            } catch (Exception ignore) {}
        }
    }
    if (!StringUtils.isEmpty(errorMessage))
        httpSession.setAttribute("jasperError", errorMessage);
    getServletConfig().getServletContext().getRequestDispatcher(forwardTo).forward(req, res);
}

这是一个与servlet交互以创建显示和CSV报告的jsp。对不起,如果你是一个scriptlet纯粹主义者,但我最初从其他地方得到这个代码,它有点毛茸茸。我相信如果你需要,你可以在不使用scriptlet的情况下解决如何完成所有工作。

<%@page import="java.util.HashMap"%><%@
page import="java.io.FileInputStream"%><%@
page import="net.sf.jasperreports.engine.*" %><%@
page import="net.sf.jasperreports.engine.util.*" %><%@
page import="net.sf.jasperreports.engine.export.*" %><%@
page import="net.sf.jasperreports.j2ee.servlets.*" %><%@
page import="java.sql.Connection" %><%@
page import="org.hibernate.Session" %><%@
page import="org.hibernate.Transaction" %><%@
page import="com.pa.rollupedit.common.connection.HibernateSessionFactory" %><%@
page import="com.pa.rollupedit.loader.utility.Util"%><%@
page import="org.apache.commons.lang.StringUtils"%><%
String reportTitle = StringUtils.defaultIfEmpty((String)session.getAttribute("reportTitle"), "");
String reportName = StringUtils.defaultIfEmpty((String)session.getAttribute("reportName"), "");
boolean isCSV = reportName.contains("CSV");
JasperPrint jasperPrint = (JasperPrint)session.getAttribute("jasperPrint");
JasperPrint jasperPrintCSV = (JasperPrint)session.getAttribute("jasperPrintCSV");
String errorMessage = (String)session.getAttribute("jasperError");
boolean top = new Boolean(StringUtils.defaultIfEmpty(request.getParameter("top"), "false"));
boolean hasCSV = new Boolean(StringUtils.defaultIfEmpty(request.getParameter("hasCSV"), "false"));
String cameFrom = StringUtils.defaultIfEmpty(request.getParameter("cameFrom"), "admin");
String type = StringUtils.defaultIfEmpty(request.getParameter("type"), "editing");
int pageIndex = 0;
int lastPageIndex = 0;
StringBuffer sbuffer = new StringBuffer();

if (StringUtils.isEmpty(errorMessage)) {
    if (isCSV) {
        try {
            OutputStream os = response.getOutputStream();
            JRCsvExporter exporter = new JRCsvExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrintCSV);
            exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, sbuffer);
            exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "image?image=");
            exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(pageIndex));
            exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, "");
            exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
            exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");

            exporter.exportReport();

            byte[] csvBytes = sbuffer.toString().getBytes();
            InputStream is = new ByteArrayInputStream(csvBytes);

            response.setContentType("text/comma-separated-values");
            response.setHeader("Content-Disposition",
                "attachment;filename=\"" + reportName + ".csv\"");
            byte[] fileBytes = new byte[10240000];
            int bytesRead = is.read(fileBytes, 0, 10240000);
            while (bytesRead >= 0) {
                os.write(fileBytes, 0, bytesRead);
                bytesRead = is.read(fileBytes, 0, 10240000);
            }
            is.close();
            os.flush();
            os.close();
            out.clearBuffer();
            return;
        } catch (Exception e) {
            e.printStackTrace();
            errorMessage = "Problem generating CSV download file: " + e.getMessage();
        }

    } else {
        JRHtmlExporter exporter = new JRHtmlExporter();

        if (jasperPrint.getPages() != null)
            lastPageIndex = jasperPrint.getPages().size() - 1;

        try {
            pageIndex = new Integer(StringUtils.defaultIfEmpty(request.getParameter("page"), "0"));
        } catch (NumberFormatException ignore) {}

        if (pageIndex < 0) pageIndex = 0;
        if (pageIndex > lastPageIndex) pageIndex = lastPageIndex;

        if (pageIndex < 0) errorMessage = "Report has no data.";
        else {
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, sbuffer);
            exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "image?image=");
            exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(pageIndex));
            exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, "");
            exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
            exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");

            exporter.exportReport();
        }
    }
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="css/pearson.css" type="text/css" rel="stylesheet" />
<link href="css/portlet-specifics.css" type="text/css" rel="stylesheet" />
<link href="css/fancy.css" type="text/css" rel="stylesheet" />
<title><%=reportTitle%></title>
<script type="text/javascript" src="js/commonJS.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<script>window.history.forward(1);</script>
<script type="text/javascript">
function back() {
    var myForm = document.getElementById("myform");
    myForm.action = "ReportController?type=<%=type%>&cameFrom=<%=cameFrom%>";
    myForm.submit();
}
function downloadCSV() {
    //document.getElementById("twirliecsv").style.visibility = "visible";
    var url = "ReportController?reportName=<%=reportName%>CSV&reportTitle=<%=reportTitle%>&top=<%=top%>&hasCSV=<%=hasCSV%>&page=-99";
    var w = window.open(url, "_blank",
        "height=700, width=1000, left=50, top=100, toolbar=0, titlebar=1, scrollbars=1, resizable=1, menubar=0, location=0, directories=0, status=0, modal=1, alwaysRaised=1");
}
</script>
</head>
<body text="#000000" link="#000000" alink="#000000" vlink="#000000">
<%if (StringUtils.isEmpty(errorMessage)) {%>
<form id="myform" action="ReportController">
  <input type="hidden" id="type" name="type" value="<%=type%>"/>
  <input type="hidden" id="cameFrom" name="cameFrom" value="<%=cameFrom%>"/>
  <table width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td width="50%">&nbsp;</td>
      <td align="left">
        <hr size="1" color="#000000">
        <table width="100%" cellpadding="0" cellspacing="0" border="0">
          <tr>
            <%if (top) {%>
                <td><input onclick="back();" type="button" class="admin-button" value="Back"/></td>
            <%} else {%>
                <td><input onclick="window.top.close();" type="button" class="admin-button" value="Close"/></td>
            <%}
            if (hasCSV) {%>
                <td><input onclick="downloadCSV();" type="button" class="admin-button" value="CSV"/></td>
            <%}%>
            <td>&nbsp;&nbsp;&nbsp;</td>
            <%if (!isCSV) {
                if (pageIndex > 0) {%>
                    <td><a href="ReportController?reportName=<%=reportName%>&reportTitle=<%=reportTitle%>&top=<%=top%>&hasCSV=<%=hasCSV%>&page=0"><img src="images/first.GIF" border="0"></a></td>
                    <td><a href="ReportController?reportName=<%=reportName%>&reportTitle=<%=reportTitle%>&top=<%=top%>&hasCSV=<%=hasCSV%>&page=<%=pageIndex - 1%>"><img src="images/previous.GIF" border="0"></a></td>
                <%} else {%>
                    <td><img src="images/first_grey.GIF" border="0"></td>
                    <td><img src="images/previous_grey.GIF" border="0"></td>
                <%}
                if (pageIndex < lastPageIndex) {%>
                    <td><a href="ReportController?reportName=<%=reportName%>&reportTitle=<%=reportTitle%>&top=<%=top%>&hasCSV=<%=hasCSV%>&page=<%=pageIndex + 1%>"><img src="images/next.GIF" border="0"></a></td>
                    <td><a href="ReportController?reportName=<%=reportName%>&reportTitle=<%=reportTitle%>&top=<%=top%>&hasCSV=<%=hasCSV%>&page=<%=lastPageIndex%>"><img src="images/last.GIF" border="0"></a></td>
                <%} else {%>
                    <td><img src="images/next_grey.GIF" border="0"></td>
                    <td><img src="images/last_grey.GIF" border="0"></td>
                <%}
            }%>
            <td width="100%">&nbsp;</td>
          </tr>
        </table>
        <hr size="1" color="#000000">
      </td>
      <td width="50%">&nbsp;</td>
   </tr>
   <tr>
      <td width="50%">&nbsp;</td>
      <td align="center">
        <%=sbuffer.toString()%>
      </td>
    </tr>
  </table>
</form>
<%} else {%>
    <form action="ReportController">
        <input type="hidden" id="cameFrom" name="cameFrom" value="<%=cameFrom%>"/>
        <div style="margin: 20px 20px;">
        <%if (top) {%>
            <a href="ReportController"><input type="submit" class="admin-button" value="Back"/></a>
        <%} else {%>
            <input onclick="window.top.close();" type="button" class="admin-button" value="Close"/>
        <%}%>
        </div>
    </form>
    <div style="color: red; margin: 20px 20px; font: bold 16px/18px Arial, sans-serif;"><%=errorMessage%></div>
<%}%>
</body>
</html>

答案 2 :(得分:0)

您可以使用JasperFillManager生成报告(一旦有JasperReport个对象)。您可以稍后使用JasperExportManager将其打印出来。

为了获得JasperReport对象,您可以在运行时编译jrxml文件,如How do I compile jrxml to get jasper?中所述,或使用预编译的.jasper文件,如How to create JasperReport object from compiled .jasper file?