前提操作:将要转的jasper文件放到webcontent下,可专门建一个文件夹,此处为report。
转为html文件:
在WebRoot根目录下创建jsp文件testhtml.jsp,内容如下:
<%@
page
contentType
=
"text/html;charset=GB2312"
%>
<%@
page
import
=
"net.sf.jasperreports.engine.*"
%>
<%@
page
import
=
"java.util.*"
%>
<%@
page
import
=
"java.io.*"
%>
<%@
page
import
=
"java.sql.*"
%>
<%
//
报表编译之后生成的
.jasper
文件的存放位置
File reportFile =
new
File(
this
.getServletContext().
(1)
getRealPath(
"/report/sample.jasper"
));
String url=
"jdbc:mysql://localhost:3306/db"
;
Class.forName(
"com.mysql.jdbc.Driver"
);
Map parameters =
new
HashMap();
//"SQLSTR"
是报表中定义的参数名称
,
其类型为
String
型
//
设置
SQLSTR
参数的内容
,
根据需要赋值
sql
语句
parameters.put(
"SQLSTR"
,
"select * from employee"
);
(2)
Connectionconn =DriverManager.getConnection(url,
(3)
"username"
,
"password"
);
JasperRunManager.runReportToHtmlFile(reportFile.getPath(),
(4)
parameters,conn);
response.sendRedirect(
"report/sample.html"
);
(5)
.//将html文件存储下来
File destFile =new File("D:\\test.html");
JasperRunManager.runReportToHtmlFile(reportFile.getPath(), destFile.getPath(), parameters, Connectionconn);
destFile.createNewFile();
%>
|
代码说明:
1. 定位jasper文件
2. 给报表模板中使用到的参数SQLSTR赋值,这里指定一个sql语句
3. 采用JDBC方式连结数据库
4. 生成HTML文件,参数分别为报表文件模板物理位置,报表参数,数据库连结
5. 转向到此页面,这个页面是固定的,需要和报表模板的位置和路径相同
发布项目后预览,输入
http://localhost:8080/iReportTest/testhtml.jsp(本例采用tomcat作为web服务器,发布过程参考其他文档,数据库采用的mysql)
效果:
4.8 创建显示PDF格式报表的JSP文件
在WebRoot根目录下创建jsp文件testpdf.jsp,内容如下:
<%@
page
contentType
=
"application/pdf;charset=UTF-8"
%>
<%@
page
import
=
"net.sf.jasperreports.engine.*"
%>
<%@
page
import
=
"java.util.*"
%>
<%@
page
import
=
"java.io.*"
%>
<%@
page
import
=
"java.sql.*"
%>
<%
//
报表编译之后生成的
.jasper
文件的存放位置
File reportFile =
new
File(
this
.getServletContext().
getRealPath(
"/report/sample.jasper"
));
String url=
"jdbc:mysql://localhost:3306/db"
;
Class.forName(
"com.mysql.jdbc.Driver"
);
Map parameters =
new
HashMap();
//"SQLSTR"
是报表中定义的一个参数名称
,
其类型为
String
型
parameters.put(
"SQLSTR"
,
"select * from employee where employee_id like 'Z%'"
);
Connection conn = DriverManager.getConnection(url,
"username"
,
"password"
);
byte
[] bytes=JasperRunManager.
runReportToPdf(reportFile.getPath(),parameters,conn);
response.setContentType(
"application/pdf"
);
response.setContentLength(bytes.length);
ServletOutputStream outStream = response.getOutputStream();
outStream.write(bytes,0,bytes.length);
outStream.flush();
outStream.close();
out.clear();
out = pageContext.pushBody();
%>
参考自http://blog.csdn.net/trocp/article/details/6910745
|