分享

Springmvc与jasperreport结合生成报表的一种方法

 recruits 2014-05-21

项目原因需要在springmvc的基础上整合jasperreports生成报表。其实springmvc已经提供了对jasperreports的支持,感觉springmvc采用的一个比较好的方式是将报表的生成作为一个view处理,但是需要对每一种报表配置他的jasperreports模板及视图的映射,这样的话添加报表必须变更配置,比较麻烦,所以自己想了一个方法来避免这种配置,代码可以很容易和spring整合起来。

 japserreports生成报表基本流程其实就是根据一个模板和数据源生成一个中间类型,然后可以在此基础上可以导出几种格式。我的想法是提供方法供springmvc的controller调用产生中间文件,然后在view里面向客户端导出请求的格式。

首先是ReportPrint类,很简单,只是包含一个JasperPrint对象(既上述的中间文件),代码很简单,不解释

01public class ReportPrint {
02    JasperPrint jasperPrint = null;
03 
04    public JasperPrint getJasperPrint() {
05        return jasperPrint;
06    }
07 
08    public void setJasperPrint(JasperPrint jasperPrint) {
09        this.jasperPrint = jasperPrint;
10    }
11     
12}
接下来就是ReportCreater类,该类可通过spring注入到其他类中,调用它的createReport方法

01public class ReportCreater {
02    private static final Log logger = LogFactory.getLog(ReportCreater.class);
03    private String jasperReportPath = null;//报表的模板文件存放路径(相对classpath,通过spring注入)
04    /**
05     * jasperDesignMap作为一个缓存来存储编译后的JasperReport模板
06     */
07    private Map<String, JasperReport> jasperDesignMap = new ConcurrentHashMap<String, JasperReport>();
08     
09    public void resetJasperDesignCache() {
10        jasperDesignMap.clear();
11    }
12     
13    /**
14     * controller调用该方法来产生ReportPrint对象
15     */
16    public ReportPrint createReport(final String reportKey, final ResultSet rs, Map<String, ?> reportParams) throws ReportException {
17        try {
18            return _createReport(reportKey, rs, reportParams);
19        } catch (JRException e) {
20            logger.error(null, e);
21            throw new ReportException("产生报表出错" + reportKey);
22        }
23    }
24     
25    private ReportPrint _createReport(final String reportKey, final ResultSet rs, Map<String, ?> reportParams) throws ReportException, JRException {
26        JasperReport jasperReport = getJasperReport(reportKey);    
27        ReportPrint reportPrint = new ReportPrint();
28        JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(rs);
29        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, reportParams, resultSetDataSource);
30        reportPrint.setJasperPrint(jasperPrint);
31         
32        return reportPrint;
33    }
34     
35    private JasperReport getJasperReport(final String reportKey) {
36        try {
37            return _getJasperReport(reportKey);
38        } catch (IOException e) {
39            logger.error(null, e);
40            throw new ReportException("关闭文件流异常:" + reportKey);
41        } catch (JRException e) {
42            logger.error(null, e);
43            throw new ReportException("产生报表异常:" + reportKey);
44        }
45    }
46     
47    private JasperReport _getJasperReport(final String reportKey) throws IOException, JRException {
48        JasperReport jasperReport = null;
49        if (jasperDesignMap.containsKey(reportKey)) {
50            jasperReport = jasperDesignMap.get(reportKey);
51        } else {
52            jasperReport = getJasperReportFromFile(final String reportKey);
53            jasperDesignMap.put(reportKey, jasperReport);
54        }
55         
56        return jasperReport;
57    }
58     
59    /**
60     * 从模板文件编译获得模板对象
61     */
62    private JasperReport getJasperReportFromFile(final String reportKey)  throws IOException, JRException {
63        String filePath = jasperReportPath + reportKey + ".jrxml";//图省事只支持jrxml的
64        InputStream jasperFileIS = null;
65        JasperReport jasperReport = null;
66         
67        try {
68            jasperFileIS = this.getClass().getClassLoader().getResourceAsStream(filePath);
69            if (jasperFileIS == null) {
70                throw new ReportException("报表文件不存在:" + filePath);
71            }
72             
73            JasperDesign jasperDesign = JRXmlLoader.load(jasperFileIS);
74            jasperReport = JasperCompileManager.compileReport(jasperDesign);
75        } finally {
76            if (jasperFileIS != null) {
77                jasperFileIS.close();
78            }
79        }
80         
81        return jasperReport;
82    }
83     
84    public String getJasperReportPath() {
85        return jasperReportPath;
86    }
87     
88    public void setJasperReportPath(String jasperReportPath) {
89        this.jasperReportPath = jasperReportPath;
90    }
91     
92    public static void main(String[] argv) {
93     
94    }
95     
96}

以上就可以产生中间文件了,接下来就是按照spring的view规范写一个导出各种格式的视图就可以了

01public class ReportView extends AbstractView  {
02    private static final Log logger = LogFactory.getLog(ReportView.class);
03    private static final String XLS = "xls";
04    private static final String PDF = "pdf";
05    private static final String CSV = "csv";
06    private static final String REPORT_NAME = "reportName";
07    private static final String FORMAT = "format";
08    private static final String REPORT_PRINT = "reportPrint";
09    private static final String HTML = "html";
10     
11    private static Map<String, IReportFileExporter> EXPORTER_MAP =
12            new HashMap<String, IReportFileExporter>(4);
13     
14    static {
15        EXPORTER_MAP.put(XLS, new ReportXlsExporter());
16        EXPORTER_MAP.put(PDF, new ReportPdfExporter());
17        EXPORTER_MAP.put(CSV, new ReportCsvExporter());
18        EXPORTER_MAP.put(HTML, new ReportHtmlExporter());
19    }
20     
21    @Override
22    protected void renderMergedOutputModel(Map model, HttpServletRequest request,
23            HttpServletResponse response) {
24        String reportName = (String) model.get(REPORT_NAME);//报表的文件名
25        String format = (String) model.get(FORMAT);//报表的格式pdf xls .....
26        ReportPrint reportPrint = (ReportPrint) model.get(REPORT_PRINT);//这就是之前生成的中间文件
27        response.setContentType("application/x-msdown;charset=utf-8");
28        try {
29            /* http头里的文件名貌似不支持utf-8,gbk之类的编码,需要转换一下
30             * 另外发现如果用new String(reportName.getBytes("UTF-8"), "iso-8859-1")的话Chrome和FF的
31             * 下载对话框的文件名是正常的,IE却是乱码,只能用GBK才正常
32             */
33            response.setHeader("Content-Disposition","attachment;filename=\"" +
34                    new String(reportName.getBytes("GBK"), "iso-8859-1") + "\"");
35        } catch (UnsupportedEncodingException e) {
36            logger.error(null, e);
37        }
38        exportFile(reportPrint, format, response);
39    }
40     
41    private void exportFile(ReportPrint reportPrint, String format, HttpServletResponse response) {
42        try {
43            _exportFile(reportPrint, format, response);
44        } catch (JRException e) {
45            logger.error("导出报表异常", e);
46        } catch (IOException e) {
47            logger.error(null, e);
48        }
49    }
50     
51    private void _exportFile(ReportPrint reportPrint, String format, HttpServletResponse response) throws IOException, JRException {
52        OutputStream buffOS = null;
53         
54        try {
55            buffOS = new BufferedOutputStream(response.getOutputStream());
56            IReportFileExporter exporter = null;
57             
58            if (EXPORTER_MAP.containsKey(format)) {
59                exporter = EXPORTER_MAP.get(format);//获取需要格式的导出类
60                exporter.export(reportPrint, buffOS);
61            } else {
62                logger.error("错误的报表格式:" + format);
63            }
64        } finally {
65            if (buffOS != null) {
66                buffOS.close();
67            }
68        }
69    }
70     
71}
导出器是一个简单的接口,各种格式只要实现export方法就可以了

1public interface IReportFileExporter {
2    public void export(ReportPrint reportPrint, OutputStream os) throws JRException;
3}
给一个导出PDF格式的例子,很简单

01public class ReportPdfExporter implements IReportFileExporter {
02 
03    public void export(ReportPrint reportPrint, OutputStream os) throws JRException {
04        JRPdfExporter exporter = new JRPdfExporter();
05        exporter.setParameter(JRExporterParameter.JASPER_PRINT, reportPrint.getJasperPrint());
06        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
07        exporter.exportReport();
08    }
09 
10}

差不多久这样了,完整的代码已经上传。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多