Professional Documents
Culture Documents
Os Ag Spring Frame 6 PDF
Os Ag Spring Frame 6 PDF
23 Jan 2007
This tutorial, the final installment in a six-part series, shows you how to use
Java™Server Pages (JSP), Velocity, Tiles, and PDF export using the Spring
Framework. You'll experiment with the V in Model-View-Controller (MVC) -- the
various Web views built into the Spring MVC. Along with this solid introduction to the
various view technologies supported by the Spring MVC, you'll see how easy these
technologies are to implement in the sample Phonebook application you've been
building throughout this series.
Part 2 covered how to build your first bare-bones application using the Spring
Framework on Geronimo.
Part 3 showed you how to extend the Geronimo application from Part 2 by adding
Java Database Connectivity (JDBC) support via the Derby database. You saw how
to integrate Object Relational Mapping (ORM) to your application using iBATIS.
Part 4 introduced you to Spring AOP and the Spring Web Framework. With the
Spring AOP, any object managed by the Spring Framework can become aspect
oriented, and this tutorial relies on the declarative transaction management services
provided via the Spring AOP.
Part 5 examined Spring MVC and got you started with the Spring MVC by
introducing you to its MVC framework and Web views.
This final installment, Part 6, shows you how to use JSP, Velocity, Tiles, and PDF
export using the Spring Framework. You get to experiment with various Web views
built into the Spring MVC.
One of the biggest challenges that Web application developers face is creating an
adaptable design. Making your views component flexible is particularly challenging.
Because Spring's support for views is so robust, this challenge is more manageable.
The use of JSPs, Tiles, Velocity, and PDF export in this tutorial is designed to
demonstrate how the Spring MVC API makes this possible.
JSPs and Velocity are two complementary view technologies. You can create views
using either one, each with its own set of advantages and disadvantages. This
tutorial demonstrates how easy it is to replace one with the other in the sample
Phonebook application.
You begin by reviewing JSP support in Spring MVC and then looking at Tiles, a very
good templating engine for view layout management. Tiles makes it easy to manage
your Web page layout, and Spring has built-in support for Tiles. You'll make use of
these classes to change the Web layout of the Phonebook application.
Next you'll replace the use of JSPs by using views defined with the Velocity
templating engine. Velocity makes it easy to access Java objects in your views
without complex definitions and Java constructs, such as Try Catch loops.
Finally, you get a look at rendering the Phonebook application's home page to be
displayed as a PDF file. Spring takes care of all the cumbersome and complex code
and logic needed to create a PDF. It gives you a clean API to work on the content,
without confusing you with PDF details.
Prerequisites
To follow along with this tutorial you should have a basic understanding of:
• Object-oriented programming
• Java Platform, Enterprise Edition (Java EE) terminology
• SQL statements
• XML semantics
• JSP tags, tag libraries, and tag library descriptors
An understanding of MVC is a plus, and a working knowledge of Velocity is also
highly advantageous, but isn't required.
System requirements
You need the following tools to follow along:
• The Spring Framework v1.2.8 -- You'll be using the compressed file with
all dependencies.
• Apache Geronimo 1.1 -- Geronimo is a Java 2 Platform, Enterprise
Edition (J2EE)-certified application server from Apache.
• Apache Derby database -- This tutorial uses Derby, which is an open
This section contains instructions for installing and configuring the software required
to develop, deploy, and run the example application.
All of these JAR files come bundled with the Spring Framework
installation package. You can find them in the directories indicated in the
above list, next to the .jar file name. Make sure to copy all of these JAR
files into the <WORKSPACE>/phonebook/lib directory.
5. Installing Standard Taglibs from Apache and the Spring taglib: You'll
use the JSPs defined in Part 5 of this tutorial series and extend your
application using them, so you need to install JSTL libraries. (Refer to the
installation instructions in Part 5 of this series.)
6. Data model definition and database setup for your application: You'll
use the same Derby database that you created in other parts of this
tutorial series. The data model is also the same. If you created the
database and tables in Part 3, 4, or 5, then you should be all set. If not,
please follow instructions from Part 3 to take care of that first.
Tiles
Tiles is a templating engine built into the Apache Struts framework. Some of the
important features provided by Tiles include:
Tiles is also beneficial to you if your Geronimo application's views use similar view
components in multiple pages. For example, if all your pages need to have the same
header and footer, or even a same left menu, then you can define these as Tiles and
use the Tiles API as a layout manager.
Velocity
Velocity, another templating engine based on Java technology, allows objects
defined in Java code to be referenced from views. One of the primary goals of
Velocity is to provide an alternate and simpler view technology to JSP view
technology by attempting to eliminate the complex use of JSP tags and Java
constructs like Try Catch loops.
Velocity also allows Web designers to work in parallel with application developers
based on the MVC model. Web page designers can focus solely on creating the site,
and programmers can focus on application code, because Velocity separates Java
code from the Web pages, making the pages more maintainable.
Figure 1 shows the basic MVC pattern using Velocity as the view technology.
Views are created as Velocity templates, or .vm files. You can pass Java objects as
references to these views. You'll see how this works in later sections of this tutorial.
Clean and maintainable JSPs are a major benefit of using Velocity as a view
technology for your Geronimo applications. Velocity views contain the HTML that
represents the Web page view, with minimal reference to Java objects.
PDF export
Generating PDFs for Web views has always been a challenge for Web application
developers. Creating the PDF alone involves a cumbersome set of steps, and this
doesn't even take into account the difficulty in adding content. Spring MVC's PDF
support simplifies the process considerably. It takes care of all the intricate steps
involved in creating PDFs and provides a streamlined API to add content into it.
Spring's PDF support makes it easy to export your page views as PDFs in your
Geronimo application.
Now that you've laid the groundwork for the various technologies covered in this
tutorial, it's time to integrate them into the Phonebook application.
• Define a view class to create the PDF for your Phonebook home page.
• Add this to the view resolver chain in Application Context.
Figure 2. Directory structure of the application after extracting the source file
As you can see in the directory structure listed in Figure 2, there are no new
controllers for Tiles -- it's all about configuration. In the following sections, you'll find
out how Spring makes this possible.
Figure 3 gives you an idea of how to define your layout using Tiles.
Figure 3. Directory structure of the application after unzipping the source file
As you can see, Tiles acts as the layout manager and the individual implementation
pages are considered JSP Tiles. The layout manager can place the Tiles in
whatever way you want as long as the template elements are provided an
implementation page via a definition.
Next, see how you can replace the JSPs with views defined in Velocity by just
changing some configurations in the Application Context file. For this tutorial, you'll
change the home page to be replaced by the Velocity template. You can use it as an
exercise to convert the rest of the pages to Velocity views.
The final part of your application shows you how to create a PDF view using the
AbstractPdfView class from Spring MVC. This class takes care of all the work of
creating the PDF document for you and gives you a clean document to add your
content to. Then you'll manually create the Phonebook home page and return it as a
PDF.
Note: Spring MVC's PDF support is not like a screen grabber for Web pages; there
are other tools available for that purpose. You have to manually create a view that
you want to export in the PDF document.
As with any other JSP tag library, you must add the Tiles library to the Web
application deployment descriptor before you can use it. Just add the taglib element
in Listing 1 to your web.xml file.
<jsp-config>
<taglib>
<taglib-uri>/tiles</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</taglib>
</jsp-config>
tag library to describe the layout of a page. It defines how the pages of your
application will look without specifying the content. The content will be inserted at
run time. As you can see, it's a simple template; you define your default page
structure to be Header > Body > Footer. Listing 2 shows the code for this JSP.
Listing 2. phonebook-layout.jsp shows how your Web pages are laid out
You'll use this same template for all your pages. It's using the tiles:insert tag to
insert contents represented by the name attribute. As you can see here, there's no
content, only the layout of the page.
Now you need to associate views to Tiles view names, which you'll do next.
You can see that the name of your view definition file is phonebook-definitions.xml.
The TilesConfigurer reads this file at initialization and then makes all the views
The other bean definition is for ViewResolver, which Spring should use to resolve
your view. The ResourceBundleViewResolver is one of the most commonly
used view resolvers from the Spring Framework. You need to pass in the properties
file that defines the view names that are mapped to a class and a URL. Listing 4
shows the contents from your views-phonebook-tiles.properties file.
home-mvc.class=org.springframework.web.servlet.view.tiles.TilesView
home-mvc.url=home-mvc
addentry-mvc.class=org.springframework.web.servlet.view.tiles.TilesView
addentry-mvc.url=addentry-mvc
modifyentry-mvc.class=org.springframework.web.servlet.view.tiles.TilesView
modifyentry-mvc.url=modifyentry-mvc
The definition in Listing 4 tells the Spring MVC module that you have three views in
your application, and each one is a TilesView. The second line shows the URL
specific to each page representing these views.
Next you'll see how to inject actual views implemented by specific JSPs into your
Tiles layout.
The layout tile shown in Listing 2 is generic and will be used by all of your Web
pages. It doesn't know anything about the home, addEntry, or ModifyEntry JSP
page contents. This is by design, as it lets you reuse this layout for many pages.
Instead of hardcoding the content in the layout definition page, it's passed as
parameters to the layout page at run time.
In Spring, you do this by defining an XML definitions file. Listing 5 shows how it's
done in your Phonebook application.
Listing 5. Definitions file for passing content in to layout page at run time
<tiles-definitions>
<!-- DEFAULT MAIN TEMPLATE -->
<definition name="template"
page="/WEB-INF/jsp/phonebook-layout.jsp">
<put name="header"
value="/WEB-INF/jsp/header.jsp"/>
<put name="footer"
value="/WEB-INF/jsp/footer.jsp"/>
</definition>
<!-- The Home Page -->
<definition name="home-mvc" extends="template">
</tiles-definitions>
The first definition defines a default template by giving it a name and a page that
contains the content for that template. If you go back to Listing 2, where you defined
the layout for your application in phonebook-layout.jsp, you'll notice that the name of
the views inserted in that layout are the same as those defined in this template. So
you're essentially associating content to the template in these definitions here.
The put elements in the template definition tell the Tiles framework where to get the
views from. In your case, the header view gets its content from header.jsp, and the
footer gets it from footer.jsp.
The next Tiles definition defines your home page. It extends the default template and
just injects the body into the home-mvc.jsp page. If you look at this definition
carefully, you'll see how your home page gets built. Here's what happens:
Now that you've seen Tiles in action with the Spring Framework on the Geronimo
application server, you can move on to integrating Velocity into your application.
There are two ways you can make ApplicationContext aware of your Velocity
templates. The first one is using the VelocityConfigurer. All you need to do is
provide the location of your Velocity templates in resourceLoaderPath, and the
VelocityConfigurer makes all the templates from that location available to your
application at run time.
The other (and preferred) way is to define your own controller and then use that to
locate your views. Listing 6 shows these bean definitions in the
phonebook-servlet.xml file.
The first two bean definitions define that a request for home.vel page should be
controlled by the PhonebookVelocityController class. You'll be defining this
class in the following sections. The third bean definition uses the
VelocityViewResolver to resolve any page requests with a .vm extension.
Listing 6. Bean definitions that make your context aware of Velocity views
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/*.do">phonebookController</prop>
<prop key="/*.htm">phonebookFlowController</prop>
<prop
key="/*.flow">phonebookFlowController</prop>
<prop
key="/addentry-mvc.act">addEntryFormController</prop>
<prop
key="/home-mvc.act">phonebookHomeController</prop>
<prop
key="/modifyentry-mvc.act">modifyEntryFormController</prop>
<prop
key="/deleteentry-mvc.act">deleteEntryFormController</prop>
<prop
key="/home.vel">phonebookVelocityController</prop>
<prop
key="/home.pdf">phonebookPDFController</prop>
</props>
</property>
</bean>
<bean id="phonebookVelocityController"
class="phonebook.velocity.PhonebookVelocityController"/>
<!-- View Resolver for Velocity -->
<bean id="velocityViewResolver"
class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"
>
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".vm"/>
</bean>
Why define a controller for Velocity in the first place? Remember that you populate
your home page with all the phonebook entries read from the database, and you
read this list from the database and pass it to the Velocity view as an object. The
Velocity engine passes this object to the home page template, which then iterates
through it using the Velocity Template Language tags. Listing 7 shows code for
PhonebookVelocityController.
Listing 7. Class that reads PhonebookEntries from the database and passes to
the view
You can see that the controller uses WebApplicationContext to get the
phonebook bean and reads the phonebook entries from the database. It then adds
this as an object to the view. You'll see how it's read by the Velocity template next.
Listing 8. The default template defining the layout of your Web application
You can see that your phonebook layout is the same. The Velocity engine reads this
template at run time, and the parse tag renders the components passed into it as
parameters. The viewName is passed in dynamically by the
phonebookVelocityController at run time.
if (retVal != true) {
return;
}
}
document.myForm.action="/phonebook/deleteentry-mvc.act";
document.myForm.method="POST";
document.myForm.submit();
}
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Phone Book - $time1 </title>
</head>
<body>
<!--The Heading of the Phone Book Page-->
<h1 align=center>Phone Book</h1>
<BR>
<BR>
<!-- The table containing phone book contents. -->
<TABLE border="1" width="100%">
<TH width="5%" align=center>Select</TH>
<TH width="25%" align=center>Name</TH>
<TH width="15%" align=center>Home Phone</TH>
<TH width="15%" align=center>Work Phone</TH>
<TH width="15%" align=center>Cell Phone</TH>
<TH width="25%" align=center>Email</TH>
</html>
This home.vm template definition uses Velocity Template Language (VTL), the
templating language for Velocity. The second line of this template takes the
pbEntries object passed in by your Velocity controller class. Then it's used to
iterate through the list populating the table with phonebook entries.
Note: This tutorial doesn't cover VTL in detail. Refer to the Velocity reference guide
to get in-depth information about this topic (see Resources for a link).
The final step in this process is to add a URL mapping for .vm requests.
<servlet-mapping>
<servlet-name>phonebook</servlet-name>
<url-pattern>*.vel</url-pattern>
</servlet-mapping>
If everything goes fine, your browser page will look like the one shown in Figure 5.
The next section shows you how easy it is to return a PDF made from the contents
of a Web page using Spring MVC's PDF support.
First you have to define a controller to get the list of phonebook entries from a
database table and pass it to the PDF view class, so start developing your PDF
controller.
The next logical step is to define the View class that actually generates the PDF
from your model output.
important method to note in this class is buildPdfDocument. This is where all the
magic happens. Listing 12 shows complete code for generating a PDF for the
Phonebook application.
As you can see, you have to manually create the content for the PDF document. But
Spring's support classes makes it so much easier!
The next step is to define the view resolver for PDF views.
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/*.do">phonebookController</prop>
<prop key="/*.htm">phonebookFlowController</prop>
<prop
key="/*.flow">phonebookFlowController</prop>
<prop
key="/addentry-mvc.act">addEntryFormController</prop>
<prop
key="/home-mvc.act">phonebookHomeController</prop>
<prop
key="/modifyentry-mvc.act">modifyEntryFormController</prop>
<prop
key="/deleteentry-mvc.act">deleteEntryFormController</prop>
<prop
key="/home.vel">phonebookVelocityController</prop>
<prop
key="/home.pdf">phonebookPDFController</prop>
</props>
</property>
</bean>
<bean id="phonebookPDFController"
class="phonebook.pdf.PhonebookPDFController">
<property name="methodNameResolver">
<bean
class="org.springframework.web.servlet.mvc.multiaction.
PropertiesMethodNameResolver">
<property name="mappings">
<props>
<prop
key="/home.pdf">handlePdf</prop>
</props>
</property>
</bean>
</property>
</bean>
If you see the controller class, the view it uses is the same as defined in this
properties class. This is how Spring associates this view class to that controller.
<servlet-mapping>
<servlet-name>phonebook</servlet-name>
<url-pattern>*.pdf</url-pattern>
</servlet-mapping>
Now it's time to build, deploy, and run the application so you can see it in action.
You also need to make sure that you have all the JAR files mentioned in the
readme.txt file in your <WORKSPACE>/phonebook/lib directory. Please read the
instructions in that file carefully, and make sure to copy all the required files into
<WORKSPACE>/phonebook/lib. Note: You can refer to build and pack instructions
in Part 2 of this tutorial series for more information on building and unpacking these
files.
Deploy the phonebook.war using the Deploy New tool in Geronimo. If everything
works as expected, You'll see a message on the Geronimo Web Console saying
Phonebook application deployed successfully. Next, point your browser
to the new page: http://localhost:8080/phonebook/home.pdf. If everything worked as
expected, you should see the PDF in Adobe Acrobat Reader in your browser.
• Clear separation of views and the content that goes into these views
• The ability to separate tasks (using templates with Spring makes it easy
for application developers to concentrate completely on application code
and for Web developers to design the best HTML pages without worrying
about how they will be rendered)
• The ability to change view technologies dynamically
• The ability to test individual view components and pinpoint errors early in
the development cycle
Section 6. Summary
This tutorial has given you a solid introduction to the various view technologies
supported by the Spring MVC. You saw how easy it is to implement these
technologies in your sample Phonebook application. Spring's layered architecture
allows you to introduce only as much functionality as you think your application
needs, and allows you to add more as you get comfortable with a particular
technology.
Using templates to define and manage layouts for views is not new, but using this
technology with Spring is easy. You saw that Spring proves to be a great framework
for taking care of many complex issues for you while providing a simple way to
perform necessary tasks, such as creating PDFs.
Downloads
Description Name Size Download
method
Part 6 source code geronimo.spring6.source.zip 126KB HTTP
Part 6 WAR file geronimo.spring6.war.zip 7,149KB HTTP
Resources
Learn
• The official Spring Reference Manual is a clean and simple way of learning
more about Spring Framework.
• "The Spring series, Part 1: Introduction to the Spring framework"
(developerWorks, June 2005) is another good introduction to the Spring
Framework.
• Check out the article "Simplify Your Web App Development Using the Spring
MVC Framework" to learn how to build a simple stock-trading Web applications
using the Spring Framework.
• Read " The Spring series, Part 3: Swing into Spring MVC" (developerWorks,
September 2005) for a good introduction to Spring MVC.
• Check out another helpful tutorial on Spring MVC basics.
• "Introduction to the Spring Framework" is a thorough write-up by one of the first
and most active members of the Spring design team.
• Peruse this documentation on how to deploy Spring Framework example
applications on Apache Geronimo.
• Get an introduction to classic transactions in "Tour Web Services Atomic
Transaction operations: Beginner's guide to classic transactions, data recovery,
and mapping to WS-AtomicTransactions" (developerWorks, September 2004).
• Read "Optimize your Apache Geronimo distribution" (developerWorks, May
2006) to learn to hone the deployment of your Apache Geronimo distribution to
the necessary core services and applications.
• Check out "Create, deploy, and debug Apache Geronimo applications"
(developerWorks, May 2005) to learn how to use the Eclipse plug-in for
Geronimo.
• Read Martin Fowler's seminal piece "Inversion of Control Containers and the
Dependency Injection pattern."
• Check out the developerWorks Apache Geronimo project area for articles,
tutorials, and other resources to help you get started developing with Geronimo
today.
• Find helpful resources for beginners and experienced users at the Get started
now with Apache Geronimo section of developerWorks.
• Check out the IBM® Support for Apache Geronimo offering, which lets you
develop Geronimo applications backed by world-class IBM support.
• Visit the developerWorks Open source zone for extensive how-to information,
tools, and project updates to help you develop with open source technologies
and use them with IBM's products.
• Browse all the Apache articles and free Apache tutorials available in the
developerWorks Open source zone.
• Browse for books on these and other technical topics at the Safari bookstore.
• Stay current with developerWorks technical events and webcasts.
• Get an RSS feed for this series. (Find out more about RSS.)
Get products and technologies
• Link to download the Spring Framework separately if you want to. You can also
check the Changelog to see what's changed in newer versions.
• Visit the Tomcat home page to learn more about the Tomcat Container. The site
also gives you lots of examples to learn how to deploy your Web applications in
Tomcat.
• Get the Apache Standard taglibs implementing JSTL 1.1.
• Download the latest version of Apache Geronimo.
• Innovate your next open source development project with IBM trial software,
available for download or on DVD.
• Download your free copy of IBM WebSphere® Application Server Community
Edition V1.0 -- a lightweight J2EE application server built on Apache Geronimo
open source technology that is designed to help you accelerate your
development and deployment efforts.
Discuss
• Participate in the discussion forum for this content.
• Stay up to date on Geronimo developments at the Apache Geronimo blog.
• Get involved in the developerWorks community by participating in
developerWorks blogs.
Trademarks
IBM, the IBM logo, and WebSphere are registered trademarks of IBM in the United
States, other countries, or both.
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.