当前位置: 首页 > 知识库问答 >
问题:

从Servlet调用Jasper iReport

宁鹏程
2023-03-14

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

我使用NetBeans 7.1.2作为IDE。我已经在NetBeans中安装了iReportDesigner-4.5.0作为插件。我已经创建了一个示例报告并存储了。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. 它ext-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?

共有3个答案

东方玉泽
2023-03-14

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

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

方奕
2023-03-14

下面是我用来从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);
}

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

<%@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>
唐元青
2023-03-14
/*
 * 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";
    }
}
 类似资料:
  • 问题内容: 我需要从另一个Servlet调用Servlet的POST方法,并在Servlet的参数中传递一个Blob。这是可能的,如果可以的话,该怎么做。PS:我不能使用Apache HttpClient 问题答案: 您需要自己创建并发送HTTP请求。您不能使用转发/重定向/包含,因为您要将方法从GET更改为POST,并且想要发送请求。 由于显然不是HttpClient(以及其他第三方库?),您最

  • 问题内容: 我正在尝试使用MVC设计模式创建一个Web应用程序。对于GUI部分,我想使用JavaScript。并用于控制器Java Servlet。 现在,我从未真正使用过JavaScript,因此很难弄清楚如何从JavaScript调用Java Servlet,以及如何从Servlet获取响应。 有人可以帮我吗? 问题答案: 因此,您想将Ajax调用激发到servlet吗?为此,您需要JavaS

  • 我在为测试目的调用简单java类中的servlet时遇到了一个问题。我希望将一个参数与servlet一起传递,方法将是post。如何实现? 在搜索答案时,我看到有人推荐了HttpClient。但只是想知道是否有办法避免这种情况。

  • 谁能告诉我,除了RequestDispatcher之外,是否还有其他方法可以从我的servlet调用jsp页面?因为我试了很多都没有成功。 我的servlet工作正常,从JSP中恢复了所有数据。我所需要的只是在用户正确输入用户名和密码时被重定向到另一个页面。 我要为其重定向的jsp

  • 我正在研究一个合作医疗系统。 我的代码在url调用的servlet的

  • 问题内容: 我想从Java应用程序调用Servlet。问题是,该调用似乎未到达Servlet。我没有收到任何错误,但是没有到达Servlet中的第一个输出“ doPost”。如果我在Web浏览器中打开URL,我当然会得到如下错误:不支持GET等。但是至少我知道发生了一些错误。 我使用以下代码(ActionPackage类仅包含一个Vector参数,并且可序列化): Java应用程序: Servle