iReport+JasperReport+JSP 输出HTML方式预览
目前JasperReport最新版本是3.7.2,iReport也有同步版本更新。今天试用了一下,并用JSP生成HTML预览,代码如下:
2 pageEncoding = " UTF-8 " %>
3 <% @ page
4 import = " java.io.*,
5 net.sf.jasperreports.engine. * ,
6 net.sf.jasperreports.engine.util. * ,
7 java.util. * ,java.sql. * ,
8 net.sf.jasperreports.engine.export. * " %>
9 <! DOCTYPE html PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN " " http://www.w3.org/TR/html4/loose.dtd " >
10 < html >
11 < head >
12 < meta http - equiv = " Content-Type " content = " text/html; charset=UTF-8 " >
13 < title > Insert title here </ title >
14 </ head >
15 < body >
16 <%
17 File reportFile = new File(application
18 .getRealPath( " jasper/Test2.jasper " ));
19 JasperReport jasperReport = (JasperReport) JRLoader
20 .loadObject(reportFile.getPath());
21 Map parameters = new HashMap();
22 parameters.put( " para1 " , " AAA " );
23 Class.forName( " com.mysql.jdbc.Driver " );
24 Connection conn = DriverManager.getConnection(
25 " jdbc:mysql://localhost:3306/phpcms " , " root " , " root " );
26 JasperPrint jasperPrint = JasperFillManager.fillReport(
27 jasperReport, parameters, conn);
28 JRHtmlExporter exporter = new JRHtmlExporter();
29 exporter
30 .setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
31 exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
32
33 exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
34 exporter.exportReport();
35 out.flush();
36 conn.close();
37 %>
38 </ body >
39 </ html >
首先,需使用iReport制作模板,我使用的是本机Mysql数据源,取得数据库phpcms中的某个表的数据,模板字段根据SQL语句自动生成,同时手工新建一个模板变量“para1”,作为生成报表时实时变量传递。最后编译模板,生成Test2.jasper文件;
然后打开Eclipse JEE,新建Dynamic Web Project,将Test2.jasper拷贝到项目目录webContent/jasper下,引入commons-collections.jar,commons-digester.jar,commons-logging.jar,jasperreport-3.7.2.jar,log4j.jar,mysql-connector-java.jar包,一定要引入这些包,不然似乎是无法运行起来的。
注意,如果异常提示找不到Groovy相关的类,请不要盲目的去引入Groovy包,先确认自己的模板里是否有使用Groovy脚步,如果没有的话,请检查自己的xml模板文件(*.jrxml)中jasperReport标签配置项里关于language的设置,如果是groovy,请修改为java即可。本来这个是可以通过设置iReport的全局选项的语言项来搞定,不过我尝试过修改为Java好像也不管用,不知道是否是iReport的bug
最后,用浏览器打开验证报表生成情况,并看para1是否正确传递。