搜索.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h3>Search the id which you want</h3>
<form method="POST" action="filereport.jsp">
<p>Give the searching ID</p>
<input type="text" name="employid"/><br>
<input type="submit" value="show"/>
</form>
</body>
</html>
文件报告.jsp
<%@page import="java.sql.SQLException"%>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.Map"%>
<%@ page import="net.sf.jasperreports.engine.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="Class.*" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h2>your searching result is :</h2>
<%
Connection conn=null;
try{
//connection to mysql database
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/product?user=root&password=mysql123");
////Loading Jasper Report File from Local file system
String jrxmlFile = session.getServletContext().getRealPath(request.getContextPath())+"/Reports/reportgenerate.jasper";
InputStream input = new FileInputStream(new File(jrxmlFile));
Map parameters = new HashMap();
int id=Integer.parseInt(request.getParameter("employid"));
parameters.put("employeeid", id);
//generating the report
JasperReport jasperReport = JasperCompileManager.compileReport(input);
JasperPrint jasperPrint=JasperFillManager.fillReport(jasperReport, parameters,conn);
//byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), parameters, conn.getconnection());
//exporting the report as pdf
//
////Exporting the report as a PDF
JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(JRException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
if(conn!=null){
conn.close();
}
}
%>
</body>
</html>
问题是当我运行文件时,会打开一个空白的 pdf 视图,并显示错误“无法加载 pdf 文档”。有人可以帮忙吗?
提前致谢。
我可以看到两个问题:
flush
和 close
response.getOutputStream()
示例
JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
考虑使用
try
catch
语句来表示 close()
,并为您的响应添加正确的标题。
whenNoDataType
标签上没有属性 jasperReport
,它将生成一个空的 pdf,这可能会造成麻烦。您可以更改此行为设置 whenNoDataType="BlankPage"
或您认为最合适的任何内容。请参阅 WhenNoDataTypeEnum API有时问题可能出在您的浏览器 (Chrome) 设置上。您应该转到 Chrome 浏览器中的设置,然后转到隐私,然后转到网站设置,然后向下滚动到 PDF 文档,然后删除“从 Chrome 中打开”选项并选择“下载 PDF”
也许另一个问题可能是您使用后没有
flush
和close
您的outputStream
;即,
outputStream.flush();
outputStream.close();