guide to struts

Upload: silly08

Post on 08-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Guide to Struts

    1/25

    www.planetjava.co.uk Introduction to Struts

    1/25

    Introduction and Guide to Struts

    John Hunt

    PlanetJava

    www.planetjava.co.uk

    [email protected]

    Abstract

    Struts is a complex piece of software in its own right. This means that time and effortmust be invested in learning Struts before it can be of benefit. This tutorial explainswhat Struts is and presents some advantages and drawbacks of Struts so that you candetermine 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 alsoexplicitly 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 thislimitation 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 isnot difficult and in fact Struts is to some extent just such an architecture. However, the disadvantageof building your own is that it is not proven, you have to design, test and debug it and others are notfamiliar with it. Struts on the other hand is very widely adopted, is open source (available from theApache organisation) and well tested. However, for simple applications the learning curve presented

    by Struts may outway any benefits obtained! So what should you do? Shouldyou 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.

    http://www.planetjava.co.uk/http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    2/25

    www.planetjava.co.uk Introduction to Struts

    2/25

    2 What is Struts

    Let us start by considering what Jakarta Struts is. The Struts framework can be viewed form anumber of different perspectives, these include:

    1. An open source, reusable framework, available from the Apache Software Foundation. Seehttp://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 applicationdevelopment.

    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 2000when its original creator Craig R. McClanahan donated it to the Apache Software Foundation. Atthat 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 applicationdeveloper easier (at least from within the Struts framework). Thus it now possesses a basicarchitecture 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 webpages sent back to the user.

    Let us take the major feature of Struts and consider it in slightly more detail Struts is animplementation 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 thedisplay, from the business logic, from the handling of user input and is not a new idea. Indeed I firstcame 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 toprovide a structure for building GUI based applications and the idea still holds for Java-based webapplications (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 howthese features may be displayed.

    Figure 1: The Model-View-Controller architecture

    Display/View

    Control ofUser Input

    Information

    Model

    http://struts.apache.org/http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    3/25

    www.planetjava.co.uk Introduction to Struts

    3/25

    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.

    StrutsFront Controller

    Servlet

    ApplicationController

    (Action)

    Model

    (JavaBeans)

    View

    (JSP)

    1. Event(http request)

    2. executes 3. calls behaviour

    4. forwards

    6. Update(http response)

    5. (get information)

    Figure 2: The MVC in Struts

    In the above figure the Struts framework provides a Servlet that receives the initial HTTP requestform 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 shouldbe sent (this is determine based on information loaded form a Struts specific configuration file thatwe 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 doesthis by calling on JavaBeans (or Enterprise JavaBeans) to do this. Once it has completed itsoperations, 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

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    4/25

    www.planetjava.co.uk Introduction to Struts

    4/25

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

    4 Advantages of Struts frameworkStruts is an implementation of the MVC design pattern. However, as I indicated at the start of thistutorial, you can implement your own MVC based architecture (indeed I did so back in 2000). SOwhy 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 allowschanges 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 onthe 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 havingeveryone 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 spaceDivide 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 moremanagement.

    Consistent approach.

    By following the Struts architecture everyone will build their parts of the web application in thesame shared knowledge and shared understanding thus make it easier for others to debug,

    maintain and enhance the system in the future.

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    5/25

    www.planetjava.co.uk Introduction to Struts

    5/25

    5 Disadvantages of Struts framework

    Although there are many advantages to adopting the Struts framework, Struts is not without itsdrawbacks. 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 thedrawbacks 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 is1.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 forthe 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 anotherlanguage to learn for Web development. There is some validity to limiting Java code access inUI 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 thisdoes not prevent the UI developer from going nuts with Java code.

    Complexity

    Separating the problem into parts introduces complexity. There is no question that someeducation 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 andsome 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 webapplications, 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/JSPdocumentation available. There are certainly less books and less web-based guides. Of coursequantity does not necessarily mean quality although in Struts case some of the documentationavailable 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 (atleast 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 implementeverything 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.

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    6/25

    www.planetjava.co.uk Introduction to Struts

    6/25

    6 Installing and Configuring Struts

    Whenever you start with a new framework one of the issues can be getting the thing up and runningin 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.zipfile.

    3. Extract the contents of the ZIP file.

    You can now extract he contents of the struts distribution ZIP file using whatever unzip toolyou 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 Javaenvironment.

    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 theTomcat 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.

    http://localhost:8080/strutsblankhttp://www.winzip.com/http://struts.apache.org/http://jakarta.apache.org/tomcathttp://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    7/25

    www.planetjava.co.uk Introduction to Struts

    7/25

    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 webapplication, 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 canbe 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 applicationare 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 ApplicationThe structure of a Java Web Application as laid out in the Servlet specification is illustrated in thefollowing figure. The boxes highlighted in dark gray are compulsory (although the META -INFdirectory and the Manifest.MF file are automatically created if you Jar this structure up (into a WebARchive 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.

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    8/25

    www.planetjava.co.uk Introduction to Struts

    8/25

    shop

    META-INF

    Manifest.MF

    WEB-INF

    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.

    All html files located at the web application root are visible to the externalweb.

    WEB-INF the contents of this directory is hidden from the web server and contains the classfiles 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 Jared up thenthey 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.xmlfile used to configuration the navigation, validation etc. that will happen within a web application.These files are illustrated in Figure 6.

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    9/25

    www.planetjava.co.uk Introduction to Struts

    9/25

    Figure 5: The struts jars used with a web application

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

    Dont 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 byTomcat. If you copy that to your work area then you will have all the elements you need to getstarted. If you do not have an expanded directory of this sort (not all web servers actually expand theWAR 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-

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    10/25

    www.planetjava.co.uk Introduction to Struts

    10/25

    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 Strutsapplication, it is time to consider the flow-of-control within a Struts application. Understandingthis 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 ithas received it. This is illustrated in the following figure in which more Struts detailed have been

    added.

    JavaBeans

    ApplicationAction

    StrutsFront Controller

    Servlet

    View

    (JSP)

    1. submit

    (requests .do)

    2. executes 3. calls behaviour

    5. forwards

    7. Update(http response)

    6. (get information)

    struts-config.xml

    2. maps request to action

    4. maps result to view

    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

    .do.

    2. When the request for.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 linkrequests 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 nextbased on these return results.

    5. The Servlet then forwards the request on that view so that it can generate the resulting webpage.

    Note that we have simplified the Struts Servlet concept here by implying that it is a single Servlet, itis 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

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    11/25

    www.planetjava.co.uk Introduction to Struts

    11/25

    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-controlelements for you.

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

    1. Plan the navigation and code in XML within the struts-config.xml file.

    2. Create form that invokes .do3. 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 resultsituations.

    2. Create a form that invokes .do

    You will need to define a web page containing a HTML form which action matches the

    .do address of the action. This can be done using a standard HTML form or using theStruts 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 ActionForwardclass 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 fromoutside 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

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    12/25

    www.planetjava.co.uk Introduction to Struts

    12/25

    the Action or the JavaBeans.

    10A 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.1Step 1: Define the navigation elements in struts-config.xmlThe 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.xmlfile in the WEB-INF directory of your file store. We will use this as the basis of our configurationfile. If you open this file in your favourite editor you will find that there are a lot of comments and anumber of different sections to it. Most of this we do not want, delete everything between and exceptfor the element.

    We can now define our action mappings for this web application. In this case there will be only oneas we only have a very simple example to look at. The element contains a list of

    elements. It is these elements that specify which action handles which request. An

    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 which specifies the result value to check for and theview to return. It does this using two attributes name for the return value (form the action) and pathfor 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.

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    13/25

    www.planetjava.co.uk Introduction to Struts

    13/25

    Figure 8: The struts-config.xml file

    Note that in the above example we have placed our JSP view within a directory calledjsps withinthe WEB-INF directory. It will thus only be available to the Struts web application.

    10.2Step 2: Create the form to request the actionWe 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 anyunnecessary 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:

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    14/25

    www.planetjava.co.uk Introduction to Struts

    14/25

    Figure 9: The index.html page

    10.3Step 3: Create an Action ObjectNext 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 processingresponse- 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:

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    15/25

    www.planetjava.co.uk Introduction to Struts

    15/25

    Figure 10: The simple WelcomeAction class

    In the above example, the execute method merely prints out a welcoming message (to the Tomcatstandard output) and returns a value back to the struts framework that indicates successful

    processing of the request.

    10.4Step 4: Create the JSP ViewFinally, 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 thejsps

    directory under the WEB-INF directory. This JSP is illustrated below.

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    16/25

    www.planetjava.co.uk Introduction to Struts

    16/25

    Figure 11: A simple JSP View

    10.5Step 5: Installing on TomcatWe 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 yourweb 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 beendeveloping across to the your /webapps/HelloStrutsWorld directory. You

    will also need to copy your HTML page to the HelloStrutsWorld directory. Thus in addition to theStruts 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.6Step 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:

    http://localhost:8080/HelloStrutsWorld/index.htmlhttp://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    17/25

    www.planetjava.co.uk Introduction to Struts

    17/25

    Figure 12: The inidex.html web page

    Note that in Tomcat that the name of the web application, by default, is the directory within whichthe 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 actionto 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:

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    18/25

    www.planetjava.co.uk Introduction to Struts

    18/25

    Welcome

    Action

    StrutsFront Controller

    Servlet

    welcome.jsp

    1. submit

    (requests welcome.do)

    2. executes

    3. returns "success"

    5. forwards

    7. Update(http response)

    struts-config.xml2. maps request to action

    4. maps result to view

    index.html

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

    11Extending 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.

    12The Bookstore Example

    In the bookstore example we will allow the user to enter data into a HTML form. This data will thenbe used to populate a Form Bean (called Book) and passed over to our Action classs execute

    method.12.1Step 1: Modify the input formAgain 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 allactions to be grouped together. The resulting index.html web page is presented below.

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    19/25

    www.planetjava.co.uk Introduction to Struts

    19/25

    Figure 15: The modified index.html page

    12.2Step 2: Modify the struts-config.xml fileWe must now update the struts-config.xml file. As you willrememberthis file handles thenavigation elements of the application, however it is more than just a navigation specification it isthe 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 theAction 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 element. This element contains one or more

    elements. This element defines a form bean. Thus:

    defines a list of beans to use to pass data from forms.

    defines a single bean with a name and a class. The name and class are defined asattributes on the form-bean element:

    namedefines the name by which the form bean will be referenced within the struts-

    config.xml filetype 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 withdata 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 elements.

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    20/25

    www.planetjava.co.uk Introduction to Struts

    20/25

    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 wenow 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 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.3Step 3: The Book Form BeanThis 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

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    21/25

    www.planetjava.co.uk Introduction to Struts

    21/25

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

    Figure 17: The Book Form Bean Class

    12.4Step 4: The PurchaseAction classNext 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 ReceiptJavaBean 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 belowand the Receipt result bean class is presented in Figure 19.

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    22/25

    www.planetjava.co.uk Introduction to Struts

    22/25

    Figure 18: The PurchaseAction class

    Figure 19: The Receipt Results Bean

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    23/25

    www.planetjava.co.uk Introduction to Struts

    23/25

    12.5Step 5: The View JSPsIn 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 returnssuccess. 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 Strutstag 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 tagitself you specify the name of the bean to access and the name of the property on that bean (as

    illustrate din line 18 ofFigure 21). Note that the name of the bean is the name under which theresults bean was placed in the request object by the Action class.

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    24/25

    www.planetjava.co.uk Introduction to Struts

    24/25

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

    12.6Step 6: Installing and running the struts application

    We can now compile all the java classes and install the application as before on Tomcat. Note thatall the Java classes must be placed in the appropriate class directory ( or if Jard 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

    http://www.planetjava.co.uk/
  • 8/7/2019 Guide to Struts

    25/25

    www.planetjava.co.uk Introduction to Struts

    25/25

    Figure 23: The success bookbought view

    13References

    [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 (2ndEd.), OReilly, 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.

    http://www.planetjava.co.uk/