2012-10-03 61 views
2

我正在研究基於JSP和MySql的Web應用程序。基本要求是 - 我需要在用戶點擊超鏈接時顯示報告,並提供將報告導出爲Excel的選項。從Servlet調用Jasper iReport

我使用NetBeans 7.1.2作爲我的IDE。我已經安裝了iReportDesigner-4.5.0作爲NetBeans插件。我創建了一個示例報告並將.jrxml和.jasper文件存儲在我的項目文件夾中。現在我正在嘗試使用servlet調用報告。我已經包括了我的項目庫中的下列JAR文件 -

  1. 使用mysql-connector-java的5.1.18-bin.jar
  2. 公地的BeanUtils-1.8.2.jar
  3. 公地collections- 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

任何人都可以請提供我一些代碼來調用從servlet的iReport的?

回答

1

這裏解釋的一些代碼,我用它來填補碧玉報告從一個servlet。這是一個定製的,但應該幫助你。

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
/* 
* 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"; 
    } 
}