Struts Framework
This page will give you a short overview of Struts Framework and its main components. After finishing reading this, continue on to the tutorial to create a simple Struts-based Web application.
What Is the Struts Framework?
The Struts Framework is a standard for developing well-architected Web applications. It has the following features:
- Open source
- Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:
- Model: application state
- View: presentation of data (JSP, HTML)
- Controller: routing of the application flow
- Implements the JSP Model 2 Architecture
- Stores application routing information and request mapping in a single core file,
struts-config.xml
Architecture Overview

All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration file
struts-config.xmlis used by the controller to determine the routing of the flow. This flows consists of an alternation between two transitions:| From View to Action | A user clicks on a link or submits a form on an HTML or JSP page. The controller receives the request, looks up the mapping for this request, and forwards it to an action. The action in turn calls a Model layer (Business layer) service or function. |
| From Action to View | After the call to an underlying function or service returns to the action class, the action forwards to a resource in the View layer and a page is displayed in a web browser. |

- User clicks on a link in an HTML page.
- Servlet controller receives the request, looks up mapping information in
struts-config.xml, and routes to an action. - Action makes a call to a Model layer service.
- Service makes a call to the Data layer (database) and the requested data is returned.
- Service returns to the action.
- Action forwards to a View resource (JSP page)
- Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page.
- JSP file is invoked and sent to the browser as HTML.
- User is presented with a new HTML page in a web browser.
Struts Components
The Controller
This receives all incoming requests. Its primary function is the mapping of a request URI to an action class selecting the proper application module. It's provided by the framework.
The struts-config.xml File
This file contains all of the routing and configuration information for the Struts application. This XML file needs to be in the WEB-INF directory of the application.
Action Classes
It's the developer's responsibility to create these classes. They act as bridges between user-invoked URIs and business services. Actions process a request and return an ActionForward object that identifies the next component to invoke. They're part of the Controller layer, not the Model layer.
View Resources
View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files, Resource bundles, JavaBeans, and Struts JSP tags.
ActionForms
These greatly simplify user form validation by capturing user data from the HTTP request. They act as a "firewall" between forms (Web pages) and the application (actions). These components allow the validation of user input before proceeding to an Action. If the input is invalid, a page with an error can be displayed.
Model Components
The Struts Framework has no built-in support for the Model layer. Struts supports any model components:
- JavaBeans
- EJB
- CORBA
- JDO
- any other
Creating a Struts Application
with Exadel Studio
In this tutorial, the Struts Framework will be used to create and build a Web application using the Exadel Studio Web IDE.
We will be using the well known Numberguess example that comes with the Tomcat servlet container. This application asks you to guess a random number between 0 and 100 generated by the application. It works this way:
- The application prompts a user to guess a number between 0 and 100.
- The application compares the user input number to the number it randomly generated.
- Then:
- if the numbers don't match, it will ask the user to guess again.
- if the numbers do match, the game ends, but can be started again.
Before We Start
We only need to go over a few points before we start. It is assumed that you have a good basic knowledge of the Java language, JSP, and Web application development. This tutorial is based on Exadel Studio 6.2 Professional Edition.
After installing, launch Eclipse ${Eclipse_Home}\eclipse.exe. If you don't see the Exadel Studio "perspective" (there should be window pane titled "Struts Projects" to the left in the application window), then select Window/Open Perspective.../Other.../Exadel Studio from the menu bar.Developing the Guessing Game Application
Now, let's create our application. We'll need to create a new project, design the Web Flow, build a couple of Java classes, write a few JSP pages, and then run the application. All within Exadel Studio.
Creating a New Project
Like any other IDE, we first need to create a new project in Exadel Studio. To do this, select File/New/Project... from the menu bar and then Exadel Studio/Struts Project from the New Project dialog box. Select Next.
In the first step, you should see the following values:
| item | value |
|---|---|
| Project Name | The name of your new project, type in guessGame |
| Use Default Path | Leave checked. |
| Location | Leave as is. |
| Version | Leave as is. |
| Template | Leave as is. |
Select Next to go to step 2 of the Create New Project wizard. This step allows you to register your application with the Tomcat servlet container, so that you can test and run your application in a web browser. Leave all values as they are. We will use guessGame as our application name. This means we will be able to run the application in a web browser using
http://localhost:8880/guessGame/ as the URL.
Click Next to go to the last step. This step allows you to select what TLD files to include in your project. Leave as is.
Click Finish to finish project creation.
Finally, in the Navigation tree view where the project tree is displayed, expand the WebContent/WEB-INF node, right-click on struts-config.xml, and select Open.
Your project should look like the image below. To the left is the project tree with the
struts-config.xml file selected; to the right, the Web Flow diagram where we will be creating our application.
| Please note: if you don't see the Exadel Palette in Eclipse, select Window/Show View/Exadel Palette from the menu bar. |

Creating the Web Flow
One of the unique features of Exadel Studio is its Web Flow feature. The Web Flow diagram is the visual representation of a Struts configuration file showing how the application flow goes from component to component. Exadel Studio allows you to create your Web Flow (application logic) even before implementing any of the constituent Actions or JSP pages. (To view the underlying XML coding of your Struts configuration file, you can always select Source at the bottom of the Web Flow diagram.) All the elements that we need for our application can be created by right-clicking on the Web Flow diagram as shown in the figure below. (You can also do the same by right-clicking on nodes in the project tree.)

Creating the First JSP Page
We'll start by creating the first JSP page. This JSP page will prompt us to enter a number to match against the number generated by the application. Right-click the Web Flow diagram and select Add/Page.... For the name enter:
/pages/start.jsp . Click Finish. A JSP page should appear on the Web Flow diagram.Creating a Global Forward
Next, we will be creating a Global Forward. A Forwards simply allows you to direct traffic to another resource in the application. Think of it as being a link to another resource. The resource can be another Action, an Exception, or a JSP page. In our case, this Global Forward will be the starting point of our application.
Right-click the Web Flow diagram and select Add/Global Forward.... A wizard should appear with the fields shown below. Fill in the fields with the values below:
Once you have created the Forward your Web Flow should look like this figure below:
| item | value | explanation |
|---|---|---|
| Name | start | The name of this Forward. |
| Path | /pages/start.jsp | The Forward will jump to this resource. |
| Redirect | Leave blank. | Whether a redirect instruction should be issued by the browser. |
| ContextRelative | Leave blank. | Used in multi-modular applications. |

Creating an Action
An action is a unit of logic. It is the place where you can perform a business function in your application. Once the business function has finished execution, the Action will forward (via a local Forward working in the same way as a Global Forward) the execution to the resource specified by the Forward.
Right-click anywhere on the Web Flow diagram and select Add/Action.... The Add Action wizard will appear. Its fields and values are explained below.
Click Finish to create this Action.
| item | value | explanation |
|---|---|---|
| Path | /makeGuess | Path to this Action |
| Name | MakeGuessForm | Name of the FormBean that will capture input from the start.jsp page. |
| Scope | session | Scope of the action form. |
| Type | sample.MakeGuessAction | Java class name of this Action |
| Validate | Leave blank. | Whether to call the validate method of the action form |
Now we need to create a transition from the start.jsp page to the Action. To do that, select the Create New Connection icon
in the upper-left corner of the diagram to change the cursor to the connector cursor
. Using this cursor, select the start.jsp JSP page and then select the makeGuessAction. To revert to the regular cursor, go back to the upper-left corner and select the Selection icon
.
. Using this cursor, select the start.jsp JSP page and then select the makeGuessAction. To revert to the regular cursor, go back to the upper-left corner and select the Selection icon
Your Web Flow diagram should look like this now:

Adding JSP Pages
Up to now, we're set up to do the following: A user will be shown start.jsp and enter a number. Then, execution will be passed on to the makeGuessAction where a decision will be made about matching the numbers.
Now we need to add the decision results to the Web Flow. If we have a match, then we want to redirect to a page that will show us that the game is over. If we don't have a match, we want to allow the user to enter a number again.
To do this, we need to create two JSP pages. So, right-click on the Web Flow diagram, select Add/Page..., and enter this name:
/pages/match.jsp
Then, repeat and enter this name:/pages/nomatch.jsp
Now, we need to create transitions from the makeGuess Action to the two JSP pages we've created. Or, in other words, we need to create two local Forwards for the makeGuess Action. So, select the Create New Connection icon
in the upper-left corner of the diagram to change the cursor to the connector cursor
. Using this cursor, select the makeGuess Action and then select the /pages/match.jsp page. Next, select the makeGuessAction and then select the /pages/nomatch.jsp page. To revert to the regular cursor, go back to the upper-left corner and select the Selection icon
.
. Using this cursor, select the makeGuess Action and then select the /pages/match.jsp page. Next, select the makeGuessAction and then select the /pages/nomatch.jsp page. To revert to the regular cursor, go back to the upper-left corner and select the Selection icon
If there is a match, we don't need to do anything else, but, if no match occurred, we want to be able to try to match again. So, we need to create a transition from the /pages/nomatch.jsp page back to the makeGuess Action. Go ahead and create a transition by dragging and connecting.
At this point, your Web Flow should look like the figure below:

Creating a FormBean
A FormBean acts as a bridge between the JSP page and the Action. It captures user input from the JSP pages and delivers it to the Action. A FormBean can also validate the input before passing it on to the Action.
Let's create the Form Bean. Switch to the Tree mode of the editor, right-click the struts-config.xml/form-beans, and select Create Form Bean.... Then, enter the following values:
| item | value | explanation |
|---|---|---|
| Name | MakeGuessForm | Back when we created our makeGuess Action we gave this value to the name field. To associate this Form Bean to the Action, the names much match. |
| Type | sample.MakeGuessForm | Java class type of this Form Bean. |

Completion of the Web Flow Design
Now that we are done with the Web Flow design phase, let's take a look at the source code of struts-config.xml. Select the Source tab at the bottom of the editor. This is the Struts configuration file that we have created. Note that at no point did we have to write any XML by hand. The Web Flow was created with the help of wizards and drag-and-drop.

Working with the Java Classes
So far we have created our flow without actually implementing any functionality. Now, we'll need to start implementing functionality by first building the two Java classes referenced in our Web Flow design. We'll use Exadel Studio to create stub coding, fill in the coding, and then build the classes.
Generating the Java Stub Classes
We need to generate stub Java classes for our Action and FormBean. The generated Java classes are based on templates (using Apache's Velocity language) that can be modified according your project needs. The templates can be found at ${StrutsStudio_Home}\templates\generation\.

Right-click on the Web Flow diagram and select Generate Java Code.... Click the Generate button. You should see the window below showing the files that have been generated.
We have now generated two Java source files. One for the Action class and one for the FormBean class. Let's now go ahead and fill in the source code for the classes. You can see the generated files in the guessGame/JavaSource folder in the tree in the Package Explorer or Exadel Studio views.
We have now generated two Java source files. One for the Action class and one for the FormBean class. Let's now go ahead and fill in the source code for the classes. You can see the generated files in the guessGame/JavaSource folder in the tree in the Package Explorer or Exadel Studio views.
The FormBean Class (MakeGuessForm.java)
A FormBean in the Struts framework acts as a bridge between a JSP page and an Action. It captures all input from a JSP form by the use of setXXX()methods. In order for the FormBean to capture all input from the forms, the HTML form fields must match the setter methods exactly (including case).
Our FormBean is very simple. It has one attribute along with setter and getter methods for this attribute. The reset() method clears the form of previous values. We will just set the values to
-1. The validate() method checks for the validity of input captured before proceeding to an Action. In this example we are not going to worry about that, so, in this case, we will just return a null value to indicate that no validation is needed.
Below is the generated Java class. Code that appears in black was generated, blue-colored code is what we need to type in. Comments are in red.
package sample;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
public class MakeGuessForm extends org.apache.struts.action.ActionForm {
//attribute - must match name on HTML form
private String guessNumber;
private boolean isBigger;
//setter method
public void setGuessNumber (String num) {
this.guessNumber = num;
}
//getter method
public String getGuessNumber () {
return this.guessNumber;
}
public void setIsBigger (boolean b){
this.isBigger = b;
}
public boolean getIsBigger () {
return this.isBigger;
}
public MakeGuessForm () {
}
public void reset(ActionMapping actionMapping, HttpServletRequest request) {
}
public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest request) {
return null;
}
}
The Action Class (MakeGuessAction.java)
A Struts Action is a unit of logic. It is the place where a call to a business function is made (in our example we will include our business code inside the Action). An Action class acts as a bridge between the Controller layer and the Data layer in a three-tiered application.
In our Action class, once the execute() method is done executing, it forwards to the next resource in a Struts application. That resource is usually a JSP page. You can have any number of local Forwards within an Action. In our example we have two, match and nomatch. The transitions are shown on the Web Flow diagram.
Local Forwards always override Global Forward names. So for example, if you have a Global Forward with the name shoppingCart and a local Forward with the same name, the local Forward takes priority. If a local Forward can not be found then Struts will try to find the same name among Global Forwards.
The
MakeGuessAction.java file is shown below:package sample;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; // need for Session object
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class MakeGuessAction extends org.apache.struts.action.Action {
// Global Forwards
public static final String GLOBAL_FORWARD_start = "start";
// Local Forwards
// local forwards generated by Exadel Studio
// making an error in Forward names is a common mistake
// Exadel Studio minimizes such errors by generating local Forwards names for you
public static final String FORWARD_match = "match";
public static final String FORWARD_nomatch = "nomatch";
public MakeGuessAction() {
}
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
// retrieve user entered value on the page
MakeGuessForm mgf = (MakeGuessForm)form;
int userGuess = Integer.parseInt( mgf.getGuessNumber() );
// get this session
HttpSession session = request.getSession();
// retrieve the generated number, if not running for first time
Object genNumberObj = session.getAttribute("applGeneratedNumber");
int generated;
// check if generated number was created, if null, it means you are running for the first time
if(genNumberObj==null) {
generated = (int)(Math.random()*100); // generate number between 0 and 100
// save the number in this session
session.setAttribute("applGeneratedNumber",new Integer(generated));
} else {
// if number already exists, get the number
generated = ((Integer)genNumberObj).intValue();
}
// compare numbers, if equal, forward to FORWARD_match resource
// if not, forward to FORWARD_nomatch
if ( userGuess != generated) {
mgf.setIsBigger(userGuess > generated);
return mapping.findForward(FORWARD_nomatch);
}
else {
// if we guess the number and want to play a new game, kill
// the current session so that we start with a new one
session.invalidate();
return mapping.findForward(FORWARD_match);
}
}
}
Compiling the Classes
Eclipse should have already compiled your classes as soon as you saved them unless you have the automatic build option turned off. (To turn it on you just need to select Project/Build Automatically from the menu bar.)
JSP Pages
Exadel Studio has several features that speed development in working with JSP files. There is a special Exadel Palette and a JSP previewing feature.
Exadel Studio has a powerful Exadel Palette of sets of icons representing different tag libraries for use with JSP files. You can simply drag and drop these icons onto your JSP pages.
Also, Exadel Studio has a powerful design-time JSP Preview available. Simply select the Preview tab in the lower left corner of the JSP editor to see how the JSP file will look.
Initial Application Page
start.jsp is the first page that is shown when we run the application. It defines a simple form with one user input text and a button to submit the request. Here is the code to enter for it:<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html>
Please guess a number:<br/>
<!-- html form -->
<html:form action="/makeGuess.do">
<!-- input text field for the number -->
<html:text property="guessNumber" /><br/>
<!-- button -->
<html:submit value=" Guess "/>
</html:form>
</html:html>
Failure Result Page
nomatch.jsp will be used to display a page, if we don't guess the number correctly.<!-- tag libraries imports -->
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:html>
<html:form action="/makeGuess.do"> <!-- html form -->
<!--
Here we are checking if the number entered by the user is greater or smaller then
then number generated by system. We are using the Form Bean that we created to retrieve its isBigger attribute that we set in MakeGuessAction.java. If the number entered by the user is smaller,
then "Try bigger number" is printed. If the number is larger, then "Try smaller number" is printed
-->
<logic:present name="MakeGuessForm" property="isBigger" >
<!-- if bigger -->
<logic:equal name="MakeGuessForm" property="isBigger" value="true">
Try a <b>smaller</b> number.
</logic:equal>
<!-- if smaller -->
<logic:equal name="MakeGuessForm" property="isBigger" value="false">
Try a <b>bigger</b> number.
</logic:equal>
</logic:present>
<br /><br />
Please guess a number:<br/>
<!-- same as in start.jsp, input text box to enter a new number -->
<html:text property="guessNumber" />
<html:submit value=" Guess " />
</html:form>
</html:html>
When done creating this file, select Preview to see how the page will look. A snapshot of the preview is shown below.

Success Result Page
The last page simple prints that our guess was successful and has a link to play another game. Since we added a link to the start of our application, if you look at the Web Flow, match.jsp shows a link to the Global Forward.
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html>
You guessed correctly!
<br/><br/>
<html:link forward="start"> Play Again </html:link>
</html:html>
Running the Application
The last thing that is left to do is to run the application in a Web browser. Click on the green arrow button on the Tomcat toolbar to start the Tomcat servlet engine.
Tomcat output is written to the Console view. If you are starting Tomcat for the first time, Exadel Studio will check to see if you have a JDK set for your Java environment. (You need to have the full JDK to run Struts applications.) If Eclipse points to a JRE, you will be asked to specify the location of your JDK on your computer. Once the Tomcat server has started up, right-click the startGame Forward, and select Run, as shown below.
Then, you should see the following page in the Web browser.
Tomcat output is written to the Console view. If you are starting Tomcat for the first time, Exadel Studio will check to see if you have a JDK set for your Java environment. (You need to have the full JDK to run Struts applications.) If Eclipse points to a JRE, you will be asked to specify the location of your JDK on your computer. Once the Tomcat server has started up, right-click the startGame Forward, and select Run, as shown below.
Then, you should see the following page in the Web browser.







No comments:
Post a Comment