Struts
Struts
1
Jakarta Struts Live
Struts Quick Start Tutorial
Getting started with Struts, skip the fluff, just the facts!
This chapter is a tutorial that covers getting started with Strutsjust the basics, nothing more, nothing less. This
tutorial assumes knowledge of Java, JDBC, Servlets, J2EE (with regards to Web applications) and JSP. Although
you can follow along if you are not an expert in all of the above, some knowledge of each is assumed.
Instead of breaking the chapters into a myriad of single topics, which are in depth ad nauseum, we treat Struts in
a holistic manner, minus the beads and crystals. The focus of this chapter is to skim briefly over many topics to
give you a feel for the full breadth of Struts. Later chapters will delve deeply into many topics in detail.
In this chapter, you will cover:
The struts configuration
Writing Actions
Working with Struts Custom tags
Setting up datasource
Handling exceptions
Displaying objects in a JSP
Jakarta Struts Live
2
In this chapter you will perform the following steps:
1. Download Struts
2. Setup a J2EE web application project that uses Struts
3. Write your first Action
4. Write your first forward
5. Configure the Action and forward in the Struts configuration file
6. Run and Test your first Struts application.
7. Debugging Struts-Config.xml with the Struts Console
8. Add Logging support with Log4J and commons logging.
9. Write your first ActionForm
10. Write your first input view (JSP page)
11. Update the Action to handle the form, and cancel button
12. Setup the database pooling with Struts
13. Declaratively Handle Exception in the Struts Config file
14. Display an Object with Struts Custom Tags
Jakarta Struts Live
Download Struts 3
Download Struts
The first step in getting started with Struts is to download the Struts framework. The Struts home page is located
at http://jakarta.apache.org/struts/index.html. You can find online documentation at the Struts home page. How-
ever, to download Struts you need to go to the Jakarta Download page at http://jakarta.apache.org/site/binin-
dex.cgi. Since all of the Jakarta download links are on the same page, search for Struts on this page. Look for
the link that looks like this:
Struts KEYS
1.1 zip PGP MD5
1.1 tar.gz PGP MD5
Download either compressed file.
One of the best forms of documentation on Struts is the source. Download the source from http://
jakarta.apache.org/site/sourceindex.cgi. Once you have both the source and binaries downloaded, extract them.
(WinZip works well for Windows users.) This tutorial will assume that you have extracted the files to c:\tools\
jakarta-struts-1.1-src and c:\tools\ jakarta-struts-1.1. If you are using another drive, directory, or *n?x (UNIX or
Linux), adjust accordingly.
Jakarta Struts Live
Set up a J2EE Web Application Project That Uses Struts 4
Set up a J2EE Web Application Project That Uses Struts
Struts ships with a started web application archive file (WAR file) called struts-blank.war. The struts-blank.war
file has all of the configuration files, tag library descriptor files (tld files) and JAR files that you need to start
using Struts. The struts-blank.war file includes support for Tiles and the Validator framework. You can find the
struts-blank.war file under C:\tools\jakarta-struts-1.1\webapps.
1. A war file is the same format as a ZIP file. Extract the struts-blank.war file to a directory called
c:\strutsTutorial (adjust if *n?x). When you are done, you should have a directory structure as fol-
lows:
C:.
|---META-INF
|---pages
|---WEB-INF
|---classes
| |--resources
|---lib
|---src
|---java
|---resources
The blank war file ships with an Ant build script under WEB-INF/src. The structure of the extracted
directory mimics the structure of a deployed web application.
2. In order for the build.xml file to work, you need to modify it to point to the jar file that contains the
Servlet API and the jar file that points to the JDBC API from your application server.
For example, if you had Tomcat 5 installed under c:\tomcat5, then you would need to modify the
servlet.jar property as follows:
<property name="servlet.jar"
value="C:/tomcat5/common/lib/servlet-api.jar"/>
Tip: Tomcat is a Servlet container that supports JSP. If you are new to web development in Java, there are
several very good books on Java web development. You will need to know about JSP, Servlets and
web applications to get the most out of this chapter and this book. If you are new to Java web develop-
ment, try this tutorial: http://java.sun.com/j2ee/1.4/docs/tutorial/doc/WebApp.html#wp76431.
3. If you are using an IDE (Eclipse, NetBeans, JBuilder, WSAD, etc.), set up a new IDE project pointing
to C:\strutsTutorial\WEB-INF\src\java as the source directory, add your application servers serv-
let.jar file (servlet-api.jar for tomcat) and all the jar files from C:\strutsTutorial\WEB-INF\lib.
Jakarta Struts Live
Write Your First Action 5
Write Your First Action
Actions respond to requests. When you write an Action, you subclass org.apache.struts.action.Action
and override the execute method.
The execute method returns an ActionForward. You can think of an ActionForward as an output view.
The execute method takes four arguments: an ActionMapping, ActionForm, HttpServletRequest and an HttpS-
ervletResponse (respectively).
The ActionMapping is the object manifestation of the XML element used to configure an Action in the Struts
configuration file. The ActionMapping contains a group of ActionForwards associated with the current action.
For now, ignore the ActionForm; we will cover it later. (It is assumed that you are familiar with HttpServletRe-
quest and HttpServletResponse already.)
Go to strutsTutorial\WEB-INF\src\java and add the package directory strutsTutorial. In the strutsTutorial direc-
tory, add the class UserRegistration as follows:
package strutsTutorial;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class UserRegistrationAction extends Action {
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
return mapping.findForward("success");
}
}
Notice that this Action forwards to the output view called success. That output view, ActionForward, will be a
plain old JSP. Lets add that JSP.
Jakarta Struts Live
Write Your First Forward 6
Write Your First Forward
Your first forward will be a JSP page that notifies the user that their registration was successful. Add a JSP page
to c:\strutsTutorial called regSuccess.jsp with the following content:
<html>
<head>
<title>
User Registration Was Successful!
</title>
</head>
<body>
<h1>User Registration Was Successful!</h1>
</body>
</html>
The forward is the output view. The Action will forward to this JSP by looking up a forward called success.
Thus, we need to associate this output view JSP to a forward called success.
Jakarta Struts Live
Configure the Action and Forward in the Struts Configuration File 7
Configure the Action and Forward in the Struts
Configuration File
Now that we have written our first Action and our first Forward, we need to wire them together. To wire them
together we need to modify the Struts configuration file. The Struts configuration file location is specified by the
config init parameter for the Struts ActionServlet located in the web.xml file. This was done for us already by the
authors of the blank.war starter application. Here is what that entry looks like:
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
...
<load-on-startup>2</load-on-startup>
</servlet>
Thus, you can see that the blank.wars web.xml uses WEB-INF/struts-config.xml file as the Struts configuration
file.
Follow these steps to add the success forward:
1. Open the c:\strutsTutorial\WEB-INF\struts-config.xml file.
2. Look for an element called action-mappings.
3. Add an action element under action-mappings as shown below.
<action path="/userRegistration"
type="strutsTutorial.UserRegistrationAction">
<forward name="success" path="/regSuccess.jsp"/>
</action>
The above associates the incoming path /userRegistration with the Action handler you wrote earlier, strutsTu-
torial.UserRegistrationAction.
Jakarta Struts Live
Configure the Action and Forward in the Struts Configuration File 8
Whenever this web application gets a request with /userRegistration.do, the execute method of the strutsTuto-
rial.UserRegistrationAction class will be invoked. The web.xml file maps request that end in *.do to the Struts
ActionServlet. Since the web.xml file was provided for us, you will not need to edit it. Here is the mapping for in
the web.xml file for reference:
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
The Struts ActionServlet will invoke our action based on the path attribute of the above action mapping. The
ActionServlet will handle all requests that end in *.do. You may recall that our Action looks up and returns a for-
ward called success. The forward element maps the success forward to the regSuccess.jsp file that you just cre-
ated in the last section.
The ActionMapping that gets passed to the execute method of the Action handler is the object representation of
the action mapping you just added in the Struts config file.
Jakarta Struts Live
Run and Test Your First Struts Application 9
Run and Test Your First Struts Application
The blank.war file ships with a started Ant script that will build and deploy the web application.
If you are new to Ant, then today is a good day to get up to speed with it. Ant is a build system from Jakarta.
Struts uses a lot of Jakarta projects. Most Jakarta projects use Ant. Ant is also a Jakarta project. (Technically, it
used to be a Jakarta project, and it was promoted to a top level project at the 1.5 release.) You can learn more
about Ant and read documentation at http://ant.apache.org/. You can download Ant at http://www.apache.org/
dist/ant/. Also, you can find an install guide for Ant at http://ant.apache.org/manual/installlist.html.
Technically, you do not have to use Ant to continue on with this tutorial, but it will make things easier for you.
Its up to you. If you are not using Ant, now is a good time to start. Read http://ant.apache.org/manual/
usinglist.html to start using Ant after you install it.
If you are using the Ant build.xml file that ships with the blank.war (look under WEB-INF/src), you will need to
add the ${servlet.jar} file to the compile.classpath as follows:
<path id="compile.classpath">
<pathelement path ="lib/commons-beanutils.jar"/>
<pathelement path ="lib/commons-digester.jar"/>
<pathelement path ="lib/struts.jar"/>
<pathelement path ="classes"/>
<pathelement path ="${classpath}"/>
<pathelement path ="${servlet.jar}"/>
</path>
Notice the addition of the <pathelement path ="${servlet.jar}"/>. The compile classpath is used by the compile
target.
After you add the pathelement, change the project.distname property to strutsTutorial as follows:
<property name="project.distname" value="strutsTutorial"/>
Go ahead and run the Ant build script as follows:
C:\strutsTutorial\WEB-INF\src> ant
If things go well, you should see the message BUILD SUCCESSFUL. Once you run the Ant build script with the
default target, you should get a war file in your c:\projects\lib directory called strutsTutorial.war. Deploy this war
file to your application server under the web context strutsTutorial. You will need to refer to your application
server manual for more details on how to do this. For Tomcat and Resin, this is a simple matter of copying the
war file to Tomcats or Resins home-dir/webapps directory. The webapps directory is under the server directory.
Jakarta Struts Live
Run and Test Your First Struts Application 10
If you are not Ant savvy, you can simulate what this ant script does by setting your IDE to output the binary files
to C:\strutsTutorial\WEB-INF\classes, and then zipping up the c:\strutsTutorial directory into a file called strut-
sTutorial.war.
Now that you have built and deployed your web application, test your new Action/forward combination by going
to http://localhost:8080/strutsTutorial/userRegistration.do. You should see the following:
Figure 1.1 Running The Action for the first time
Congratulations! You have just written your first Struts Action. Now, admittedly this Action does not do much.
At this point, you may be having troubles. The most obvious problem is probably a misconfigured struts-con-
fig.xml file. There are two ways to solve this.
Jakarta Struts Live
Run and Test Your First Struts Application 11
Debug Struts-Config.xml with the Struts Console
If you are new to XML, it may be a little hard to edit the struts-config.xml file. If you are having troubles with
the struts-config.xml file, you should download the Struts Console. The Struts Console is a Swing based struts-
config.xml editor; it provides a GUI for editing struts-config files. The Struts Console works as a plugin for
JBuilder, NetBeans, Eclipse, IntelliJ and more. The Struts Console can be found at http://www.jamesh-
olmes.com/struts/console/; follow the install instructions at the site. If you have a problem, you can edit the
struts-config file with Struts Console. If there is a problem with the struts-config.xml file, the Struts Console will
take you to the line / column of text that is having the problem. For example, here is an example of editing a
struts-config file with a malformed XML attribute:
Figure 1.2 Running Struts Console against a malformed struts-config.xml file
Notice the Goto Error button. Clicking the button takes you to the exact line in the struts-config.xml file that is
having the problem.
Jakarta Struts Live
Run and Test Your First Struts Application 12
Once everything is fixed, you can view and edit the struts-config.xml file with the Struts Console as follows:
Figure 1.3 Running Struts Console in a happy world
The figure above shows editing struts-config.xml and inspecting the userRegistration action that you just config-
ured.
Personally, I only use the Struts Console if there is a problem or I want to validate my struts-config.xml file with-
out launching the application server. I prefer editing the struts-config.xml with a text editor, but find that the
Struts Console comes in handy when there is a problem. In addition to mentoring new Struts developers and
doing development myself, I teach a Struts course. I have found that Struts Console is extremely valuable to new
Struts developers. Students (and new Struts developers) can easily make a small mistake that will cause the con-
fig file to fail. I can stare for a long time at a struts-config.xml file, and not find a one off error. Most of these
errors, you will not make once you are a seasoned Struts developer, but they can be very hard to diagnose without
the Struts Console when you are first getting started.
Another debugging technique is to use common logging to debug the application at runtime.
Jakarta Struts Live
Run and Test Your First Struts Application 13
Add Logging Support with Log4J and Commons Logging
You may wonder why we dedicate a whole section to logging. Well to put it simply, when you are new to Struts,
you will need to do more debugging, and logging can facilitate your debugging sessions dramatically.
The Struts framework uses Commons Logging throughout. Logging is a good way to learn what Struts does at
runtime, and it helps you to debug problems. The Commons Logging framework works with many logging sys-
tems; mainly Java Logging that ships with JDK 1.4 and Log4J.
Using Struts without logging can be like driving in the fog with your bright lights, especially when something
goes wrong. You will get a much better understanding how Struts works by examining the logs. Logging can be
expensive. Log4J allows you to easily turn off logging at runtime.
Log4J is a full-featured logging system. It is easy to set up and use with Struts. You need to do several things:
1. Download Log4J
2. Unzip the Log4J distribution
3. Copy the log4j.jar file to c:\strutsTutorial\WEB-INF\lib
4. Create a log4j.properties file
5. Start using logging in our own classes
Like Struts, Log4J is an Apache Jakarta project. The Log4J home page is at http://jakarta.apache.org/log4j/docs/
index.html. You can download Log4J from http://jakarta.apache.org/site/binindex.cgi. Search for Log4J on this
page. Look for the link that looks like:
Log4j KEYS
1.2.8 zip PGP MD5
1.2.8 tar.gz PGP MD5
Click on the 1.2.8 ZIP file link. Download this file to c:\tools, and adjust accordingly for different drives, directo-
ries and operating systems (like *n?x). Copy the log4j-1.2.8.jar file located in C:\tools\jakarta-log4j-1.2.8\dist\lib
to c:\strutsTutorial\WEB-INF\lib.
Jakarta Struts Live
Run and Test Your First Struts Application 14
Now that you have the jar file in the right location you need to add log4j.properties files so that the web applica-
tion classloader can find it. The Ant script copies all properties (*.properties) files from \WEB-INF\src\java to
\WEB-INF\classes. The Ant script also deletes the \WEB-INF\classes directory. Thus, create a log4j.properties
file in the \WEB-INF\src\java directory with the following contents:
log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%5p] %d{mm:ss}
(%F:%M:%L)%n%m%n%n
The code above sends output to the stdout of the application with the priority, date time stamp, file name, method
name, line number and the log message. Logging is turned on for classes under the Struts package and the strut-
sTutorial code.
To learn more about Log4J, read the online documentation at http://jakarta.apache.org/log4j/docs/manual.html,
and then read the JavaDoc at http://jakarta.apache.org/log4j/docs/api/index.html. Look up the class
org.apache.log4j.PatternLayout in the JavaDocs at the top of the file is a list of conversion characters for the out-
put log pattern. You can use the conversion characters to customize what gets output to the log.
Putting log4j on the classpath (copying the jar file to WEB-INF\lib), causes the Commons Logging to use it. The
log4J framework finds the log4j.properties file and uses it to create the output logger.
If you start having problems with Struts, then set up the logging level of Struts to debug by adding the following
line to log4j.properties file:
log4j.logger.org.apache.struts=DEBUG
Underneath the covers, we are using Log4J. However, if we want to use logging in our own code, we should use
Commons Logging, which allows us to switch to other logging systems if necessary. Thus, we will use the Com-
mons Logging API in our own code. To learn more about Commons Logging, read the short online manual at
http://jakarta.apache.org/commons/logging/userguide.html.
Jakarta Struts Live
Run and Test Your First Struts Application 15
Edit the UserRegistrationAction by importing the two Commons Logging classes and putting a trace call in the
execute method as follows:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;