2

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

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

  1. mysql-connector-java-5.1.18-bin.jar
  2. commons-beanutils-1.8.2.jar
  3. commons-collections-3.2.1.jar
  4. groovy-all-1.7.5.jar
  5. iText-2.1.7.jar
  6. jasperreports-4.5.0.jar
  7. commons-digester-1.7.jar
  8. commons-logging-1.1.jar
  9. jfreechart-1.0.12.jar
  10. commons-javaflow-20060411.jar

谁能给我一些代码来从 servlet 调用 iReport吗?

4

3 回答 3

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";
    }
}
于 2012-12-22T04:01:22.070 回答
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 的情况下弄清楚如何完成所有工作。

<%@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>
于 2012-10-03T12:47:30.100 回答
0

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

为了获取JasperReport对象,您可以jrxml在运行时编译文件,如如何编译 jrxml 以获取 jasper?或使用预编译.jasper文件,如如何从已编译的 .jasper 文件创建 JasperReport 对象?

于 2012-10-03T12:45:47.923 回答