这是我用来从 servlet 填充 jasper 报告的一些代码。它有点定制,但应该可以帮助你。
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
HttpSession httpSession = req.getSession();
String errorMessage = null;
String forwardTo = null;
String reportName = req.getParameter("reportName");
String cameFrom = req.getParameter("cameFrom");
if (StringUtils.isEmpty(reportName)) { // direct to report menu
String type = req.getParameter("type");
forwardTo = "/WEB-INF/jsp/reports.jsp?cameFrom=" + cameFrom + ((StringUtils.isEmpty(type)) ? "" : "&type=" + type);
} else { // direct to specific report
forwardTo = "/WEB-INF/jsp/jasperreport.jsp?cameFrom=" + cameFrom;
JasperPrint jasperPrint = null;
Connection conn = null;
int page = -1;
try {
page = new Integer(StringUtils.defaultIfEmpty(req.getParameter("page"), "-1"));
} catch (NumberFormatException ignore) {}
boolean isFirstTime = (page == -1);
boolean isCSV = (page == -99);
String reportTitle = req.getParameter("reportTitle");
String jasperPath = (String)httpSession.getServletContext().getAttribute("jasperpath");
String reportPath = jasperPath + "/" + reportName + ".jasper";
File reportFile = new File(reportPath);
if (reportFile == null || !reportFile.exists())
throw new IOException("File " + reportPath + " not found. The report design must be compiled first.");
try {
if (isFirstTime) { // Clear any leftover report session attributes.
httpSession.removeAttribute("jasperPrint");
httpSession.removeAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE);
httpSession.removeAttribute("reportTitle");
httpSession.removeAttribute("reportName");
httpSession.removeAttribute("jasperError");
Integer nParms = (Integer) httpSession.getAttribute("nParms");
if (nParms == null) nParms = 0;
httpSession.removeAttribute("nParms");
for (int ixParm = 1; ixParm < nParms + 1; ++ixParm) {
httpSession.removeAttribute("parmName_" + ixParm);
httpSession.removeAttribute("parmValue_" + ixParm);
}
}
httpSession.setAttribute("reportName", reportName);
if (isFirstTime || isCSV) {
JasperReport jasperReport = (JasperReport)JRLoader.loadObject(reportPath);
conn = ReportServiceImpl.getDBConnectionForReports();
@SuppressWarnings("rawtypes")
Map<String, Comparable> parameters = new HashMap<String, Comparable>();
parameters.put("SUBREPORT_DIR", String.valueOf(reportFile.getParentFile()) + java.io.File.separator);
parameters.put("ReportTitle", reportTitle);
parameters.put("BaseDir", reportFile.getParentFile());
// Get report-specific parameters (if any).
int nParms = 0;
try {
if (isFirstTime) {
nParms = new Integer(StringUtils.defaultIfEmpty(req.getParameter("nParms"), "0"));
httpSession.setAttribute("nParms", nParms);
} else nParms = (Integer)httpSession.getAttribute("nParms");
} catch (NumberFormatException ignore) {}
for (int ixParm = 1; ixParm < nParms + 1; ++ixParm) {
String _parmName = null;
String _parmValue = null;
if (isFirstTime) { // get parms from request and place in session
_parmName = req.getParameter("parmName_" + ixParm);
_parmValue = req.getParameter("parmValue_" + ixParm);
httpSession.setAttribute("parmName_" + ixParm, _parmName);
httpSession.setAttribute("parmValue_" + ixParm, _parmValue);
} else { // get parms from session
_parmName = (String) httpSession.getAttribute("parmName_" + ixParm);
_parmValue = (String) httpSession.getAttribute("parmValue_" + ixParm);
}
if (!StringUtils.isEmpty(_parmName)) { // if date range not specified, use defaults
if (_parmName.equals("START_TIME_MS") || _parmName.equals("END_TIME_MS")) {
BigDecimal dateMillis = new BigDecimal(0l);
if (_parmValue.length() == 0) {
if (_parmName.equals("START_TIME_MS")) dateMillis = new BigDecimal(0l);
else dateMillis = new BigDecimal(System.currentTimeMillis());
} else {
if (_parmValue.contains("/"))
dateMillis = new BigDecimal(ReportServiceImpl.getDateInMillis(_parmValue));
else dateMillis = new BigDecimal(_parmValue);
}
parameters.put(_parmName, dateMillis);
} else parameters.put(_parmName, _parmValue);
}
}
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
httpSession.setAttribute("reportTitle", reportTitle);
httpSession.setAttribute((isCSV) ? "jasperPrintCSV" : "jasperPrint", jasperPrint);
if (isFirstTime)
httpSession.setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
}
} catch (LoadingException le) {
le.printStackTrace();
errorMessage = "Problem reading db connection properties.";
} catch (SQLException e) {
e.printStackTrace();
errorMessage = "Problem opening db connection.";
} catch (JRException jre) {
jre.printStackTrace();
errorMessage = "Jasper problem loading/filling report: " + reportPath;
} catch (DatabaseException de) {
de.printStackTrace();
errorMessage = "Problem retrieving hibernate session.";
} catch (HibernateException he) {
he.printStackTrace();
errorMessage = "Problem getting hibernate transaction or database connection.";
} catch (IllegalArgumentException iae) {
errorMessage = "No data found for report: \"" + reportTitle + "\"";
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (conn != null) ReportServiceImpl.closeDBConnectionForReports();
} catch (Exception ignore) {}
}
}
if (!StringUtils.isEmpty(errorMessage))
httpSession.setAttribute("jasperError", errorMessage);
getServletConfig().getServletContext().getRequestDispatcher(forwardTo).forward(req, res);
}
这是一个与 servlet 交互以创建显示和 CSV 报告的 jsp。对不起,如果你是一个脚本纯粹主义者,但我最初是从其他地方得到这个代码的,它有点毛茸茸。我敢肯定,如果需要,您可以在不使用 scriptlet 的情况下弄清楚如何完成所有工作。
<%@page import="java.util.HashMap"%><%@
page import="java.io.FileInputStream"%><%@
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.sql.Connection" %><%@
page import="org.hibernate.Session" %><%@
page import="org.hibernate.Transaction" %><%@
page import="com.pa.rollupedit.common.connection.HibernateSessionFactory" %><%@
page import="com.pa.rollupedit.loader.utility.Util"%><%@
page import="org.apache.commons.lang.StringUtils"%><%
String reportTitle = StringUtils.defaultIfEmpty((String)session.getAttribute("reportTitle"), "");
String reportName = StringUtils.defaultIfEmpty((String)session.getAttribute("reportName"), "");
boolean isCSV = reportName.contains("CSV");
JasperPrint jasperPrint = (JasperPrint)session.getAttribute("jasperPrint");
JasperPrint jasperPrintCSV = (JasperPrint)session.getAttribute("jasperPrintCSV");
String errorMessage = (String)session.getAttribute("jasperError");
boolean top = new Boolean(StringUtils.defaultIfEmpty(request.getParameter("top"), "false"));
boolean hasCSV = new Boolean(StringUtils.defaultIfEmpty(request.getParameter("hasCSV"), "false"));
String cameFrom = StringUtils.defaultIfEmpty(request.getParameter("cameFrom"), "admin");
String type = StringUtils.defaultIfEmpty(request.getParameter("type"), "editing");
int pageIndex = 0;
int lastPageIndex = 0;
StringBuffer sbuffer = new StringBuffer();
if (StringUtils.isEmpty(errorMessage)) {
if (isCSV) {
try {
OutputStream os = response.getOutputStream();
JRCsvExporter exporter = new JRCsvExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrintCSV);
exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, sbuffer);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "image?image=");
exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(pageIndex));
exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, "");
exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");
exporter.exportReport();
byte[] csvBytes = sbuffer.toString().getBytes();
InputStream is = new ByteArrayInputStream(csvBytes);
response.setContentType("text/comma-separated-values");
response.setHeader("Content-Disposition",
"attachment;filename=\"" + reportName + ".csv\"");
byte[] fileBytes = new byte[10240000];
int bytesRead = is.read(fileBytes, 0, 10240000);
while (bytesRead >= 0) {
os.write(fileBytes, 0, bytesRead);
bytesRead = is.read(fileBytes, 0, 10240000);
}
is.close();
os.flush();
os.close();
out.clearBuffer();
return;
} catch (Exception e) {
e.printStackTrace();
errorMessage = "Problem generating CSV download file: " + e.getMessage();
}
} else {
JRHtmlExporter exporter = new JRHtmlExporter();
if (jasperPrint.getPages() != null)
lastPageIndex = jasperPrint.getPages().size() - 1;
try {
pageIndex = new Integer(StringUtils.defaultIfEmpty(request.getParameter("page"), "0"));
} catch (NumberFormatException ignore) {}
if (pageIndex < 0) pageIndex = 0;
if (pageIndex > lastPageIndex) pageIndex = lastPageIndex;
if (pageIndex < 0) errorMessage = "Report has no data.";
else {
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, sbuffer);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "image?image=");
exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(pageIndex));
exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, "");
exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");
exporter.exportReport();
}
}
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="css/pearson.css" type="text/css" rel="stylesheet" />
<link href="css/portlet-specifics.css" type="text/css" rel="stylesheet" />
<link href="css/fancy.css" type="text/css" rel="stylesheet" />
<title><%=reportTitle%></title>
<script type="text/javascript" src="js/commonJS.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<script>window.history.forward(1);</script>
<script type="text/javascript">
function back() {
var myForm = document.getElementById("myform");
myForm.action = "ReportController?type=<%=type%>&cameFrom=<%=cameFrom%>";
myForm.submit();
}
function downloadCSV() {
//document.getElementById("twirliecsv").style.visibility = "visible";
var url = "ReportController?reportName=<%=reportName%>CSV&reportTitle=<%=reportTitle%>&top=<%=top%>&hasCSV=<%=hasCSV%>&page=-99";
var w = window.open(url, "_blank",
"height=700, width=1000, left=50, top=100, toolbar=0, titlebar=1, scrollbars=1, resizable=1, menubar=0, location=0, directories=0, status=0, modal=1, alwaysRaised=1");
}
</script>
</head>
<body text="#000000" link="#000000" alink="#000000" vlink="#000000">
<%if (StringUtils.isEmpty(errorMessage)) {%>
<form id="myform" action="ReportController">
<input type="hidden" id="type" name="type" value="<%=type%>"/>
<input type="hidden" id="cameFrom" name="cameFrom" value="<%=cameFrom%>"/>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="50%"> </td>
<td align="left">
<hr size="1" color="#000000">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<%if (top) {%>
<td><input onclick="back();" type="button" class="admin-button" value="Back"/></td>
<%} else {%>
<td><input onclick="window.top.close();" type="button" class="admin-button" value="Close"/></td>
<%}
if (hasCSV) {%>
<td><input onclick="downloadCSV();" type="button" class="admin-button" value="CSV"/></td>
<%}%>
<td> </td>
<%if (!isCSV) {
if (pageIndex > 0) {%>
<td><a href="ReportController?reportName=<%=reportName%>&reportTitle=<%=reportTitle%>&top=<%=top%>&hasCSV=<%=hasCSV%>&page=0"><img src="images/first.GIF" border="0"></a></td>
<td><a href="ReportController?reportName=<%=reportName%>&reportTitle=<%=reportTitle%>&top=<%=top%>&hasCSV=<%=hasCSV%>&page=<%=pageIndex - 1%>"><img src="images/previous.GIF" border="0"></a></td>
<%} else {%>
<td><img src="images/first_grey.GIF" border="0"></td>
<td><img src="images/previous_grey.GIF" border="0"></td>
<%}
if (pageIndex < lastPageIndex) {%>
<td><a href="ReportController?reportName=<%=reportName%>&reportTitle=<%=reportTitle%>&top=<%=top%>&hasCSV=<%=hasCSV%>&page=<%=pageIndex + 1%>"><img src="images/next.GIF" border="0"></a></td>
<td><a href="ReportController?reportName=<%=reportName%>&reportTitle=<%=reportTitle%>&top=<%=top%>&hasCSV=<%=hasCSV%>&page=<%=lastPageIndex%>"><img src="images/last.GIF" border="0"></a></td>
<%} else {%>
<td><img src="images/next_grey.GIF" border="0"></td>
<td><img src="images/last_grey.GIF" border="0"></td>
<%}
}%>
<td width="100%"> </td>
</tr>
</table>
<hr size="1" color="#000000">
</td>
<td width="50%"> </td>
</tr>
<tr>
<td width="50%"> </td>
<td align="center">
<%=sbuffer.toString()%>
</td>
</tr>
</table>
</form>
<%} else {%>
<form action="ReportController">
<input type="hidden" id="cameFrom" name="cameFrom" value="<%=cameFrom%>"/>
<div style="margin: 20px 20px;">
<%if (top) {%>
<a href="ReportController"><input type="submit" class="admin-button" value="Back"/></a>
<%} else {%>
<input onclick="window.top.close();" type="button" class="admin-button" value="Close"/>
<%}%>
</div>
</form>
<div style="color: red; margin: 20px 20px; font: bold 16px/18px Arial, sans-serif;"><%=errorMessage%></div>
<%}%>
</body>
</html>