Stepping Through Jakarta Struts
Stepping Through Jakarta Struts
Stepping Through Jakarta Struts
Stepping
through
Jakarta Struts
Page 1 of 16
Stepping through Jakarta Struts
1.What is Struts?
Struts, from the Jakarta Project, is a development framework for Java servlet
applications based upon the Model-View-Controller (MVC) design paradigm. The
purpose of this article is to give you a quick intro to Struts, covering the necessary
details to make it possible to build a simple one-page example containing an HTML
form. Then I'll refine this example to show you additional features of Struts. I'll
assume that you are familiar with Java servlet programming and the MVC
architecture.
Page 2 of 16
Stepping through Jakarta Struts
Page 3 of 16
Stepping through Jakarta Struts
Page 4 of 16
Stepping through Jakarta Struts
The easiest way to start on a new Struts application is to take an existing one--for
example "struts-blank"--and make a copy of it in the "webapps" directory. When you
get more experienced with Struts you'll probably add your own standard classes and
files to your setup, and you'd then start taking a copy of this directory structure. For
our first application we simply copy all files and directories in the folder "struts-
blank" and rename the folder to "myproject". The contents of some of the files must
now be edited.
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:
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
Page 5 of 16
Stepping through Jakarta Struts
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
</web-app>
You'll see that the servlet will be called if our browser requests a file called <some-
name>.do. So when we submit the form in our one-page application we'll decide to
use the action-name "submit.do". How the Struts servlet knows what to do with this
request we'll discover next.
Up to now it has been simple and straightforward, right? Now I'll need to explain a
few things. First I'll tell you what services the servlet offers to us, and then we'll see
how we give it the instructions for a specific request. If you look at figure 1--the
MVC architecture--you'll notice the arrows marked "2" and "3". This is the interaction
between the servlet controller and the model, including the business logic. 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
Page 6 of 16
Stepping through Jakarta Struts
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.
<struts-config>
<form-bean name="submitForm"
type="hansen.playground.SubmitForm"/>
</form-beans>
<action path="/submit"
type="hansen.playground.SubmitAction"
name="submitForm"
input="/submit.jsp"
scope="request">
<forward name="success" path="/submit.jsp"/>
<forward name="failure" path="/submit.jsp"/>
</action>
Page 7 of 16
Stepping through Jakarta Struts
</action-mappings>
</struts-config>
As you can see the file contains two sections: the form-beans section that lists the
ActionForm beans, 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:
path - name of the request: "submit.do". You don't enter the ".do"-part here.
type - the path for the Action class file
name - is the logical name of the form bean (from the form-bean section)
input - validation errors should be shown on this page
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'll return to this feature. In our simple case we always
return to the same page.
It's wise to standardize on class names. I've used these simple conventions:
We're now ready to code the ActionForm and the Action classes--and the jsp view.
In order for the ActionForm bean to work, you must use Struts' own tags for creating
the HTML form and the controls in it. I'll not go into details about these tags - they're
clearly modeled after the "real" HTML-tags. The form page from figure 2, which we
call submit.jsp, contains this HTML:
<html>
<head><title>Submit example</title></head>
<body>
Page 8 of 16
Stepping through Jakarta Struts
<html:errors/>
<html:form action="submit.do">
Last Name: <html:text property="lastName"/><br>
Address: <html:textarea property="address"/><br>
Sex: <html:radio property="sex" value="M"/>Male
<html:radio property="sex" value="F"/>Female<br>
Married: <html:checkbox property="married"/><br>
Age: <html:select property="age">
<html:option value="a">0-19</html:option>
<html:option value="b">20-49</html:option>
<html:option value="c">50-</html:option>
</html:select><br>
<html:submit/>
</html:form>
</body>
</html>
The 3 taglib lines define the Struts tag libraries. In this jsp-file we only use the html-
library.
The html:errors section is used to display validation errors. We'll return to that.
Most of the well-known HTML-attributes for the controls (for example events) can
also be used with Struts tags. Note that Struts insists on using the word "property"
instead of the more familiar "name".
This class must extend the Struts ActionForm, and must have setters and getters for
all the form controls in the jsp-page (5 in our example). Optionally it may have a
validation method, which I'll demonstrate later in this article. Note that I've entered
a default value for the "lastName" text field.
package hansen.playground;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
/* Last Name */
private String lastName = "Hansen"; // default value
public String getLastName () {
return (this.lastName);
}
public void setLastName (String lastName) {
this.lastName = lastName;
}
Page 9 of 16
Stepping through Jakarta Struts
/* 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 (this.sex);
}
public void setSex (String sex) {
this.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;
}
The Action class is--seen from the application programmer's perspective--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 "perform" 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 hansen.playground;
Page 10 of 16
Stepping through Jakarta Struts
import javax.servlet.http.*;
import org.apache.struts.action.*;
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.
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.
First restart your servlet container. Normally you'll have to do this whenever you
modify a config file or update a Java class.
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.
Page 11 of 16
Stepping through Jakarta Struts
In step 7 you saw how we stored the users last name in uppercase in the request
object. To give you an idea of how some of the other Struts tags work, I'll show how
to display this name--with a greeting to the user.
Tags Purpose
<logic:present Only if the name "lastName" is present in the
name="lastName" scope="request"> request object we'll evaluate what's inside the
... opening and closing tags. Therefore nothing will
</logic:present> show up until the "perform" method is called.
<logic:equal name="submitForm" If the property "age" in the ActionForm bean has
property="age" the value "a" (age 0-19) the text "young" is send
value="a"> to the browser.
young
</logic:equal>
<bean:write name="lastName" Sends the value of the "lastName" attribute in the
scope="request"/> request object to the browser.
With these extra lines the page could display like this in the browser:
Page 12 of 16
Stepping through Jakarta Struts
I'll finish this introduction to Struts by showing you how to make some simple
validations. 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.
While we're modifying the code, we also add some log messages so we can check
the data we receive from the form:
Page 13 of 16
Stepping through Jakarta Struts
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.
The error messages are taken from the ApplicationResources.properties file. The
messages are inserted in the jsp-page by using the Struts tag <html:errors/>. 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 ApplicationResources.properties file (note
that HTML tags may be included as you like it):
errors.header=<h4>Validation Error(s)</h4><ul>
errors.footer=</ul><hr>
Page 14 of 16
Stepping through Jakarta Struts
Note that age 0-19 is selected as default according to normal HTML selection list
practice.
Here's a picture that shows how the Struts components work together:
6. Final remarks
There's a lot more to say about Struts, but having kept my example simple I hope
that I have brought forward the basic architecture of Struts. A very important
characteristic of this architecture is the loose coupling between modules. There are
no hardcoded file names or class names in the controller or in the Action or
ActionForm classes.
Another thing is that all text in your pages may be placed in the
ApplicationResources.properties file--you may even implement multi-language
support using these properties-files.
7. Resources
There are a lot of good resources available from the Struts web site. My favorites
are these:
Page 15 of 16
Stepping through Jakarta Struts
Page 16 of 16