Accessing the only Java bean passed to jasper reco

2019-07-29 23:58发布

问题:

I need to create a PDF file using JasperReports. The problem is that it has to take only one Java bean as a parameter (not list nor array) and the report has custom layout that can not be expressed in tables or lists or whatever. If I execute the following code, when jrxml has only layout and no printing of the parameters - PDF displays OK. This is how I try to pass a parameter:

Map<String, Object> map = new HashMap<String, Object>();
url = getClass().getClassLoader().getResource("/WEB-INF/reports/reg.jrxml");
jasperReport = JasperCompileManager.compileReport(url.getPath());
map.put("PARAM_NAME", myBean);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, 
    map, new JREmptyDataSource());
JasperExportManager.exportReportToPdfStream(jasperPrint, responseOutputStream);

The question is, how should I configure my jrxml file so that I have access to fields of myBean, so that I can fill in text fields? I have tried adding

<parameter name="PARAM_NAME" class="net.sf.jasperreports.engine.JRDataSource"/>

to jrxml file but I still can't access it's fields. Say, myBean has a field uid and getUid() correspondingly and I need to print it somewhere.

回答1:

Don't know why I couldn't do this from the very beginning... Changed parts of Java code to:

List<IBClientBean> data = new ArrayList<MyBean>();
data.add(myBean);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, 
    new HashMap<String, Object>(), new JRBeanCollectionDataSource(data));

and added manually to the beginning of jrxml file, right after declaration of properties (instead of what I tried to add in the question):

<field name="uid" class="java.lang.String"/>

and so on for all required fields in MyBean. Then I was able to print uid to pdf simply typing $F{uid} inside of Text Field.