Friday, February 29, 2008

HowTo: JasperReports framework. Deployment to Tomcat

JasperReports framework does not ship report engine WAR file - you have to build it yourself.

Building JasperReports report engine WAR file

1. Download jasperreports-1.2.6-project.zip, unzip it to directory jasper.

2. Create Eclipse project: New->Project->General->Project. Location should point to jasper directory.

3. In the Eclipse Navigatior, select jasperreports-1.2.6\demo\samples\webapp\build.xml, open it, select war target, right-click->RunAs->Ant Build. The jasper-webapp.war file is built in jasperreports-1.2.6\demo\samples\webapp\ directory.

Deploying JasperReports report engine WAR file to Tomcat

1. Copy jasper-webapp.war file to tomcat\webapps directory. Start Tomcat, it will unzip the WAR file.

Deploying JasperReports report to Tomcat

For each report, you should have one file with .jasper extension (compiled report definition).
1. Copy the report file to jasper-webapp\reports directory.

2. Copy JDBC driver, required by your report, to jasper-webapp\WEB-INF\lib directory.

3. Modify jasper-webapp\jsp\html.jsp JSP file to load .jasper file, open database connection and render the report as HTML:


<%@ page errorPage="error.jsp" %>
<%@ page import="datasource.*" %>
<%@ page import="net.sf.jasperreports.engine.*" %>
<%@ page import="net.sf.jasperreports.engine.util.*" %>
<%@ page import="net.sf.jasperreports.engine.export.*" %>
<%@ page import="net.sf.jasperreports.j2ee.servlets.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>

<%
File reportFile = new File(application.getRealPath("/reports/MyReport.jasper"));
if (!reportFile.exists())
throw new JRRuntimeException("File WebappReport.jasper not found. The report design must be compiled first.");

JasperReport jasperReport = (JasperReport)JRLoader.loadObject(reportFile.getPath());

Map parameters = new HashMap();
parameters.put("ReportTitle", "Address Report");
parameters.put("BaseDir", reportFile.getParentFile());

Class.forName ("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection ("jdbc:mysql://XX.XX.XX.XX/world", "userId", "password");

JasperPrint jasperPrint =
JasperFillManager.fillReport(
jasperReport,
parameters,
connection
);

connection.close();

JRHtmlExporter exporter = new JRHtmlExporter();

exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "../servlets/image?image=");

exporter.exportReport();
%>
4. Restart Tomcat.

5. Invoke your report, using URL like: "http://localhost:8080/jasper-webapp/jsp/html.jsp".

No comments: