这里的是定方法主要参照sturts2-jasperreport-plugin的完成方法(其实就是抄的)
PDF的样子是这样的两页的pdf

然后action的配置是这样的(不要在意格式)
@ParentPackage("HulftPackage")
@Namespace("/")
@Action(value = "testreport",
results = {
@Result(name = "success", type = "jasper", params={
"location","/WEB-INF/report/report5.jasper",
"format", "PDF",
"dataSource","mySource",
"reportKey","myfirstreport",
"exportParameters","param",
})
}
)
public class TestReportAction extends ActionSupport {
private Connection conn = null;
@Override
public String execute() throws Exception {
conn = getConnection();
mySource = new ArrayList<ReportData>();
ReportData data = new ReportData();
data.setId("001");
data.setName("陈");
data.setClassName("一班");
List<ReportChild> clist = new ArrayList<ReportChild>();
ReportChild child = new ReportChild();
child.setCourseName("合格");
child.setDegree(33);
clist.add(child);
child = new ReportChild();
child.setCourseName("不合格");
child.setDegree(67);
clist.add(child);
data.setChild(clist);
mySource.add(data);
data = new ReportData();
data.setId("002");
data.setName("拉拉");
data.setClassName("二班");
clist = new ArrayList<ReportChild>();
child = new ReportChild();
child.setCourseName("合格");
child.setDegree(11);
clist.add(child);
child = new ReportChild();
child.setCourseName("不合格");
child.setDegree(89);
clist.add(child);
data.setChild(clist);
mySource.add(data);
return SUCCESS;
}
public Map param;
public Map getParam()
{
HashMap a = new HashMap();
a.put("testmyp", "sadfdsafdsaf");
return a;
}
private List<ReportData> mySource;
public List<ReportData> getMySource()
{
return mySource;
}
public Connection getConn() {
return conn;
}
private static Connection getConnection()throws
ClassNotFoundException,SQLException{
String driver="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@172.16.173.106:1521:TESTSTRUTS";
String user="test";
String password="test";
Class.forName(driver);
Connection conn=DriverManager
.getConnection(url,user,password);
return conn;
}
}
@Result(name = "success", type = "jasper", params={ "location","/WEB-INF/report/report5.jasper", "format", "PDF", "dataSource","mySource", "reportKey","myfirstreport", "exportParameters","param",
主要代码段是这个result type 是jasper
location 是编译后的jasper文件。入手途径1ireport编译后自动获得,2自己写一个compile获得(sturts2-jasperreport-plugin程序里有)
format 是输出格式 PDF HTML DOC EXCEL
dataSource 是数据源 也就是一个返回值是list的get属性
reportKey 是用来做HTML图片时做sessionkey用的
exportParameters 是报表report的param内容 也就是一个返回值是Map的get属性
然后是STRUTS.xml的配置 定义了jasper类型
<package name="HulftPackage" extends="struts-default"> <result-types> <result-type name="jasper" class="com.hulftchina.result.JasperReportsResult"/> </result-types> </package>
JasperReportsResult类就是struts plug抄过来的就是调用的地方重写了一下
因为jasper升级以后调用方式改变了所以这里重新写了一下,包括 数据库连接 自定义javabean和param的输入方式
@Override protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { initializeProperties(invocation); if (logger.isDebugEnabled()) { logger.debug("Begin execute jasper report."); } Map parameters= null; HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(ServletActionContext.HTTP_RESPONSE); // 设置http头 // 本地缓存1分钟 response.setHeader("CACHE-CONTROL", "PRIVATE"); response.setHeader("Cache-Control", "maxage=60"); response.setHeader("Pragma", "public"); // 完全接受后显示 response.setHeader("Accept-Ranges", "none"); // 文字设定 response.setCharacterEncoding("UTF-8"); // action内设定的连接取得 ValueStack stack = invocation.getStack(); Connection conn = (Connection) stack.findValue(connection); if (exportParameters != null) { parameters = (Map) stack.findValue(exportParameters); if (parameters != null) { if (logger.isDebugEnabled()) { logger.debug("Found export parameters; adding to exporter parameters..."); } } } //取得服务器绝对路径 ServletContext servletContext = (ServletContext) invocation.getInvocationContext().get(ServletActionContext.SERVLET_CONTEXT); String systemId = servletContext.getRealPath(finalLocation); JasperPrint jasperPrint; try { JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(systemId); ValueStackDataSource stackDataSource = null; // 数据库连接存在的时候 if (conn != null) { jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn); } else if (dataSource != null) { stackDataSource = new ValueStackDataSource(stack, dataSource, wrapField); jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, stackDataSource); } else { jasperPrint = JasperFillManager.fillReport(jasperReport, parameters); } } catch (JRException e) { logger.error("Error building report for uri " + systemId, e); throw new ServletException(e.getMessage(), e); } try { JRAbstractExporter exporter = null; ExporterConfiguration configuration = null; if (format.equals(FORMAT_PDF)) { response.setContentType("application/pdf"); exporter = new JRPdfExporter(); configuration = new SimplePdfExporterConfiguration(); } else if (format.equals(FORMAT_HTML)) { String sessionKey = null; response.addHeader("Content-Type", "text/html"); exporter = new HtmlExporter(); configuration = new SimpleHtmlExporterConfiguration(); sessionKey = ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE; if (!StringUtils.isEmpty(reportKey)) { sessionKey = ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE + reportKey; } request.getSession().setAttribute(sessionKey, jasperPrint); SimpleHtmlExporterOutput output = new SimpleHtmlExporterOutput(response.getOutputStream()); // img图片取得serverlet设定 output.setImageHandler( new WebHtmlResourceHandler("reportimage?image={0}" + (StringUtils.isEmpty(reportKey) ? "" : "&" + ImageServlet.JASPER_PRINT_REQUEST_PARAMETER + "=" + sessionKey))); exporter.setExporterOutput(output); } else if (format.equals(FORMAT_DOC)) { response.addHeader("Content-Type", "application/msword"); exporter = new JRDocxExporter(); configuration = new SimpleDocxExporterConfiguration(); } else if (format.equals(FORMAT_XLS)) { response.setContentType("application/vnd.ms-excel"); exporter = new JRXlsExporter(); configuration = new SimpleXlsExporterConfiguration(); } else { throw new ServletException("Unknown report format: " + format); } // 输入编译后的jasper的打印类 exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); if (!format.equals(FORMAT_HTML)) { exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream())); } exporter.setConfiguration(configuration); exporter.exportReport(); } catch (JRException e) { String message = "Error producing " + format + " report for uri " + systemId; logger.error(message, e); throw new ServletException(e.getMessage(), e); } catch (Exception e) { String message = "Error producing " + format + " report for uri " + systemId; logger.error(message, e); throw new ServletException(e.getMessage(), e); } }
如果输出为html的话还需要在web.xml中加入 img取得的servlet这个是和上边代码中的("reportimage?image={0}"相呼应的
<!-- 报表html版的图片取得 -->
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>net.sf.jasperreports.j2ee.servlets.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/reportimage</url-pattern>
</servlet-mapping>
这样基本的web版报表输出就ok了。