Java Reference
In-Depth Information
response.setContentType("application/pdf");
servletOutputStream.flush();
servletOutputStream.close();
}
catch (JRException e)
{
// display stack trace in the browser
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
response.setContentType("text/plain");
response.getOutputStream().print(stringWriter.toString());
}
}
}
Since web browsers are incapable of displaying reports in JasperReports' native
format (at least without the help of an applet), we must export the report to a format
that the browser can understand. JasperReports allows us to export reports to PDF
and many other formats. Since the PDF format is widely used, we chose to export to
this format in this example.
The servlet in the above example calls the static
JasperRunManager.
runReportToPdfStream()
method. The signature for this method is:
runReportToPdfStream(java.io.InputStream
inputStream
,
java.io.OutputStream
outputStream
,
java.util.Map
parameters
,
JRDataSource
dataSource)
To display the report on the browser, we need to pass the binary report template,
or Jasper
file, in the form of a stream, as the first argument of this method.
We can accomplish this by calling the
javax.servlet.ServletContext.
getResourceAsStream()
method, passing a
String
containing the location
of the Jasper file as a parameter. This method will return an instance of
java.
io.InputStream
that we can use as the first argument for the
JasperRunManager.
runReportToPDFStream()
method.
The
JasperRunManager.runReportToPDFStream()
method needs an instance of
java.io.OutputStream()
to write the compiled report. We can simply use the
default output stream for the servlet, which can be obtained by calling the
javax.
servlet.http.HttpServletResponse.getOutputStream()
method.