pass list in Java Beans List in Jasper Report

2020-02-01 08:36发布

I am using Jasper Report with Servlet. Team Bean looks like

private int tid;
private String title;
private List<Member> members;
//getter and setter

Member bean looks like

private int id;
private String name;
//getter and setter

In report Servlet,

 List<Team> teams = service.getTeams();
 Map parameters = new HashMap();
 JasperPrint jasperPrint = null;
 jasperPrint  = JasperFillManager.fillReport(jasperReport, parameters, new JRBeanCollectionDataSource(teams));

When add teams in new JRBeanCollectionDataSource(teams), how can I show it in Jasper report? Because it contains List in the List.

Do I need subreport to solve this problem?

Or can I solve this without subreport?

1条回答
姐就是有狂的资本
2楼-- · 2020-02-01 09:20

There are two ways that you can accomplish this:

With a subreport

You can indeed solve this by using a subreport. To do that you would need to add a subreport and set its datasource expression to new JRBeanCollectionDataSource($F{members}). The fields of your Member bean would then be available as fields in the subreport (e.g. $F{name}).

With a list component

You can also solve this without a subreport by using a list component. This is available from the palette in iReport, or you can copy the example below. This needs to be added to the detail band of your report.

The list component has a datasource expression just like a report, which you should set to new JRBeanCollectionDataSource($F{members}), and has a listContents element that behaves like the detail band of a subreport; the elements inside it will be repeated once for every member in the datasource.

The list component requires a subdataset in your report, but this will be added automatically by iReport, or you can easily add an empty one: <subDataset name="dataset1"/>.

<componentElement>
    <reportElement x="0" y="0" width="555" height="20"/>
        <jr:list xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
        <datasetRun subDataset="dataset1">
            <dataSourceExpression><![CDATA[new JRBeanCollectionDataSource($F{members})]]></dataSourceExpression>
        </datasetRun>
        <jr:listContents height="20" width="555">
            <textField>
                <reportElement x="0" y="0" width="100" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
            </textField>
        </jr:listContents>
    </jr:list>
</componentElement>

More information on the list component is available here: http://jasperreports.sourceforge.net/sample.reference/list/index.html

查看更多
登录 后发表回答