2010-03-08 81 views

回答

1

這是一個在Servlet文件中創建的虛擬報告。

它與普通Java類中的相同。

只要確保您有文件頂部的jasper報告類的導入。

下面的示例從XML數據源構建報表。

public class JasperServlet extends HttpServlet { 
    public void doGet(HttpServletRequest req, HttpServletResponse res) 
      throws ServletException, IOException { 
     try { 
      String reportFile = "myJasperReport.jrxml"; 
      File outputFile = new File("Report.pdf"); 
      HashMap hm = new HashMap(); 

      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory 
        .newInstance(); 
      DocumentBuilder documentBuilder = documentBuilderFactory 
        .newDocumentBuilder(); 
      Document document = documentBuilder.parse(new File("myXml.xml")); 

      // Compile the report 
      JasperReport report = JasperCompileManager 
        .compileReport(reportFile); 
      JRXmlDataSource xml = new JRXmlDataSource(document, "/xml/root"); 
      // Fill the report 
      JasperPrint print = JasperFillManager.fillReport(report, hm, xml); 
      // Create an Exporter 
      JRExporter exporter = new JRPdfExporter(); 
      exporter.setParameter(JRExporterParameter.OUTPUT_FILE, outputFile); 
      exporter.setParameter(JRExporterParameter.JASPER_PRINT, print); 
      // Export the file 
      exporter.exportReport(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
5

您可以準備Jasper文件並將其傳輸到客戶端。

bytes[] byteStream = JasperRunManager.runReportToPdf("myJasperReport.jasper",paramMap,databaseConn); 

OutputStream outStream = servletResponse.getOutputStream(); 
response.setHeader("Content-Disposition","inline, filename=myReport.pdf"); 
response.setContentType("application/pdf"); 
response.setContentLength(byteStream.length); 
outStream.write(bytes,0,bytes.length); 
3

一個完整的方法來從servlet做到這一點是:

public void myServletMethod(HttpServletRequest request, HttpServletResponse response) throws IOException{ 
      JasperReport jasperReport = null; 
      JasperDesign jasperDesign = null; 
      Map parameters = new HashMap(); 
      String path = getServletContext().getRealPath("/WEB-INF/"); 
      jasperDesign = JRXmlLoader.load(path+"/relative/path/to/MyReport.jrxml"); 
      jasperReport = JasperCompileManager.compileReport(jasperDesign); 
      byte[] byteStream = JasperRunManager.runReportToPdf(jasperReport, parameters, **new DataSourceOfYourPreference**);        
      OutputStream outStream = response.getOutputStream(); 
      response.setHeader("Content-Disposition","inline, filename=myReport.pdf"); 
      response.setContentType("application/pdf"); 
      response.setContentLength(byteStream.length); 
      outStream.write(byteStream,0,byteStream.length);  

    } 
+0

性能可以通過填充'.jasper'文件,而不是在編譯每個請求的報告得到改善。 – 2018-01-23 22:38:58