日期:2014-05-17 浏览次数:20871 次
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.sf.jasperreports.engine.JasperCompileManager; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class ReportsAction extends ActionSupport { private static final long serialVersionUID = 1L; //数据源 private List<Object> list; //jasperreports接收的参数 private Map<String, Object> params = new HashMap<String, Object>(); public String execute() throws Exception { //伪代码 list = getXXService().query...;//调用service方法 params.put("key1", value1); params.put("key2", value2); try { //读取jasper模板 String reportSource = ServletActionContext.getServletContext().getRealPath("/jasper/report_template.xml"); File parent = new File(reportSource).getParentFile(); //将模板编译成jasper文件(实际项目中,jasper由ireport编译好后放入项目中,以节省编译过程所消耗的时间) JasperCompileManager.compileReportToFile(reportSource, new File(parent, "compiled_report.jasper").getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); return ERROR; } return SUCCESS; } public List<Object> getList() { return list; } public Map<String, Object> getParams() { return params; } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <!-- Configuration for the default package. --> <struts> <package name="default" extends="struts-default,jasperreports-default"> <!-- 输出不同格式的报表 --> <action name="PDF" class="com.actions.ReportsAction"> <result name="success" type="jasper"> <!-- 指定jasper文件位置 --> <param name="location">/jasper/compiled_report.jasper</param> <!-- 数据源,名称必须和Java代码中名称一致 --> <param name="dataSource">list</param> <!-- 参数,名称也必须与Java代码中名称一致 --> <param name="reportParameters">params</param> <!-- 输出格式 --> <param name="format">PDF</param> </result> </action> <action name="HTML" class="com.actions.ReportsAction"> <result name="success" type="jasper"> <param name="location">/jasper/compiled_report.jasper</param> <param name="dataSource">list</param> <param name="reportParameters">params</param> <param name="format">HTML</param> </result> </action> <action name="XML" class="com.actions.ReportsAction"> <result name="success" type="jasper"> <param name="location">/jasper/compiled_report.jasper</param> <param name="dataSource">list</param> <param name="reportParameters">params</param> <param na