The most reliable and efficient way to execute a report through a web app (for this example I’ll be using servlets) is to have the report pre-compiled and ready. You can place ur SQL Qurrey inside the report itself or pass a java ResultSet object when creating a report.
First you need to convert your compiled .jasper file to a java object. Jasper API provides the class called JasperReport for this purpose. We also need to know the templateURL (The physical location of the jasper file on the server)
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperReport;
JasperReport jasperReport = (JasperReport) JRLoader.loadObject (templateURL);
Then Create the JasperPrint Object using the parameters and the resultset.
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRResultSetDataSource(resultSet));
resultSet = the SQL result set containing your data.
Parameters = the HashMap containing your parameters.
Then Load a ByteStream and “Flush” The report
OutputStream outputStream = servletResponse.getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
exporter.exportReport();
byteStream = baos.toByteArray();
outputStream.write(byteStream);
outputStream.flush();
outputStream.close();
You can call this code and flush the contents to a new window or put it in the same screen. For HTML Export you can use JRHtmlExporter instead of JRPdfExporter.