Random Random - 3 months ago 76x
Java Question

Using JasperReports with a relative path

I have a web app and the client has requested to see some reports. The approach has been to use iReport and show them the report on screen.

I have already asked something like this. But today I have discovered that the paths to the report files (jrxml) are absolute. So I have to change the program so it accepts relative paths. I have been trying to do this, but it seems that neither the jrxml or the compiled (.jasper) files accepts relative paths to neither compile or to fill the report.

This is what I have got this far:

//path is generated as request.getContextPath() + "/jrxmlFiles/"
public void generateReport(HttpServletResponse res, ConexionAdmin con, String path) throws Exception{

ServletOutputStream out = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();

JasperDesign jasperDesign = JRXmlLoader.load(path);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

byte[] bytes = JasperRunManager.runReportToPdf(jasperReport, pars, con.initConexion());
out = res.getOutputStream();
out.write(bytes, 0, bytes.length);

res.setHeader("Cache-Control", "cache");
res.setHeader("Content-Disposition", "attachment; filename=report.pdf");
res.setHeader("Pragma", "cache");


This seems to work with absolute paths, but throws me:

Exception Message
net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException

when changed to a relative path. I have searched the net with no success in how to change to my fits.

I have the javaDoc for the jasper API, but I rather not read it through if I can help it.

  1. Paths must be absolute.
  2. Only compile .jrxml files to .jasper files if the .jrxml is being modified. Usually you can just load the .jasper file and skip compilation altogether. It is much faster.
  3. Store .jasper and .jrxml files outside of your web root.
  4. Create the following variables throughout all your reports:
       ROOT_DIR = "/full/path/to/reports/"
       IMAGE_DIR = $P{ROOT_DIR} + "images/"
       STYLES_DIR = $P{ROOT_DIR} + "styles/"
       SUBREPORT_DIR = $P{ROOT_DIR} + "subreports/"
       COMMON_DIR = $P{ROOT_DIR} + "common/"
  5. Reference items relative to $P{ROOT_DIR} (e.g., $P{IMAGE_DIR} is defined in terms of $P{ROOT_DIR}).
  6. Pass the value of $P{ROOT_DIR} in from your environment.
  7. Do not tightly couple your application to:
    • JasperReports
    • Servlets