publicclass HtmlReportServlet extends HttpServlet {
privatestaticfinallong serialVersionUID = 1L;
publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//连结数据库
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/jasperreportdb","root","root");
//获得Jasper输入流
InputStream inputStream = getServletConfig().getServletContext().getResourceAsStream("JasperFile//report9.jasper");
//获得JasperPrint对象
JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, new HashMap(),connection);
connection.close();
//设置格式
response.setContentType("text/html");
//获得输出流 ,这里不能这样response.getOutputStream()
PrintWriter printWriter = response.getWriter();
//创建JRHtmlExporter对象
JRHtmlExporter htmlExporter = new JRHtmlExporter();
//把jasperPrint到Session里面(net.sf.jasperreports.j2ee.jasper_print)
request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
//设值jasperPrint
htmlExporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);
//设置输出
htmlExporter.setParameter(JRExporterParameter.OUTPUT_WRITER,printWriter);
//设置图片生成的Servlet(生成图片就用这个ImageServlet,并且要在XML文件里面配置 p_w_picpath?p_w_picpath=这个是Servlet的url-pattern)
htmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,"p_w_picpath?p_w_picpath=");
//导出
htmlExporter.exportReport();
printWriter.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (JRException e) {
e.printStackTrace();
}
}
publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}