I have defined the following template:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport
PUBLIC "-//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="HelloJasper_report">
<parameter name="customer" class="com.eternity.model.Customer"/>
<detail>
<band height="20">
<staticText>
<reportElement x="220" y="0" width="200" height="20"/>
<text><![CDATA[$P{customer.firstName}]]></text>
</staticText>
</band>
</detail>
</jasperReport>
I am crateing the report with the following:
try{
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("customer", new Customer("Example name"));
System.out.println("Generating PDF...");
JasperReport jasperReport =
JasperCompileManager.compileReport("hellojasper.jrxml");
JasperPrint jasperPrint =
JasperFillManager.fillReport(jasperReport, parameters, new JREmptyDataSource());
JasperExportManager.exportReportToPdfFile(
jasperPrint, "HelloJasper.pdf");
System.out.println("HelloJasper.pdf has been generated!");
}
catch (JRException e){
e.printStackTrace();
}
where Customer is
public class Customer{
private String firstName;
public Customer(String firstName){
this.firstName = firstName;
}
}
However, the generated PDF just prints:
$P{customer.firstName}
What am I missing?
First of all, in your report you've declared a staticText
block, which will print exactly the value from the text
tag - that is why you're getting $P{person.firstName}
.
In order to evaluate parameter and print it's value you should use textField
with textFieldExpression
in your report design:
<textField isBlankWhenNull = "true">
<reportElement x="220" y="0" width="200" height="20"/>
<textElement/>
<textFieldExpression class = "java.lang.String">
<![CDATA[$P{person}.firstName]]>
</textFieldExpression>
</textField>
Secondly, you declared your person
parameter to be an instance of class com.eternity.model.Person
. Though in code you put Customer
as a person
parameter (and it doesn't seem to be a sublclass of Person). You have to:
Customer
a subclass of com.eternity.model.Person
,person
parameter to be of class Customer
with fully qualified package name (there is no package visible in your original answer).And lastly: the firstName
field has private modifier, so you should add a public getFirstName
method to your class
public String getFirstName() {
return this.firstName;
}
and then call <![CDATA[$P{person}.getFirstName()]]>
in your report.