ireport学习笔记

 将数据库的数据生成pdf,jar包以及ireport文件夹位置见相册图片

package com.ireport;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;

public class Report extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  this.doPost(request, response);
 }

 @SuppressWarnings("deprecation")
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  response.setContentType("text/html;charset=utf-8");
  request.setCharacterEncoding("utf-8");
  Map parameters = new HashMap();

//设置参数,即select * from product where product_id = ?(下面的pro_id为这里的参数),这里你懂的。。。。
  String pro_id = "1";
  try {
   Connection con = DBCon.getCon();//连接数据库
   File exe_rpt = new File(request.getRealPath("/ireport/test.jasper"));
   parameters.put("pro_id", pro_id);

   JasperPrint jasperPrint = JasperFillManager.fillReport(exe_rpt.getPath(), parameters, con);
   // 生成pdf
   byte[] bytes = JasperRunManager.runReportToPdf(exe_rpt.getPath(), parameters, con);
   response.setHeader("Content-disposition", "attachment; filename="
     + java.net.URLEncoder.encode("报表", "UTF-8") + ".pdf");// 设定输出文件头,该方法有两个参数,分别表示应答头的名字和值。
   response.setContentType("application/pdf;charset=GBK");
   response.setContentLength(bytes.length);
   ServletOutputStream ouputStream = response.getOutputStream();
   ouputStream.write(bytes, 0, bytes.length);
   ouputStream.flush();
   ouputStream.close();
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

}

你可能感兴趣的:(parameters,string,exe,exception,数据库,report)