Struts How-To

Struts - A Quick How-To

By: Abdul Habra

Version: 0.12

Date: July 19, 2002

Table Of Contents

1 Introduction

1.1 Development Platform

1.2 Prerequisites

1.3 Struts Application Creation Steps

2 Creating The Application

2.1 Determine Form's Name

2.2 Determine Data Entry Fields

2.3 Create Blank Struts Application

2.4 Create Form Class

2.5 Create Action Class

2.6 Create JSP Form Page

2.7 Create Response Page

2.8 Review web.xml

2.9 Update struts-config.xml

2.10 Run JSP Form Page

3 Validation

3.1 Modify JSP Form Page

3.2 Modify struts-config.xml

3.3 Add Error Messages To ApplicationResources.properties

3.4 Add validate() Method To Bookform.Java

3.5 Run JSP Form Page

4 Conclusion

5 References

1 Introduction

This document describes how to create a simple form-based Struts application. From a user's perspective, the application consists of the following:

    1. A data entry form.

    2. When the user clicks on a "submit" button, another page will be displayed informing the user that the data was saved.

    3. No actual saving of data occurs.

    4. We will start with a form without any validation, and then add validation in section 3.

The following two figures show the desired pages:

This document does not explain the theoretical background of Struts (e.g. MVC), nor try to convince the reader to use Struts. Please refer to the references section to learn more about Struts.

1.1 Development Platform

We will develop the application on a machine configured with the following:

    1. Windows 2000.

    2. JSDK 1.3.

    3. Tomcat 3.3.1 installed in a directory that we would denote %TOMCAT_HOME%.

    4. Struts 1.0.2.

1.2 Prerequisites

Reader should be familiar with:

    1. Java.

    2. HTML.

    3. JSP.

    4. Java Beans.

    5. The concepts of Model-View-Controller (MVC).

1.3 Struts Application Creation Steps

Creating a Struts application (with a form) consists of the following steps:

    1. Determine the form's name: For example "book".

    2. Determine data entry fields: Name and type of each field, for example "title" and "author".

    3. Create a blank Struts application.

    4. Create Form class: A Java bean. For example BookForm.java.

    5. Create Action class: For example BookAction.java.

    6. Create a JSP form page: To accept data entry. For example testJsp.jsp.

    7. Create a response page: To indicate that data was saved. For example savedOk.jsp.

    8. Review web.xml: This is an optional step to see how Tomcat maps requests to Struts.

    9. Update struts-config.xml: Associate the form with the Form and Action classes.

    10. Run JSP form page.

The following section will explain these steps in greater details.

2 Creating The Application

2.1 Determine Form's Name

Struts uses a name (similar to a variable's name) to associate a form in the JSP to the Form and Action classes. Select a name that reflects the function of the form. For example if the form is to ask for a book definition, name it "book".

2.2 Determine Data Entry Fields

Determine what are the data entry fields that will be displayed on the form. These names will be used in:

    1. The generated HTML form to define the form's input fields.

    2. In the Form class to define the properties getters and setters.

For our example we will have the following fields:

    1. The book's title: "title", a string.

    2. The book's author: "author", a string.

2.3 Create Blank Struts Application

The Struts download comes with a blank struts application that can be used to start the development of a Struts application. Please make sure that you have downloaded and installed the Struts binaries, and then do the following:

    1. In the Struts installation directory, locate the file webapps/struts-blank.war and copy it to %TOMCAT_HOME%/webapps.

    2. Rename the copied struts-blank.war file into your web application's name. For our example, we will rename it to struts-test.war.

    3. Start Tomcat. This will automatically expand the struts-test.war file into a directory structure in %TOMCAT_HOME%/webapps/struts-test/.

    4. To verify the correctness of what you have done, open a web browser go to this link:

    5. http://localhost:8080/struts-test/index.jsp

    6. The browser will show you something like this:

    1. Shutdown Tomcat.

    2. If you inspect the %TOMCAT_HOME%/webapps/struts-test/ directory you will notice that the directories required for a Tomcat application have been created.

    3. Notice that the Struts library is copied in:

    4. %TOMCAT_HOME%/webapps/struts-test/WEB-INF/lib/struts.jar

Whenever you want to create a new Struts application, you can repeat the above steps to start.

2.4 Create Form Class

Create a new Java class with the following characteristics:

    1. Name the class utilizing the form's name that you chose in step 2.1. If the name you chose is x, then the class name should be XForm.java. For our example, the name was "book"; hence name the class BookForm.java. (This is a recommendation).

    2. The class will have properties named to match the data entry fields determined in step 2.2.

    3. The following is the source of this class:

package com.tek271.test;

import javax.servlet.http.*;

import org.apache.struts.action.*;

public class BookForm extends ActionForm {

private String mTitle= null;

private String mAuthor= null;

public String getTitle() { return mTitle; }

public void setTitle(String aTitle) { mTitle= aTitle; }

public String getAuthor() { return mAuthor; }

public void setAuthor(String aAuthor) { mAuthor= aAuthor; }

public void reset(ActionMapping aMapping, HttpServletRequest aRequest) {

mTitle= null;

mAuthor= null;

} // reset()

} // BookForm class

Notice that the class extends the ActionForm class and defines a reset() method.

When you compile this class, make sure that the struts.jar and servlet.jar are available to the compiler. However, do not put struts.jar in the CLASSPATH. To compile the class:

    1. Save the class into

    2. %TOMCAT_HOME%/webapps/struts-test/WEB-INF/classes/BookForm.java

    3. In a DOS window, go to the directory:

    4. %TOMCAT_HOME%/webapps/struts-test/WEB-INF/classes/

    5. Compile the class as follows:

    6. javac -classpath "%CLASSPATH%;../lib/struts.jar;." BookForm.java

    7. This will produce BookForm.class.

    8. In order to support the class's package, create the following directories:

      1. %TOMCAT_HOME%/webapps/struts-test/WEB-INF/classes/com

      2. %TOMCAT_HOME%/webapps/struts-test/WEB-INF/classes/com/tek271/

      3. %TOMCAT_HOME%/webapps/struts-test/WEB-INF/classes/com/tel271/test

    9. Move the file BookForm.class into the directory:

    10. %TOMCAT_HOME%/webapps/struts-test/WEB-INF/classes/com/tel271/test/

2.5 Create Action Class

Create a new Java class with the following characteristics:

    1. Name the class utilizing the form's name that you chose in step 2.1. If the name you chose is x, then the class name should be XAction.java. For our example, the name was "book"; hence name the class BookAction.java. (This is a recommendation).

    2. The class will have a single method perform().

    3. The following is the source of this class:

package com.tek271.test;

import javax.servlet.*;

import javax.servlet.http.*;

import org.apache.struts.action.*;

public class BookAction extends Action {

public ActionForward perform(ActionMapping aMapping,

ActionForm aForm,

HttpServletRequest aRequest,

HttpServletResponse aResponse)

throws ServletException {

BookForm f = (BookForm) aForm;

String title = f.getTitle();

String author = f.getAuthor();

System.out.println(">>> Saved: " + title + " by " + author);

return aMapping.findForward("saved");

} // perform()

} // BookAction class

Notice the following about the perform() method:

    1. It gets a reference to the BookForm object as its second parameter.

    2. Can access both of the request and response objects.

    3. It does not actually save the book's data; it just prints it out to console. In a real application, you can save this data to a database.

    4. Returns a command for the Struts framework instructing it to go to a page denoted "saved". Notice how this command will be interpreted in section 2.9.

To compile this class, follow the steps of section 2.4 using BookAction instead of BookForm.

2.6 Create JSP Form Page

Create a JSP file named testJsp.jsp and save it into:

%TOMCAT_HOME%/webapps/struts-test/

The following is its source code:

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html>

<head> <title>Testing struts</title> </head>

<body>

<html:form action="book.do" >

Title: <html:text property="title" /> <br>

Author: <html:text property="author" /> <br>

<html:submit />

</html:form>

</body>

</html>

Notice the following about this file:

    1. The first line uses a Struts Tag Library Definition (TLD). This tag library contains some wrappers for HTML elements. The tag library will be denoted html in this page.

    2. The html:form element has an action attribute with the value "book.do". This is the name that we chose in section 2.1 followed by ".do". The web.xml file for this Struts application maps requests for URIs ending with ".do" to the struts-config.xml file.

    3. The element <html:text property="title"/> tells Struts to use the property "title" of a Form bean to read/write this text input box.

    4. The element <html:text property="author"/> tells Struts to use the property "author" of a Form bean to read/write this text input box.

2.7 Create Response Page

Create a JSP file named savedOk.jsp and save it into:

%TOMCAT_HOME%/webapps/struts-test/

The following is its source code:

<html>

<head><title>Book was saved</title> </head>

<body>

<h3>Book Was Saved</h3>

</body>

</html>

Note that this is just a simple page to give a response to the user.

2.8 Review web.xml

This is an optional step. You do not need to do any thing with this file. However, understanding it will be useful.

Open the following file in a text editor:

%TOMCAT_HOME%/webapps/struts-test/WEB-INF/web.xml

The following is the section of the file that we are interested in:

<web-app>

<servlet>

<servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param>

<param-name>application</param-name>

<param-value>ApplicationResources</param-value>

</init-param>

<init-param>

<param-name>config</param-name>

<param-value>/WEB-INF/struts-config.xml</param-value>

</init-param>

<!-- some more stuff ... -->

</servlet>

<!-- Standard Action Servlet Mapping -->

<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

<!-- some more stuff ... -->

</web-app>

Notice the following about this file:

    1. The starting point for Struts is the servlet mapping at line 17. This element tells Tomcat to map URLs ending with ".do" to a servlet named "action".

    2. Looking at the servlet element starting at line 2, we notice its name is "action".

    3. In other words, Tomcat will map URLs ending with ".do" to the servlet element in line 2.

    4. Line 4 defines the actual Java class that implements this servlet. This is a servlet implemented by Struts.

    5. Line 11 tells the Struts servlet what configuration file to use.

We can restate the above as:

When Tomcat receives a URL ending with "*.do", it will map this URL to the Struts framework, and tells Struts to use the configuration file struts-config.xml.

2.9 Update struts-config.xml

When you created the blank application, the following file was created:

%TOMCAT_HOME%/webapps/struts-test/WEB-INF/struts-config.xml

This file contains the configuration data for Struts in our application. Update this file to the following:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN"

"http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">

<struts-config>

<form-beans>

<form-bean name="bookForm" type="com.tek271.test.BookForm"/>

</form-beans>

<action-mappings>

<action path="/book" type="com.tek271.test.BookAction" name="bookForm">

<forward name="saved" path="/savedOk.jsp" />

</action>

</action-mappings>

</struts-config>

Notice the following about this file:

    1. This file specifies what Form and Action classes to use with the testJsp.jsp form.

    2. The starting point to consider is at line 10.

      1. The "path" attribute has a value of "/book".

      2. This is the name that we chose in section 2.1.

      3. Note also that in the testJsp.jsp form (section 2.6), line 5. The value given to the action attribute is "book.do". The book part is what brings Struts to this part in the struts-config.xml file.

      4. The "type" attribute at line 10 tells Struts to use the Action class we developed in section 2.5.

      5. The "name" attribute at line 10 tells Struts to use a Form bean named "bookForm" (See line 7). Think of this like a variable name defined in this file only.

    3. Line 11 tells Struts that when the Action class returns a "saved" ActionForward object, Struts should take control to "/savedOk.jsp".

      1. Look at the BookAction class (section 2.5) line 17. It returns a "saved" ActionForward object.

    1. Line 7 defines the Form Bean to be used.

      1. The "name" attribute allows Struts to associate line 10 with this Form.

      2. The "type" attribute defines what is the Java class to be used as the Form class. This is the class we developed in section 2.4.

2.10 Run JSP Form Page

In a web browser window, go to the following link:

http://localhost:8080/struts-test/testJsp.jsp

You should see something like this:

Enter some data in the text boxes, for example:

Title: King Lear

Author: William Shakespeare

When you push "Submit", you should see a new page like this:

If you inspect the Tomcat console window, you should see a line with the following text:

>>> Saved: King Lear by William Shakespeare

3 Validation

In this section we will add validation support to our program. The following steps summarize the required steps:

    1. Modify the JSP form page to display error messages.

    2. Modify struts-config.xml to tell the mapping what page to go to when an error occurs.

    3. Add error messages to ApplicationResources.properties file.

    4. Add a validate() method to BookForm.java.

You will notice how simple this is, and how the data entered in a form will get repopulated automatically when the form is redisplayed.

In the following sections, new lines have a gray background.

3.1 Modify JSP Form Page

Modify testJsp.jsp to look like this:

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html>

<head> <title>Testing struts</title> </head>

<body>

<html:errors/>

<html:form action="book.do" >

Title: <html:text property="title" /> <br>

Author: <html:text property="author" /> <br>

<html:submit />

</html:form>

</body>

</html>

Line 5 is a tag that will print the errors in an ActionErrors object.

3.2 Modify struts-config.xml

Modify the file struts-config.xml to be like this:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN"

"http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">

<struts-config>

<form-beans>

<form-bean name="bookForm" type="com.tek271.test.BookForm"/>

</form-beans>

<action-mappings>

<action path="/book"

type="com.tek271.test.BookAction"

name="bookForm"

input="/testJsp.jsp">

<forward name="saved" path="/savedOk.jsp" />

</action>

</action-mappings>

</struts-config>

The "input" attribute (line 13) tells Struts what is the page that started this form, and in case of validation errors, this page will be used to redisplay the input data.

3.3 Add Error Messages To ApplicationResources.properties

The file ApplicationResources.properties exists in the \WEB-INF\classes directory of the application. Modify it to be like this:

index.title=Struts Starter Application

index.heading=Hello World!

index.message=To get started on your own ...

error.book.title=<li>Title is required</li>

error.book.author=<li>Author is required</li>

errors.header=<h3>Errors:</h3><UL>

errors.footer=</UL><hr>

Lines 4 and 5 have the name of the error messages and their text. Line 6 is a prefix to be displayed before the error messages. Line 7 is to be appended after the error messages.

3.4 Add validate() Method To Bookform.Java

Add the following method to the BookForm.java class:

public ActionErrors validate(ActionMapping aMapping, HttpServletRequest aRequest) {

ActionErrors err = new ActionErrors();

if ((mTitle==null) || (mTitle.length() <1) )

err.add("title", new ActionError("error.book.title") );

if ((mAuthor==null) || (mAuthor.length()<1) )

err.add("author", new ActionError("error.book.author") );

return err;

} //validate

    1. In this validation method, we will require that both the title and the author to have values.

    2. Line 4 creates an ActionError object with a message name that matches Line 4 in ApplicationResources.properties file.

    3. Line 6 creates an ActionError object with a message name that matches Line 5 in ApplicationResources.properties file.

    4. Save and compile this file as described in section 2.4.

3.5 Run JSP Form Page

    1. Restart Tomcat.

    2. In a web browser window, go to the following link:

    3. http://localhost:8080/struts-test/testJsp.jsp

    4. You should see the familiar data entry screen.

    5. In the title field, enter "King Lear".

    6. Leave the author filed empty.

    7. Click the submit button.

    8. You should get a screen similar to the following:

Notice how the error message is displayed, and how the Title field retained its data.

4 Conclusion

As you have seen, using Struts requires some thinking and planning before you start coding (Something new for a change :)).

The example we did in section 2 shows how to start using Struts but does not show any advantages, it actually adds both programming and performance overhead.

If you decide to add validation and error handling using Struts, you will start to see the advantages that Struts brings you.

5 References