Java Reference
In-Depth Information
One of the main features of the
springframework
is that it allows applications to be
very loosely coupled by allowing dependencies to be defined in XML configuration
files. This allows changing dependencies without having to change a single line
of code.
In the
jasperSpring-servlet.xml
file, we define a dependency on the
database datasource by declaring the bean with an
id
of
datasource
and setting
it up as a property of the
jasperController
bean. The bean with the
id
of
publicUrlMapping
maps the
report
URL to our controller. The bean with the
id
of
viewResolver
is an instance of
org.springframework.web.servlet.view.
ResourceBundleViewResolver
.
Its purpose is to look up values in a resource bundle to determine what view to use.
Its
basename
property defines the name of the property file containing the keys to
look up. In this case, the property file must be named
views.properties
.
report.class=org.springframework.web.servlet.view.jasperreports.
JasperReportsPdfView
report.url=reports/DbReportDS.jasper
Notice that the base name of the keys (
report
, in this case) must match
the name of the controller property defined in the application context for
SimpleUrlHandlerMapping
. It is in this property file that we actually declare that
JasperReports will be used to render the data.
In this example, we are using the
JasperReportsPdfView
class to export to PDF.
The Spring framework also supports exporting to CSV, HTML, and Excel. To
export to one of these formats, the classes to use would be
JasperReportsCsvView
,
JasperReportsHtmlView
, and
JasperReportsXlsView
, respectively. All of these classes
are in the
org.springframework.web.servlet.view.jasperreports
package.
The
report.url
property defines where to find the compiled report template. In
order for the
JasperReportsPdfView
class to find the compiled report template,
it must be located in a directory matching the value of this property. The report
template we will use for this example is the one discussed in the
Database Reporting
via a Datasource
section of Chapter 4.
Just as with most MVC frameworks, we never code our servlets directly when
writing web applications using Spring MVC; instead, we write controller classes.
In this example, our controller class implements the
org.springframework.web.
servlet.mvc.Controller
interface. This interface defines a single method called
handleRequest()
.
package net.ensode.jasperbook.spring;
import java.io.IOException;