JasperReports: Calling report from servlet
19,001
Solution 1
You can prepare the Jasper file and stream it to the client.
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);
Solution 2
Here is a dummy report created within a Servlet file.
It is the same as it would be in normal Java class.
Just make sure you have the imports for your jasper report classes at the top of the file.
The bellow example builds a report from an XML datasource.
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();
}
}
}
Solution 3
A complete way to do this from the servlet would be:
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);
}
Related videos on Youtube
Author by
deven
Updated on June 04, 2022Comments
-
deven almost 2 years
I'm new to
JasperReports
and dont know how to call jasper file from servlet. My report contains the pie chart. -
Dave Jarvis over 6 yearsPerformance can be improved by filling the
.jasper
file instead of compiling the report at each request.