1

我正在通过预先设计的 Jrxml 文件从我的 Java Web 应用程序创建 Jasper 报告。该文件位于名为 jrxml 的目录中的我的 web 文件夹 (Netbeans) 中,因此我正在尝试使用此方法来获取它。

public void generateChurchReport(IncomeExpenseBean ieb) {
        church = ieb.getChurch();
        user = ieb.getUser();
        String currdate = dt.getCurrentDate();
        Connection conn = db.getDbConnection();
        Map parameters = new HashMap();
        try{ 
        parameters.put("ChurchName", church);
        JasperReport jasperReport = JasperCompileManager.compileReport("/jrxml/ChurchIncome_expenseReport.jrxml");
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
        File f = new File(user + church+ currdate +  ".pdf");
        JasperExportManager.exportReportToPdfFile(jasperPrint, f.getAbsolutePath());
        Desktop.getDesktop().open(new File(f.getAbsolutePath())); 
        }catch(Exception asd){
            System.out.println(asd.getMessage());
        }

    }

我收到文件未找到异常,因为应用程序期望该文件位于 ;

  C:\Program Files\glassfish-3.1.2.2\glassfish\domains\TestDom\jrxml\

如何在我的 web 文件夹中读取此文件以及如何在同一文件夹中创建报告?

编辑如果我不提供任何路径,如果 jrxml 文件位于该位置,我的报告将在 C:\Program Files\glassfish-3.1.2.2\glassfish\domains\TestDom\ 生成。

4

1 回答 1

6

What you are doing wrong here is, you are trying to locate your jrxml file somewhere in web folder from your java class. This will definitely raise "File Not found error" at run time because of incorrect context path. You could simply do the following:-

  1. Make a folder named say "Jrxml" under your java classes package. Suppose java classes package is com.ejb.beans, make a folder com.ejb.beans.jrxml.
  2. Put all your jrxml files into this folder.
  3. In your java class, load the class loader and locate the jrxml by its name and you will easily access it. Here is the code:-

    ClassLoader classLoader = getClass().getClassLoader();

    InputStream url = null;

    url = classLoader.getResourceAsStream("Report.jrxml");

    This url can be used to compile report as :-

    JasperReport jasperReport = JasperCompileManager.compileReport(url);

To create the report output file, you could store it at some path in your application server. Set your server path in environment variable and extract it in your class at runtime like this :-

String serverHomeDir = System.getProperty("server.home.dir");

String reportDestination = serverHomeDir + "/domains/ReportOutput/report.html";

// now print report at reportDestination
JasperExportManager.exportReportToHtmlFile(jasperPrint, reportDestination);

Your html file will be generated at the required destination, which you can easily read and render it, the way you want to, through your web page.

于 2013-08-12T09:13:20.317 回答