Expert Spring MVC and Web Flow

(Dana P.) #1
Listing 8-44.Using a URI Extension As a Mapping Key

public ModelAndView handleMultiReport(
HttpServletRequest request, HttpServletResponse response)
throws Exception {

String uri = request.getRequestURI();
String reportFormat = uri.substring(uri.lastIndexOf(".") + 1);

Map model = getModel();
model.put("format", reportFormat);

return new ModelAndView("report", model);
}

With proper configuration of the request URIs in your dispatcher’s context file, this
method can now be used to serve multiple format reports. For example, a request of
/ExpertSpringMVC/app/home.pdfwill result in a PDF version of the report, and
/ExpertSpringMVC/app/home.xlswill generate an Excel spreadsheet–based report.

■NoteThe format key (formatin the preceding example) is the name by which
JasperReportsMultiFormatViewwill look up the actual format type (csv,xls,or whatever). If you need
to change the name of the format key to something else, you can do so by setting theformatKeyproperty
on the View.

Populating the Report


A report isn’t much to look at unless it has some data to show. In common with all Spring’s
supported view types, Jasper report Views extract their data from the model, and you can do
this in two principal ways—differing slightly from other view types in this respect.
Jasper natively works with an instance of JRDataSource,which is an interface from the
Jasper library. If your model contains a single attribute and it implements JRDataSource,
then Spring will expose this object to the Jasper runtime. If your single model attribute is
a java.util.Collection, this can also be used; Spring will convert the Collectionto a
JRDataSourceand use this instead.
Should your model consist of more than one attribute, then you should configure the
Jasper Viewto tell it which model attribute is the JRDataSourceor Collectionto use. Failing
to do so means that Spring will expose the first attribute it finds that is one of those types—
which may not be the data you wanted to see in your report! On the Viewconfiguration, set
the reportDataKeyvalue to the same name as your collection in the model. Listing 8-45 shows
this setting.

262 CHAPTER 8 ■SUPPORTED VIEW TYPES

Free download pdf