1. 程式人生 > >ireport在jsp中的呼叫例子

ireport在jsp中的呼叫例子

 <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ page import="java.io.*,java.sql.*,net.sf.jasperreports.engine.*" %>
<%@ page import="com.microsoft.sqlserver.jdbc.SQLServerDriver" %>
<%@ include file="/common/header.jsp" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "

http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 <title>報表列印</title>
 <link rel="stylesheet" type="text/css" href="<s:property value="%{default_css}"/>" />
</head>

<body id="Body">
    <%
        String reportName = request.getParameter("reportName");
        //報表編譯之後的.jasper檔案的存放位置


        File reportFile = new File(application.getRealPath("/report/resource/jasper/"+reportName+".jasper"));
        String url = "jdbc:sqlserver://liubin:1433;DatabaseName=db_forest_police";
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        //傳遞報表中用到的引數值,這裡是空值
        Map parameters = new HashMap();
       
        System.out.println("-----------conn---------");
        //連線到資料庫
        Connection conn = DriverManager.getConnection(url,"sa","time0442");
        System.out.println("----------jasper begin-----------");
        //在控制檯列印報表檔案的物理路徑
        System.out.println("****物理路徑 ***"+reportFile.getPath());
       
        byte[]bytes = JasperRunManager.runReportToPdf(reportFile.getPath(),parameters,conn);
       
        System.out.println("---------jasper end-------");
        response.setContentType("application/pdf");
        response.setContentLength(bytes.length);


        //清除輸出物件的衝突(因jsp本身有自己的out輸出物件,如果去除下面的語句,則response.getOutputStream()得到的輸出物件與原來存在的out物件衝突,會報異常)

       out.clear();out=pageContext.pushBody();
       
        ServletOutputStream output = response.getOutputStream();
        output.write(bytes,0,bytes.length);
        output.flush();
        output.close();
       
        try{
            if(conn!=null){
               conn.close();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
     %> 
</body>
</html>