Você está na página 1de 25

www.planetjava.co.

uk Introduction to Struts

Introduction and Guide to Struts


John Hunt

PlanetJava
www.planetjava.co.uk
jjh@midmarsh.co.uk

Abstract
Struts is a complex piece of software in its own right. This means that time and effort
must be invested in learning Struts before it can be of benefit. This tutorial explains
what Struts is and presents some advantages and drawbacks of Struts so that you can
determine whether it is of interest to you. It then takes you step by step through the
installation of Struts and the development of two simple Struts applications. It also
explicitly describes the flow-of-control within Struts and these applications in particular
to aid your understanding.

1 Introduction
Java provides a number of technologies for building web-based applications. These include
Servlets, JSP (Java Server Pages), JSF (Java Server Faces) and JSTL (JSP Standard Tag Library).
However, none of these technologies provides a solution for how to structure web applications
(actually JSF is moving in that direction but we will ignore this for now). To overcome this
limitation many people have developed frameworks that allow standard architectures to be
employed to help structure these applications. In my own case, I was involved in developing a
Model-View-Controller (MVC) based architecture back in 2000. Building your own architecture is
not difficult and in fact Struts is to some extent just such an architecture. However, the disadvantage
of building your own is that it is not proven, you have to design, test and debug it and others are not
familiar with it. Struts on the other hand is very widely adopted, is open source (available from the
Apache organisation) and well tested. However, for simple applications the learning curve presented
by Struts may out way any benefits obtained! So what should you do? Should you use Struts?
In this tutorial we will consider what struts is, what it offers, its drawbacks and how it works. We
will also look at how to install Struts on Tomcat and how to write some simple Struts based web
applications.

1/25
www.planetjava.co.uk Introduction to Struts

2 What is Struts
Let us start by considering what Jakarta Struts is. The Struts framework can be viewed form a
number of different perspectives, these include:
1. An open source, reusable framework, available from the Apache Software Foundation. See
http://struts.apache.org
2. An implementation of the MVC design pattern.
3. A collection of utilities, that handle many of the most common tasks in Java web application
development.
4. A set of JSP custom tag libraries that simplify many common JSP operations.
Why can it be viewed form so many different angles? Essentially, because it has evolved since 2000
when its original creator Craig R. McClanahan donated it to the Apache Software Foundation. At
that time it was essentially an MVC based framework for building web applications, however as it
has been used, more and more useful features have been added to it to make web application
developer easier (at least from within the Struts framework). Thus it now possesses a basic
architecture and workflow that standardise the construction of Java web applications, a set of
utilities that provide for common operations and JSP tags that simplify the generation of the web
pages sent back to the user.
Let us take the major feature of Struts and consider it in slightly more detail – “Struts is an
implementation of the MVC design pattern”. What does this mean? The MVC design pattern (or the
Model-View-Controller design pattern to give it its full name) relates to the separation of the
display, from the business logic, from the handling of user input and is not a new idea. Indeed I first
came across the MVC architecture (as it was then called) back in 1988 [Krasner and Pope 1988]
while I was working with an object-oriented language called Smalltalk. The basic idea was to
provide a structure for building GUI based applications – and the idea still holds for Java-based web
applications (albeit with a very different implementation).
The intention of the MVC architecture is the separation of the user display, from the control of user
input, from the underlying information model as illustrated in following figure. There are a number
of reasons why this is useful:

• Reusability of application and / or user interface components,


• Ability to develop the application and user interface separately,
• Ability to inherit from different parts of the class hierarchy.
• Ability to define control style classes that provide common features separately from how
these features may be displayed.

Display/ Control of
View User Input

Information
Model

Figure 1: The Model-View-Controller architecture

2/25
www.planetjava.co.uk Introduction to Struts

This means that different interfaces can be used with the same application, without the application
knowing about it. It also means that any part of the system can be changed without affecting the
operation of the other. For example, the way that the graphical interface (the look) displays the
information could be changed without modifying the actual application or how input is handled (the
feel). Indeed the application need not know what type of interface is currently connected to it at a ll.
Inturn the information model can be modified without the control or view aspects altering.

3 Struts and the MVC


Struts implements a version of the MVC pattern. It thus offers a Controller, Model and View
concept. Indeed in any Struts application you will have:

• At least one controller


• A model for data / accessing functionality / executing business logic etc.
• A view (implemented using JSP or another presentation technology such as JSF, XSLT,
Velocity Templates etc.)
• A Struts XML configuration file

The Model-View-Controller aspects of the Struts framework are illustrated in the figure below.

Application
2. executes Controller 3. calls behaviour
(Action)
1. Event
(http request) Struts
Front Controller Model
Servlet (JavaBeans)

4. forwards View 5. (get information)


(JSP)

6. Update
(http response)

Figure 2: The MVC in Struts


In the above figure the Struts framework provides a Servlet that receives the initial HTTP request
form a client browser. This Servlet implements the Front Controller pattern from the J2EE Design
Patterns [Alur, Crupi and Malks 2001]. This “front controller” determines where the request should
be sent (this is determine based on information loaded form a Struts specific configuration file that
we will look at later). It then sends the request onto the Controller part of the MVC pattern. This
application specific controller is implemented as an Action within the Struts framework. The
Action then determines what business logic / application functionality should be executed. It does
this by calling on JavaBeans (or Enterprise JavaBeans) to do this. Once it has completed its
operations, the Action returns a status code that the Struts Servlet then uses to determine which
view to display. Once it has done this it forwards the initial HTTP request onto the appropriate view
that may or may not retrieve information form the JavaBeans processed by the Action. The resulting

3/25
www.planetjava.co.uk Introduction to Struts

HTML page is then returned to the requesting browser. In this case the view has been implemented
by a JSP file. There is no flow logic, no business logic, and no model information in the view -- just
tags. Note that this means that you must write a JSP containing Struts tags to provide the GUI.

4 Advantages of Struts framework


Struts is an implementation of the MVC design pattern. However, as I indicated at the start of this
tutorial, you can implement your own MVC based architecture (indeed I did so back in 2000). SO
why should you and I now use Struts rather than a home grown, do it yourself approach?
There are a number of very good reasons why you should adopt Struts, these include:
• Centralized configuration and control.
The use of centralized file-based configuration using XML and property files. This allows
changes to be made to the structure of the application, the flow of control and even field
validation, without modifying any Java code (and thus without the need to recompile anything).
• FormBeans
The use of Form Beans greatly simplifies the access of data input by the user in web pages,
within the Java elements of the web application. Essentially, form beans present any data input
as a single Java object from which data can be extracted directly (using get methods).
• Use of JSP tag mechanism
The tag feature promotes reusable code and abstracts Java code from the JSP file. This feature
allows nice integration into JSP-based development tools that allow authoring with tags.
• Tag library
Why re-invent the wheel, or a tag library? If you cannot find something you need in the library,
contribute. In addition, Struts provides a starting point if you are learning JSP tag technology.
• Form field validation – for automatic checking of the data entered and user notification (all on
the client side without the need to write any JavaScript yourself).
• Open source
You have all the advantages of open source, such as being able to see the code and having
everyone else using the library reviewing the code. Many eyes make for great code review.
• Sample MVC implementation
Struts offers some insight if you want to create your own MVC implementation.
• Manage the problem space
Divide and conquer is a nice way of solving the problem and making the problem manageable.
Of course, the sword cuts both ways. The problem is more complex and needs more
management.
• Consistent approach.
By following the Struts architecture everyone will build their parts of the web application in the
same – shared knowledge and shared understanding thus make it easier for others to debug,
maintain and enhance the system in the future.

4/25
www.planetjava.co.uk Introduction to Struts

5 Disadvantages of Struts framework


Although there are many advantages to adopting the Struts framework, Struts is not without its
drawbacks. If you are considering adopting Struts for any web application, then it is as well to
understand its drawbacks as to understand its advantages. Thus in this section we will consider the
drawbacks of Struts.
• Change
The Struts framework, at times, has undergone a rapid amount of change. A great deal of
change occurred between Struts 0.5 and 1.0. At the time of writing the current Struts release is
1.2.7 exactly how Struts will develop in the future is an open question (although of course
being open source software you can have your say).
• Correct level of abstraction
Does Struts provide the correct level of abstraction? What is the proper level of abstraction for
the page designer? That is the $64K question. Should we allow a page designer access to Java
code in page development? Some frameworks like Velocity say no, and provide yet another
language to learn for Web development. There is some validity to limiting Java code access in
UI development. Most importantly, give a page designer a little bit of Java, and he will use a
lot of Java. Struts helps limit the amount of Java code required in a JSP file via tag libraries.
One such library is the Logic Tag, which manages conditional generation of output, but this
does not prevent the UI developer from going nuts with Java code.
• Complexity
Separating the problem into parts introduces complexity. There is no question that some
education will have to go into understanding Struts if you are adopting it as the basis of your
web application development approach. It also means that there is a bigger learning curve to
climb. If you are doing it yourself, then you may need to learn Java, Servlets, JSPs, JSTL and
some XML. With Struts you need to understand these and then start to look at Struts – an API
which is nearly as large as these in its own right. In addition for simple or small web
applications, the overheads introduced by Struts may out weight any benefits you may gain.
However, for larger or longer lived applications Struts is likely to offer significant advantages.
• Documentation
This is varied and of course there is less Struts specific documentation that Servlet/JSP
documentation available. There are certainly less books and less web-based guides. Of course
quantity does not necessarily mean quality although in Struts case some of the documentation
available directly from Apache can be left a little wanting. However, there are some excellent
books available (such as [Cavaness 2004]).
• Less Transparent
If you create your own framework then you know exactly what is happening all the time (at
least in theory). However, when you first start with Struts it can all seem a bit like magic
(particularly if you are not clear on the workflow that happens within Struts). However, even
when you know what Struts is doing, it is doing more for you then if you implement
everything yourself. Thus it can be harder to understand / debug /maintain as well as optimize.
Indeed while creating the examples ofr this tutorial I kept getting a null pointer exception in
one example, which turned out to be caused by a typo in at the Struts XML configuration file.

5/25
www.planetjava.co.uk Introduction to Struts

6 Installing and Configuring Struts


Whenever you start with a new framework one of the issues can be getting the thing up and running
in the first place. We will therefore step through setting up Struts within a Web application server.
In our case we shall use Tomcat as it is both freely available and simple to use.
1. Download and install a Servlet/JSP compliant web application server e.g. Tomcat
You must therefore first have obtained and installed Tomcat (see
http://jakarta.apache.org/tomcat) or another J2EE compliant web server (such as
WebLogic, Jetty, WebSphere etc.).
2. Download the Struts distribution file.
Next you need to down load the current Struts .zip file. You can obtain this from the Struts
home page (see http://struts.apache.org) - look for the download links and select to
download the Binary distribution. This will take you to a page from which you can download
the current Struts release. At the time of writing this means downloading the struts-1.2.7.zip
file.
3. Extract the contents of the ZIP file.
You can now extract he contents of the struts distribution ZIP file using whatever unzip tool
you use (for example WinZIP see http://www.winzip.com). Place the contents of the Struts
ZIP file somewhere appropriate (personally I put all these downloads into a directory called
javalibs so that I can easily find them).
4. XML Parser
If you are using JDK 1.3 or earlier then you will also need to obtain an XML parser. However,
if you are using JDK 1.4 or newer then this is already available to you within the Java
environment.
5. Install a sample Struts Web Application on Tomcat
We will now install a simple Struts application on Tomcat to make sure everything works. To
do this look in the struts directory that you just extracted for a directory called webapps. In
my case this is C:\javalibs\struts-1.2.7\webapps. In this directory find a file called “struts-
blank.war”. The .war extension stands for Web Archive (in a similar manner to .jar which
stands for Java Archive). Copy this file to your Tomcat installations’ webapps directory (for
example: C:\jakarta-tomcat-4.1.31\webapps
6. Startup Tomcat
You should now startup Tomcat (this can be done by moving into the bin directory of the
Tomcat installation and typing “startup” at the command prompt).
7. Access the web application.
Once Tomcat has started up open a browser window and enter the following URL:
http://localhost:8080/struts-blank
You should then see the following page displayed. If you see this page then you have
successfully installed a Struts based web application on Tomcat.

6/25
www.planetjava.co.uk Introduction to Struts

Figure 3: Running the Struts-Blank web application

7 Struts Applications
Before we can start to think about creating Struts based Java web applications, we need to consider
how Java-based web applications are constructed. This is because, at the end of the day, Struts is a
Java-based web application. The Servlet 2.2 specification introduced the notion of a web
application, which has been further refined in the 2.3 and 2.4 specifications. Each web application
has:

• an identity (a name and a root URL, welcome pages etc.)


• its own Servlet context (an object shared amongst all Servlets in the web application that can
be used for application data).
• all resources needed for the application in the web-tier: Servlet classes, JSP files, gif files,
HTML files, deployment descriptors.
• XML deployment descriptors used to define the application and how logical resources
should be mapped to actual environment resources.
• the option of specifying a security domain and indicating which parts of the web application
are to be included in the server security domain.
• A specific directory structure that is used to allow the web container to find the various
elements of the web application.

7.1 Structure of a Web Application


The structure of a Java Web Application as laid out in the Servlet specification is illustrated in the
following figure. The boxes highlighted in dark gray are compulsory (although the META-INF
directory and the Manifest.MF file are automatically created if you Jar this structure up (into a Web
ARchive or WAR file) and are not required if you use the structure in its expanded form with, for
example Tomcat). The boxes in light gray are application specific.

7/25
www.planetjava.co.uk Introduction to Struts

shop

META-INF WEB-INF <html files>

Manifest.MF classes lib web.xml

webshop

WelcomeServlet.class

Figure 4: Web Application Structure


The elements presented in Figure 1 define the web application to the web container (for example
Tomcat). The elements are:

• shop the root directory for the web application. The name of this directory is defined in the
web application context in Tomcat.
• <html files> All html files located at the web application root are visible to the external
web.
• WEB-INF the contents of this directory is hidden from the web server and contains the class
files defining the Servlets and any supporting classes. Any JAR files used by the web
application should be placed within the lib directory. If the class files are not Jar’ed up then
they must be placed within the classes sub directory. For example in Error! Reference
source not found., the webshop package containing the WelcomeServlet class.
• web.xml this file is an xml file that defines mappings between URLs and Servlets and JSPs.
It can also specify filters to apply, security domains, session timeouts etc.

Struts modifies this structure by adding its own files into the architecture. Primarily it adds the struts
jar files to the lib directory (where they will be picked up by the Tomcat environment) as illustrated
in Figure 5. Struts also requires a number of Tag Library definitions files and XML files to be
placed in the WEB-INF directory of a web application. These files include the struts-config.xml
file used to configuration the navigation, validation etc. that will happen within a web application.
These files are illustrated in Figure 6.

8/25
www.planetjava.co.uk Introduction to Struts

Figure 5: The struts jars used with a web application

Figure 6: The struts-config.xml and tag library definitions


Don’t worry if by this stage you are thinking “how am I going to set all this up” there is an easy
short cut. You can copy the struts-blank web application directory structure just created for you by
Tomcat. If you copy that to your work area then you will have all the elements you need to get
started. If you do not have an expanded directory of this sort (not all web servers actually expand the
WAR file in this way) then you can expand it manually by using:
jar –xvf struts-blank.war
Although you may be tempted to do this within the struts-blank directory I would suggest you avoid
it. Instead, create your own directory say “HelloStrutsWorld” and copy the contents of the struts-

9/25
www.planetjava.co.uk Introduction to Struts

blank directory into this. It will make things easier later on.

8 Basic Flow of Control in a Struts Application


Now that you have successfully installed Struts and examine what you need within a Struts
application, it is time to consider the “flow-of-control” within a Struts application. Understanding
this will help you understand what we need to implement and where those components fit into the
picture as a whole. It is also the area where those new to Struts can get the most confused. The most
important thing to remember is that it is Struts which receives the initial HTTP request from a
browser and that it is the struts-config.xml file that tells Struts where to send that request once it
has received it. This is illustrated in the following figure in which more Struts detailed have been
added.

2. executes Application
3. calls behaviour
Action

1. submit 2. maps request to action


(requests <...>.do)
Struts
Front Controller struts-config.xml JavaBeans
Servlet 4. maps result to view

5. forwards View 6. (get information)


(JSP)

7. Update
(http response)

Figure 7: Basic flow-of-control within Struts


In this figure the Struts specific additions are marked in bold, in particular they are:

1. When data is sent to the Struts framework from a browser the action requested is
<something>.do.
2. When the request for <something>.do is received by the Struts Servlet, this Servlet looks up
the set of mappings provided by the struts-config.xml file. The mappings in this file link
requests to Actions. The Struts Servlet then calls the execute method on the appropriate
action object.
3. When this execute method terminates it returns a result indicating what should happen next
(for example it might return “success” or “failure”).
4. The mappings in the struts-config.xml file indicate which View should be displayed next
based on these return results.
5. The Servlet then forwards the request on that view so that it can generate the resulting web
page.

Note that we have simplified the Struts Servlet concept here by implying that it is a single Servlet, it
is not – the Struts framework is quiet complex, but it makes life easier to view what Struts is doing
as a single front controller type Servlet. Also note that there is nothing magic about Struts – it is

10/25
www.planetjava.co.uk Introduction to Struts

doing exactly what you tell it to do. You write the configuration file, you right the Action objects,
the JavaBeans and the Views. It is just that Struts does the coordination or “flow-of-control”
elements for you.

9 Steps to create a Struts Application


Now that we know how Struts works we can look at what Steps are required to create a Struts
Application. We will start off by considering the basic steps that will be needed for almost all Struts
web applications, these are:

1. Plan the navigation and code in XML within the struts-config.xml file.
2. Create form that invokes <something>.do
3. Define a form bean (if you have data to submit)
4. Create an Action object to handle the request.
5. Define a results bean (if you need to pass data to the view form the action)
6. Create a JSP view to return to the user

We will look at each of these steps in more detail below:

1. Plan the navigation.


You need to determine which action classes will handle which <…>.do requests. You also need to
determine which views are displayed in different result situations.

2. Create a form that invokes <something>.do


You will need to define a web page containing a HTML form which action matches the
<something>.do address of the action. This can be done using a standard HTML form or using the
Struts form tags.

3. Define a form bean


Form beans are used to pass data form a HTML form to the Action object. These Form Beans are
special JavaBeans that must extend the ActionForm class.

4. Create an Action Object.


An Action Object handles the request received by Struts. It is the “control” aspect of the MVC. That
is, given the input passed to it by the FormBean, what should happen next. It is a bit like an event
handler within the Swing architecture of a desktop Java GUI application. It must extend the Action
class and return an instance of the ActionForward class to indicate what should happen next.

5. Define a Results Bean


If any data should be passed onto the view then it must be made available to that view. A results
bean is a standard JavaBean that is added to the HTTP request and thus accessible within the JSP.

6. Create a JSP View


Finally, you can create the resulting view (or views). These are usually placed within a directory
within the WEB-INF directory of a web application so that they are not directly accessible from
outside of the Struts framework. This is because they rarely have meaning on their own as they are
intended only for presentation purposes with all business logic and processing occurring either in

11/25
www.planetjava.co.uk Introduction to Struts

the Action or the JavaBeans.

10 A Hello World style Struts Example


We now know what we need to do to create a simple Struts application, so lets have a go at creating
one.
10.1 Step 1: Define the navigation elements in struts-config.xml
The first thing we need to do is to define our struts-config.xml file. If you have followed my advice
and based this application on the struts-blank web application, you should find a struts-config.xml
file in the WEB-INF directory of your file store. We will use this as the basis of our configuration
file. If you open this file in your favourite editor you will find that there are a lot of comments and a
number of different sections to it. Most of this we do not want, delete everything between <struts-
config> and </struts-config> except for the <action-mapping> element.
We can now define our action mappings for this web application. In this case there will be only one
as we only have a very simple example to look at. The <action-mapping> element contains a list of
<action> elements. It is these elements that specify which action handles which request. An
<action> element has a number of attributes and sub elements. The primary attributes are:
path which indicates the URL that will be sent to Struts for this action to be performed.
type which specifies the fully qualified class name of the action to execute.
name which specifies the name of a form bean to use to pass data to the action (which we will
omit for the moment).
The sub-element we will look at is <forward> which specifies the result value to check for and the
view to return. It does this using two attributes name for the return value (form the action) and path
for the view to return.
Our very simple Struts example illustrates these ideas. In our case we will associated “welcome”
with a “uk.co.Experis.booksotre.WelcomeAction” object, and a result of “success” with a
welcome.jsp view. This is illustrated below.

12/25
www.planetjava.co.uk Introduction to Struts

Figure 8: The struts-config.xml file

Note that in the above example we have placed our JSP view within a directory called jsps within
the WEB-INF directory. It will thus only be available to the Struts web application.
10.2 Step 2: Create the form to request the action
We now need to create a HTML form that will request the Struts framework to execute the
WelcomeAction (we have yet to define). We could use the Struts form tag but as the standard
HTML form is rather more widely known (and in a bid to minimize the introduction of any
unnecessary complexity for the time being) we shall adopt it. Thus we will define a very simple
HTML form whose action attribute specifies welcome.do. Note that the form specifies the action
with a .do extension but that the struts-config.xml action mapping does not.

The HTML form we have defined will be in a file called index.html (just to make things as simple
as possible). Note that we have used the POST method but the GET method could have been used
with the form. The HTML page containing the form is presented below:

13/25
www.planetjava.co.uk Introduction to Struts

Figure 9: The index.html page

10.3 Step 3: Create an Action Object


Next we must define the class whose instance will be used to handle the processing of the request.
We will call this class WelcomeAction. It must extend the class
org.apache.struts.action.Action
and it must implement a method called execute with the following signature:
public ActionForward execute(ActionMapping mapping,
ActionForm form,
javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws java.lang.Exception
Where:
mapping - The ActionMapping used to select this instance
form - The optional ActionForm bean for this request (if any)
request - The HTTP request we are processing
response - The HTTP response we are creating

The execute method must process the specified HTTP request and can obtain the data passed to it
via the ActionForm bean (if one is available). Note it also has access to the original request and
response objects. This is illustrate din the following example:

14/25
www.planetjava.co.uk Introduction to Struts

Figure 10: The simple WelcomeAction class

In the above example, the execute method merely prints out a welcoming message (to the Tomcat
standard output) and returns a value back to the struts framework that indicates successful
processing of the request.

10.4 Step 4: Create the JSP View


Finally, we can define the resulting JSP View. This is an extremely simple JSP that merely presents
a welcome screen back to the user. This JSP is called welcome.jsp and is stored in the jsps
directory under the WEB-INF directory. This JSP is illustrated below.

15/25
www.planetjava.co.uk Introduction to Struts

Figure 11: A simple JSP View

10.5 Step 5: Installing on Tomcat


We are now ready to install the web application on Tomcat. We must of course compile the
WelcomeAction.java class before doing this. There is nothing special about this as it should be
compiled as normal with javac (or via your favourite IDE). Once this is done you need to copy your
web application directory structure to Tomcat. Do this by creating a directory under webapps within
Tomcat called HelloStrutsWorld. Now copy the WEB-INF directory where you have been
developing across to the your <Tomcat-installation>/webapps/HelloStrutsWorld directory. You
will also need to copy your HTML page to the HelloStrutsWorld directory. Thus in addition to the
Struts framework you should end up with:

../webapps/HelloStrutsWorld/index.html
../webapps/HelloStrutsWorld/WEB-INF/struts-config.xml
../webapps/HelloStrutsWorld/WEB-IN/classes/uk/co/experis/bookstore/WelcomeAction.class
../webapps/HelloStrutsWorld/WEB-INF/jsps/welcome.jsp

10.6 Step 6: Running the example


If we now startup Tomcat and enter the URL of the index.html page into a web browser:

http://localhost:8080/HelloStrutsWorld/index.html

Then we should see the following web page displayed:

16/25
www.planetjava.co.uk Introduction to Struts

Figure 12: The inidex.html web page


Note that in Tomcat that the name of the web application, by default, is the directory within which
the web application is defined. Thus if you called your directory something other than
HelloStrutsWorld, then the URL you entered will need to be modified accordingly.

If we now click on the “Enter” button, which will send a request to Struts for the welcome.do action
to be performed, then we will see the next web page displayed:

Figure 13: The JSP View

Thus the request has been sent to Struts, Struts mapped this request to the WelcomeAction (have a
look at the Tomcat output window for the WelcomeAction.execute() printout), which returned a
“success” result which caused Struts to request the welcome.jsp page to be displayed. This flow-of-
control is illustrated below for this web application:

17/25
www.planetjava.co.uk Introduction to Struts

Welcome
Action
2. executes

3. returns "success"

1. submit
Struts 2. maps request to action
(requests welcome.do)
Front Controller struts-config.xml
Servlet 4. maps result to view

index.html
5. forwards welcome.jsp

7. Update
(http response)

Figure 14: Flow-of-control within simple struts application example

11 Extending our Example


The simple example we have just examined works, but it does not involve many of the important
benefits of Struts. That is, it does enforce a
• centralized file-based configuration
• consistent approach
But it does not use any form beans to pass data to the action object, HTML tags for creating forms,
form field validators or results beans. In the next example, we will take this a bit further and
introduce form and result beans.

12 The Bookstore Example


In the bookstore example we will allow the user to enter data into a HTML form. This data will then
be used to populate a Form Bean (called Book) and passed over to our Action class’s execute
method.
12.1 Step 1: Modify the input form
Again we will use the standard HTML form. However, this time the form will have three fields,
“title”, “author” and “price”. These three fields will be standard text fields. In addition we will
change the action to be called to be one of called “purchase” and thus the action element of the form
will call purchase.do. We will take this further and add actions to the URL to make it
actions/purchase.do. This is a standard convention within Struts development and allows all
actions to be grouped together. The resulting index.html web page is presented below.

18/25
www.planetjava.co.uk Introduction to Struts

Figure 15: The modified index.html page

12.2 Step 2: Modify the struts-config.xml file


We must now update the struts-config.xml file. As you will remember this file handles the
navigation elements of the application, however it is more than just a navigation specification – it is
the Struts configuration file. It is there here that we also define any form beans that will be used. In
our case, we now have three items of information that must be passed form a HTML form to the
Action object. The first thing we must do is to define a form bean that will be used with this form.

Form beans are defined within the <form-beans> element. This element contains one or more
<form-bean> elements. This element defines a form bean. Thus:

<form-beans> defines a list of beans to use to pass data from forms.


<form-bean> defines a single bean with a name and a class. The name and class are defined as
attributes on the form-bean element:
name defines the name by which the form bean will be referenced within the struts-
config.xml file
type specifies the fully qualified class name of the bean.

In Figure 16 a form bean called book is defined which will be an instance of the class
uk.co.Experis.bookstore.Book. Notice that this merely defines a form bean that can be used with
data input from a form. It does not specify which form will provide that data nor which actions will
use it. This is done within the <action> elements.

19/25
www.planetjava.co.uk Introduction to Struts

Figure 16: The modified struts-config.xml file


Once the form bean has been defined we can move onto defining an action mapping for the
/action/puchase.do event. This is done in the same way as before except that the path is now
/action/puchase and the type is now uk.co.Experis.bookstore.PurchaseAction. In addition we
now have the name attribute. This specifies the name of the form bean to be populated from the
information sent from the form calling the /actions/puchase.do action. This is the link from the
definition of the form bean, to the point at which it is used. The instance of the Book class will be
passed into the PurchaseAction.execute() method.

The other difference in this action compared to the previous WelcomeAction is that it has two
outcomes. One for “success” and one for “failure”. There are therefore to <forward> elements, on
for each result. The “success” outcome is mapped to the bookbought.jsp and the “failure” outcome
is mapped to the bookfailure.jsp.

12.3 Step 3: The Book Form Bean


This class will be used to pass data form the HTML form to the Action class. It must extend the
ActionForm class as the argument to the execute method is expected to be of type ActionForm.
This can then be cast to an object of type Book inside the method. This will allow the get methods
to be used to obtain the data it holds. The implementation class, Book, must support the usual
JavaBean criteria. That is, it must have a zero parameter constructor and it must have set and get

20/25
www.planetjava.co.uk Introduction to Struts

methods for all properties. The actual Book Form Bean class I presented below.

Figure 17: The Book Form Bean Class

12.4 Step 4: The PurchaseAction class


Next we need to write our Action class. This time the class is to be called PurchaseAction. It will
receive an ActionForm object which will be cast to a Book – thus allowing the data entered to be
retrieved. If a book title has been omitted a “failure” status will be returned. Otherwise a Receipt
JavaBean will be instantiated and made available to the JSP view that will handle “success”. This is
done by placing the JavaBean onto the request object. The new PurchaseAction is illustrated below
and the Receipt result bean class is presented in Figure 19.

21/25
www.planetjava.co.uk Introduction to Struts

Figure 18: The PurchaseAction class

Figure 19: The Receipt Results Bean

22/25
www.planetjava.co.uk Introduction to Struts

12.5 Step 5: The View JSPs


In this Struts application we have two JSP views, one for “success” and one for “failure”. The very
simple “failure” JSP is called bookfailure.jsp and is illustrated in Figure 20. This JSP merely
presents a message to the user.

Figure 20: The very simple bookfailure.jsp view

The more complex bookbought.jsp is displayed if the execute method of the Action returns
“success”. This JSP accesses the Receipt result bean and displays information it holds. It does this
using the bean:write tag provided as part of the Struts tag libraries (not using standard JSP
useBean and getProperty tags you could achieve the same effect as bean:write however the Struts
tag is more elegant). This is the more common approach when using Struts. It does require that the
Struts bean tag library is included in the JSP (see line 4 in Figure 21). To use the bean:write tag
itself you specify the name of the bean to access and the name of the property on that bean (as
illustrate din line 18 of Figure 21). Note that the name of the bean is the name under which the
results bean was placed in the request object by the Action class.

23/25
www.planetjava.co.uk Introduction to Struts

Figure 21: The bookbought.jsp using bean:write tags

12.6 Step 6: Installing and running the struts application


We can now compile all the java classes and install the application as before on Tomcat. Note that
all the Java classes must be placed in the appropriate class directory (or if Jar’d up in the lib
directory). The result of running this application (in a directory ../webapps/bookstore) is illustrated
in Figure 22and Figure 23.

Figure 22: The revised index.html page

24/25
www.planetjava.co.uk Introduction to Struts

Figure 23: The “success” bookbought view

13 References
[Alur, Crupi and Malks 2001] D. Alur, J. Crupi and D. Malks, Core J2EE Patterns: Best Practices
and Design Strategies, Prentice Hall, 0-13-064884-1, 2001.
[Cavaness 2004] C. Cavaness, Programming Jakarta Struts (2nd Ed.), O’Reilly, 0-596-00651-9,
2004.
[Krasner and Pope 1988] G. E. Krasner and S. T. Pope, A Cookbook for Using the Model-View
Controller User Interface Paradigm in Smalltalk-80, JOOP 1(3), pp. 26-49, 1988.

25/25

Você também pode gostar