This tip will show you the overall architecture of a Strut application. The steps in this tip walk you through building all of the necessary components for struts.

Step 1: Installation of Tomcat 5.0

Download and install the latest stable version of Tomcat (5.0) from

Also make sure that you have installed JDK1.4 before installation of Tomcat 5.0.

Step 2: Create the web application directory

You'll need to know the directory structure of a Struts application, and what's put in the Directories. The "struts-blank" application is well-suited for this presentation, since it contains a Minimum number of files:

Step 3: Understanding and Modifying web.xml

The web.xml file is where servlets and other stuff are defined to the servlet container. We'll remove some unnecessary things from the web.xml file so it looks like this:

 <?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
<!-- Standard Action Servlet Configuration (with debugging) -->
<servlet-class> org.apache.struts.action.ActionServlet </servlet-class>
<!-- Standard Action Servlet Mapping -->
<!-- Struts Tag Library Descriptors -->

The file contains three sections:

  1. The definition of the Struts servlet named "ActionServlet"
  2. The URL mapping for the calls to this servlet
  3. The definitions of the Struts tag libraries

The servlet is called if our browser requests a file called . So when we submit the form in our one-page application to the action-name "".

Step 4: Understanding and modifying the struts-config.xml file

When you use Struts then part of this interaction is as follows:

First of all the Struts servlet will automatically transfer the data from your form into a JavaBean that you should supply. This bean is called the ActionForm bean, because your bean must extend the Struts "ActionForm" class. You may think of this bean as a buffer between the browser and your database. The ActionForm bean may also be used to initialize form controls and to validate the data entered by the user.

Secondly the Struts servlet will call a class which you specify and it is referred to as the Action class. This class may use the data in the ActionForm bean. The Action class is where your application coding starts. When your class finishes it returns control to the Struts servlet.

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 1.1//EN"
<!-- ========== Data Source Configuration ====================== -->
<!-- configuration for commons BasicDataSource -->

<!-- ========== Form Bean Definitions ======================== -->
<!-- Simple ActionForm Bean -->
<form-bean name="simpleForm" type="com.rohit.SimpleActionForm"/>


<!-- ========= Global Exception Definitions ======================== -->
<!-- ========== Global Forward Definitions ======================== -->
<forward name="home" path="/index.jsp" redirect="true"/>
<!-- ========== Action Mapping Definitions ==================== -->
<!-- Simple ActionForm Example =================== -->
<action path="/prepareSimple"
<forward name="success" path="/jsp/simple/Simple.jsp"/>
<forward name="error" path="jsp/database/error.jsp"/>
<action path="/processSimple"
<forward name="success" path="/jsp/simple/SimpleResults.jsp"/>

<!-- ========== Controller Configuration ========================== -->
<!-- ========== Message Resources Definitions ==================== -->
<message-resources parameter="ApplicationResources" />
<!-- ========== Plug Ins Configuration ============================== -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml" />
<plug-in className="org.apache.struts.tiles.TilesPlugin" >
<set-property property="definitions-config"
value="/WEB-INF/tiles-defs.xml" />
<set-property property="moduleAware" value="true" />
<set-property property="definitions-parser-validate" value="true" />

As you can see the file contains two sections: the form-beans section and the action-mappings. In the form-beans section you give the bean a logical name (referred to in the action-mapping) and specify the path for the class file.

The action-mappings are the most interesting. The attributes given are these:

  1. path - name of the request: "". You don't enter the ". do"-part here.
  2. type - the path for the Action class file
  3. name - is the logical name of the form bean (from the form-bean section)
  4. input - validation errors should be shown on this page
  5. scope - specifies how long the form bean should live. You may specify "session" instead.

The forward tag tells the servlet where to go if it receives either "success" or "failure" from the Action class.

We're now ready to code the ActionForm and the Action classes--and the jsp view.

Step 5: Building JSP page

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:html xhtml="true" locale="true">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple form using ActionForm</title>
<link rel="stylesheet" type="text/css" href="/../../css/example.css" />
<h1>Simple form using ActionForm</h1>
<html:form action="/processSimple">
<p>* What's your first name?:<html:text property="name" size="40" maxlength="50"/></p>
<p>* Enter a secret word or phrase:<html:password property="secret" size="40"
<p>What is your favorite color?:
<html:select property="color">
<html:option value="red">Red</html:option>
<html:option value="green">Green</html:option>
<html:option value="blue">Blue</html:option>
<p><html:checkbox property="confirm"/> Is that really your favorite color?</p>
<p>How much do you like your chosen color?:<br/>
<html:radio property="rating" value="1">Actually, I hate it.</html:radio><br />
<html:radio property="rating" value="2">Not so much.</html:radio><br />
<html:radio property="rating" value="3">I'm indifferent</html:radio><br />
<html:radio property="rating" value="4">It's pretty neat</html:radio><br />
<html:radio property="rating" value="5">I painted my whole house with it.</html:radio>
<p>Enter a message (you may use html tags):<br />
<html:textarea property="message" cols="40" rows="6"/>
<html:hidden property="hidden" value="Sssh! It's a secret. Nobody knows I'm here."/>
<hr noshade="noshade" />
<html:submit styleClass=" customButton"><bean:message key="button.submit"/></html:submit>
<html:cancel styleClass="customButton"/></center>

Step 6: Building SimpleResults.jsp page

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:html xhtml="true" locale="true">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple ActionForm Example</title>
<link rel="stylesheet" type="text/css" href="/../../css/example.css" />
<h1>Simple Form Results</h1>
<hr noshade="noshade"/>
<p>Hello <bean:write name="simpleForm" property="name" />,</p>
<p><strong>You told me a secret:</strong> <bean:write name="simpleForm" 
property="secret" /></p>
<p><strong>You said that your favorite color is:</strong> <bean:write name="simpleForm"
property="color" /></p>
<logic:equal name="simpleForm" property="confirm" value="true">
<p>You confirmed that this <em>is</em> your favorite color.</p>
<logic:notEqual name="simpleForm" property="confirm" value="true">
<p>... but you lied. Shame on you!</p>
<p><strong>On scale of 1 to 5 you rated your color:</strong>
<bean:write name="simpleForm" property="rating" />
<p><strong>This was lurking in a hidden field:</strong><br />
<bean:write name="simpleForm" property="hidden" /></p>
<p><strong>You wrote this message:</strong></p>
<p><bean:write name="simpleForm" property="message" filter="false"/></p>
<center><html:button property="Back" styleClass="customButton" 
onclick="javascript:history.go(-1)"><bean:message key="button.back"/></html:button> </center>

Step 7: Coding the ActionForm class

This class must extend the Struts ActionForm, and must have setters and getters for all the form Controls in the jsp-page. Optionally it may have a validation method for validating inputs at server side.


import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;

public final class SubmitForm extends ActionForm {
    /* Last Name */
    private String lastName = "Rohitl"; // default value
    public String getLastName() {
        return (this.lastName);
    public void setLastName(String lastName) {
        this.lastName = lastName;
    /* Address */
    private String address = null;
    public String getAddress() {
        return (this.address);
    public void setAddress(String address) {
        this.address = address;
    /* Sex */    
    private String sex = null;
    public String getSex() {
        return (;
    public void setSex(String sex) { = sex;
    /* Married status */
    private String married = null;
    public String getMarried() {
        return (this.married);
    public void setMarried(String married) {
        this.married = married;
    /* Age */
    private String age = null;
    public String getAge() {
        return (this.age);
    public void setAge(String age) {
        this.age = age;

Compile this class by including struts.jar and servlet-api.jar files in the classpath. The struts .jar file is available in the lib directory of your application and servlet-api.jar is available at <TOMCAT-HOME>\common\lib.

Step 8: Coding the Action class

The Action class is the heart of the application. This is where you must decide how you'll separate your own application code. Most often the Action class should be kept as "thin" as possible, placing business logic in other beans or even EJB's on other servers. The implementation of the Action class must contain a "execute" method, which receives the request and response objects, the instance of the ActionForm bean and the action mapping information from the configuration file. A very simple Action class, which simply lets the request pass unaltered, is given as follows:

 package com.rohit;

import javax.servlet.http.*;
import org.apache.struts.action.*;

public final class SubmitAction extends Action {
    public ActionForward execute(ActionMapping mapping,
           ActionForm form, HttpServletRequest request, 
           HttpServletResponse response) {
        SubmitForm f = (SubmitForm) form; // get the form bean
        // and take the last name value
        String lastName = f.getLastName();
        // Translate the name to upper case
        //and save it in the request object
        request.setAttribute("lastName", lastName.toUpperCase());
        // Forward control to the specified success target
        return (mapping.findForward("success"));

The manipulation of the "last name" value is only done to show how to access the form bean and how you may store data for use by other components, e.g. the jsp-file.

You may recall that the target of "success", which was specified in the Struts config file, was the submit.jsp file.

This class is also placed in the WEB-INF/classes/com/rohit directory.

An important thing to remember is that Struts only creates a single instance of the Action class shared amongst all users of the application. You should therefore not use member variables, but only local variables.

To test our example, enter this URL in the browser:


If your application works, you'll see that "Last Name" is filled with "Anil" (which means that Struts has already created an instance of the ActionForm bean, and extracted the data from it). Now enter data in all the controls and press "Submit". Note that the URL changes to "", and that all data stays unchanged in the form.

You might also want to try to enter some "problematic" characters like single and double quotes or the "<" and ">" characters in the text fields to see that Struts is perfectly capable of handling them correctly. Use the browsers "view source" to see how Struts does it.

Step 9: Create .war file

Create myproject.war using jar command provided with JDK. Open command window and change directory to your application directory (i.e.myproject).

Exceute jar –cvf myproject.war command. This creates myproject.war file in myproject directory. If jar command is not recognized, set path environment to jdk bin directory (ex. Execute command: set path=c:\jdk1.3.1\bin )

Step 10: Deploying war file

Deploy myproject.war using manager application of Tomcat 5.0 server Log to manager application by visiting the page http://ttc_ejb_srv/manager/htm. This opens dialog to enter username and password to log in the manager application. Provide the user name and password as admin (Contact your Server administrator for username and password). Once you logs in the application you should see the page as shown in the following figure.

Step 11: Testing application

Visit pages(index.jsp) using url http://ttc_ejb_srv:8080/myproject/index.jsp.

Repeat the steps for whenever you do changes in your application on client and want to test them.

Step 12: Validating your input

Let's assume that the user of our form must enter his or her last name, address, sex and age. The Simplest way to implement validation is in the ActionForm bean, but you can also do it in the Action class.

Code the "validate" method in ActionForm While we're modifying the code, we also add some log messages so we can check the data we Receive from the form:

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = new ActionErrors();
    //   Name must be entered
    if ((name == null) || (name.length() < 1)) {
        errors.add("name", new ActionError(""));
    //   Secret Phrase must be entered
    if ((secret == null) || (secret.length() < 1)) {
        errors.add("secret", new ActionError("errors.secret.required"));
    return (errors);

The servlet controller will check if the returned ActionErrors object is empty or not. If not empty the controller will return to the page specified by the "input" parameter in the config file. In our example this is the submit.jsp page. Define the error message text.The error messages are taken from the file. The messages are Inserted in the jsp-page by using the Struts tag or . In order to have a nice formatting of the messages you must also define two keys called errors.header and errors.footer. This is our file (note that HTML tags may be included as you like it):

errors.header=<h4>Validation Error(s)</h4><ul>
error.lastName=<li>Enter your last name
error.address=<li>Enter your address<li>Enter your sex
error.age=<li>Enter your age

Now restart the servlet container (Tomcat Server) and test the validations. If we don't enter anything in the form we'll get this answer: Note that age 0-19 is selected as default according to normal HTML selection list practice. Modify the Submit Page to display validation errors next to the field using <html:errors property=”propertyname” /> tag.

Output screen when validation fails

Output screen when validation passed