How do we access parameters of a bean in Jasper Re

2020-05-29 05:35发布

问题:

How do we access parameters of a bean in Jasper Reports?

I have to display the data of a model (which is not a collection) in Jasper Reports.

I pass the model to the Jasper Report as parameters in a Map.

Map<String,Object> params = new HashMap<String,Object>();
params.put("object", object);

Now this object has fields whose data I need to display in the report header section.

Like in jsp we do ${object.name}, ${object.phone} etc., how do we achieve this in JasperReports?

I tried doing $P{object.name} but it doesn't work.

Can anyone please let me know how to achieve this?

回答1:

There are a couple steps to accomplish this.

1) Define your parameter: This will be the full package and class name of the type of the parameter. Something like:

<parameter name="object" class="com.mystuff.User"/>

2) Call the getter method for the value you want: Add a textfield to the appropriate field. If I wanted to use the value for the method getId() in my User class I my textfield would look like:

<textField>
    <reportElement uuid="09bf47a8-8fc7-45c5-911a-c79c3d405ada" x="205" y="22" width="100" height="20"/>
    <textElement/>
    <textFieldExpression><![CDATA[$P{parameter1}.getId()]]></textFieldExpression>
</textField>

3) Set up the classpath in the iReport: If you are using iReport to design your report you need to tell it where the compiled version of the com.mystuff.User class is located. If you are in eclipse you can just point it to your bin folder in your project, or if you have a jar of the compiled project you can point it to that. The classpath settings are located at Tools -> Options -> Classpath Tab.