如何获取jasperreport文件(.JRXML)的确切位置以加载到系统? [英] How to get jasperreport file (.JRXML) exact location to load to the system?

查看:81
本文介绍了如何获取jasperreport文件(.JRXML)的确切位置以加载到系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图加载我创建的jasper报告(.jrxml),我将报告命名为"JREmp1.xml".但是我遇到了这个错误

I trying to load jasper report (.jrxml) that i created, i named the report "JREmp1.xml". but i got this error

"HTTP状态500-请求处理失败;嵌套异常为 net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: D:\ printpdf.metadata.plugins \ org.eclipse.wst.server.core \ tmp0 \ wtpwebapps \ JasperExample \ jasper \ JREmp1.jrxml (系统找不到指定的路径)"

"HTTP Status 500 - Request processing failed; nested exception is net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: D:\printpdf.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\JasperExample\jasper\JREmp1.jrxml (The system cannot find the path specified)"

如何获取确切位置?这是我的JREmp1.xml文件位置:

how to got the exact location? here is my JREmp1.xml file location :

这是我的控制器类中的代码:

and here is code in my controller class :

@RequestMapping(value = "/generateReport", method = RequestMethod.POST)
public String generateReport(
        @Valid @ModelAttribute("jasperInputForm") JasperInputForm jasperInputForm,
        BindingResult result, Model model, HttpServletRequest request,
        HttpServletResponse response) throws JRException, IOException,
        NamingException {

    if (result.hasErrors()) {
        System.out.println("validation error occured in jasper input form");
        return "loadJasper";

    }

    String reportFileName = "JREmp1";
    JasperReportDAO jrdao = new JasperReportDAO();

    Connection conn = null;

    try {
        conn = jrdao.getConnection();

        String rptFormat = jasperInputForm.getRptFmt();
        String noy = jasperInputForm.getNoofYears();

        System.out.println("rpt format " + rptFormat);
        System.out.println("no of years " + noy);

        HashMap<String, Object> hmParams = new HashMap<String, Object>();

        hmParams.put("noy", new Integer(noy));

        hmParams.put("Title", "Employees working more than " + noy
                + " Years");

        JasperReport jasperReport = jrdao.getCompiledFile(reportFileName,
                request);

        if (rptFormat.equalsIgnoreCase("html")) {
            JasperPrint jasperPrint = JasperFillManager.fillReport(
                    jasperReport, hmParams, conn);
            jrdao.generateReportHtml(jasperPrint, request, response); // For
            // HTML
            // report
        }
        else if (rptFormat.equalsIgnoreCase("pdf")) {
            jrdao.generateReportPDF(response, hmParams, jasperReport, conn); // For
            // PDF
            // report
        }
    } catch (SQLException sqlExp) {
        System.out.println("Exception::" + sqlExp.toString());
    } finally {
        if (conn != null) {
            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return null;
}

这是我的JasperReportDAO类中的代码:

public JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException {
    System.out.println("path " + request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
    File reportFile = new File( request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
    // If compiled file is not found, then compile XML template
    if (!reportFile.exists()) {
        JasperCompileManager.compileReportToFile(request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jrxml"),request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
    }
    JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
    return jasperReport;
}


public void generateReportHtml( JasperPrint jasperPrint, HttpServletRequest req, HttpServletResponse resp) throws IOException, JRException {
    HtmlExporter exporter=new HtmlExporter();
    List<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
    jasperPrintList.add(jasperPrint);
    exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
    exporter.setExporterOutput( new SimpleHtmlExporterOutput(resp.getWriter()));
    SimpleHtmlReportConfiguration configuration =new SimpleHtmlReportConfiguration();
    exporter.setConfiguration(configuration);
    exporter.exportReport();

}


public void generateReportPDF (HttpServletResponse resp, Map parameters, JasperReport jasperReport, Connection conn)throws JRException, NamingException, SQLException, IOException {
    byte[] bytes = null;
    bytes = JasperRunManager.runReportToPdf(jasperReport,parameters,conn);
    resp.reset();
    resp.resetBuffer();
    resp.setContentType("application/pdf");
    resp.setContentLength(bytes.length);
    ServletOutputStream ouputStream = resp.getOutputStream();
    ouputStream.write(bytes, 0, bytes.length);
    ouputStream.flush();
    ouputStream.close();
}

这是我的JasperInputForm课:

public class JasperInputForm {

    @NotEmpty
    private String noofYears;
    private String rptFmt="Html";

    public String getRptFmt() {
        return rptFmt;
    }

    public void setRptFmt(String rptFmt) {
        this.rptFmt = rptFmt;
    }

    public String getNoofYears() {
        return noofYears;
    }

    public void setNoofYears(String noofYears) {
        this.noofYears = noofYears;
    }

}

如何正确获取我的JREmp1.jrxml文件位置?我为Spring MVC应用程序开发了此报告

how to get my JREmp1.jrxml file location properly? I develop this report for Spring MVC application

更新: 这是我用@Wilson答案更新后的完整功能代码(我使用@Wilson说的第二个选项): 此功能位于JasperReportDAO内:

UPDATE : Here is my complete function code after i update with @Wilson answer (i go with second option that @Wilson said) : this function is inside JasperReportDAO :

public JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException, MalformedURLException, URISyntaxException {
    System.out.println("path " + request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
    //File reportFile = new File( request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
    URL resourceUrl = request.getSession().getServletContext().getResource("/WEB-INF/jasper/" + fileName + ".jrxml");
    File reportFile = new File(resourceUrl.toURI());

    // If compiled file is not found, then compile XML template
    if (!reportFile.exists()) {
               JasperCompileManager.compileReportToFile(request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jrxml"),request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
        }
        JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
       return jasperReport;
}

我收到此错误

"HTTP状态500-请求处理失败;嵌套异常为 java.lang.IllegalArgumentException:URI方案不是文件""

"HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: URI scheme is not "file""

如何解决这个问题?

推荐答案

使用ServeltContext读取文件有多种方法:

There is a number of way to do to read file with ServeltContext:

1. 使用ServletContext#getRealPath

String fullPath = request.getSession().getServletContext().getRealPath("/WEB-INF/jasper/" + fileName + ".jrxml");

这将为您提供所需资源的完整系统路径.但是,如果容器不展开WAR文件,它将无法正常工作.

This will get you the full system path to the resource you are looking for. However, it will not work if the container do not expand the WAR file.

2. 使用ServletContext#getResource

URL resourceUrl = request.getSession().getServletContext().getResource("/WEB-INF/jasper/" + fileName + ".jrxml");
File file = new File(resourceUrl.toURI());

无论您使用哪个容器以及应用程序的安装位置,都将返回URL.

This will return the URL no matter what container you use and where the application is installed.

3. 用户ServletContext#getResourceAsStream

InputStream resourceStream = request.getSession().getServletContext().getResourceAsStream("/WEB-INF/jasper/" + fileName + ".jrxml");

这是ServletContext#getResource的替代方法,用于获取inputSteam

This is an alternative of ServletContext#getResource to get an inputSteam

更新:

ServletContext#getResource返回的URL可能不是文件URL,可能会引起问题.请尝试将ServletContext#getResourceAsStreamJasperCompileManager#compileReportToFile:

The URL return from ServletContext#getResource may not be a file URL and it may cause issue. Please try ServletContext#getResourceAsStream with JasperCompileManager#compileReportToFile:

JasperDesign jasperDesign = JRXmlLoader.load(resourceStream);
JasperCompileManager.compileReportToFile(jasperDesign, jasperFilePath);

我发现您正在尝试将jasper报告文件写入程序分发中,这应该避免.首选方法是预编译报告,然后将其放入WAR文件中,或者将已编译的jasper报告放入一个临时目录中.

I found that your are trying to write jasper report file into your program distribution which should be avoid. The preferred way is to pre-compile your report and put into your WAR file or put the compiled jasper report into a temporary directory.

以下为完整代码示例:

public JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException, IOException {
    // Create temporary folder to store jasper report as you should not write a resource into your program
    // distribution
    String tempFolderPath = System.getProperty("java.io.tmpdir") + File.separator + "jasperReport";
    File tempFolder = new File(tempFolderPath);
    if (!tempFolder.exists()) {
        tempFolder.mkdirs();
    }
    String jasperFilePath = tempFolderPath + File.separator + fileName + ".jasper";
    File reportFile = new File(jasperFilePath);
    // If compiled file is not found, then compile XML template
    if (!reportFile.exists()) {
        InputStream jRXmlStream = request.getSession().getServletContext().getResourceAsStream
                ("/WEB-INF/jasper/" + fileName + ".jrxml");
        JasperDesign jasperDesign = JRXmlLoader.load(jRXmlStream);
        JasperCompileManager.compileReportToFile(jasperDesign, jasperFilePath);
    }
    JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
    return jasperReport;
}

这篇关于如何获取jasperreport文件(.JRXML)的确切位置以加载到系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆