如何从JSP或Java代码传递JasperReport中的参数值?

时间:2012-03-26 06:35:11

标签: java jasper-reports

我已成功创建报告并成功导出到HTMLPDF。然而,这是一个静态报告。我有一个查询:

select * from personal where id= 'val' 

我想在运行时从Java/JSP发送此参数“val”。怎么做?

3 个答案:

答案 0 :(得分:15)

创建包含参数的Map并将参数作为键值对放置。

Map parametersMap = new HashMap();  
parametersMap.put("id",7);

从JSP生成Jasper报告时:

JasperPrint jasperPrint = JasperFillManager.fillReport(
jasperReport, parametersMap, jdbcConnection);

parametersMap中的密钥与报告模板中定义的参数相同。

因此,在报告模板(jrxml)中声明参数:

<parameter name="id" class="java.lang.Integer"/>

在Jasper报告中的查询中传递参数

select * from personal where id= $P{id}

答案 1 :(得分:0)

您无法选择*,您必须指明要从中获取数据的列名称。使用 commDB.query执行查询,然后将结果传递给commDBResult,运行循环,将每行记录放入数组列表,然后使用jasper生成报告

答案 2 :(得分:0)

这将是你的jsp代码。

<%@page import="net.sf.jasperreports.engine.JasperExportManager"%>
<%@page import="net.sf.jasperreports.engine.JasperExportManager"%>
<%@page import="net.sf.jasperreports.view.JasperViewer"%>
<%@page import="net.sf.jasperreports.engine.JasperPrint"%>
<%@page import="net.sf.jasperreports.engine.JasperReport"%>
<%@page import="net.sf.jasperreports.engine.JasperFillManager"%>
<%@page import="net.sf.jasperreports.engine.JRResultSetDataSource"%>
<%@page import="net.sf.jasperreports.engine.JasperCompileManager"%>
<%@page import="net.sf.jasperreports.*"%>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
<%
           try
           {
       JasperReport jasperReport=JasperCompileManager.compileReport("PASS LOCATION TO YOUR .JRXML FILE");
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn =   DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet" , "root", "root");
        Integer inv_no=0;
        Statement stmt = null;
        ResultSet rset = null;
        Statement st2=conn.createStatement();
        String queryString = "PASS YOUR QUERY HERE";
        stmt = conn.createStatement();
        rset = stmt.executeQuery(queryString);
        JRResultSetDataSource jasperReports = new JRResultSetDataSource(rset);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,null, jasperReports);
        //JasperViewer.viewReport(jasperPrint); 

        String filename=null;
        filename="SET NAME TO YOUR FILE NAME AND APPEND.pdf TO IT";

        //Report saved in specified path
        JasperExportManager.exportReportToPdfFile(jasperPrint,filename);

        //Report open in Runtime
        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " +filename);
       }
       catch(Exception e)
       {
           out.println(e);
       }
    %>

    </body>
    <script>

     </script>
</html>