這里的是定方法主要參照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了。
