Smooth the Java Journey with Struts
April 21, 2004 David Morris
Building enterprise-level Web applications is no easy task. There are many ways to present data, control application flow, model data, and organize applications. Fortunately, aspiring Web architects can use tried- and-proven design patterns to avoid the pitfalls of others. The most important design pattern for Web architects is called Model-View-Controller. The MVC design pattern separates applications into three types of components. Model components support data retrieval from a database or other source. View components support the way data is presented to the user or the view. And controller components control the flow of the application.
The main reason to use Struts when building Web applications is its support for the MVC design pattern. Applications that adhere to the MVC design pattern have a structure that is flexible and maintainable, allowing you to maximize the useful life of applications and to minimize the cost of change. Struts is a popular framework that provides support for each part of the MVC design pattern that allows you to plug in your business logic without worrying about low-level, servlet-related plumbing.
Nothing forces you to use the MVC design pattern in Struts applications, and because of this, so there’s no right or wrong way to use Struts. The right way is to separate your application between model, view, and controller components. Most Struts application use a JavaServer Page (JSP), backed by an action form, to support the view. The controller in a Struts application extends an action class, which greatly simplifies servlet interaction. The controller moves data between the view and model and controls the flow of the application. The model can consist of simple Java beans, which use JDBC to read and write to a database; complex Enterprise JavaBeans; or something in between, like Hibernate data access objects.
WHAT IS STRUTS?
Struts is a set of Java components that make it easier to build Web applications. Under the covers, Struts is a Java servlet application that sits between your business-specific application code and a Web browser. The main component of Struts is the ActionServlet, which pre-processes requests from a browser, making it easier to process Web requests and responses from Java. A lot of the complexity of creating servlets and processing arcane HTTP protocols is simplified.
Within Struts there are components that help create applications that rely on the MVC design pattern. The ActionServlet loads an action form that you write, which extends a Struts ActionForm and collects input from the browser. The action form contains values passed to and from the browser. An action class, which you write, extends the DispatchAction class and calls your business logic classes. The action form controls the flow of your application. Action messages return status and error messages to the browser.
THE VALUE OF STRUTS
Struts is not the fanciest, most complete, or most expensive Java Web development framework. However, Struts is a stable, well-tested, widely deployed, well-documented, and free framework. Struts has evolved into a focused framework of components that strike a good balance between simplifying and stifling Web development. Rather than use trial and error to work through the intricacies of servlet programming yourself, Struts allows you to focus on your business requirements and to leave the low-level servlet programming to others.
Another of Struts’ selling points is its popularity. There is a large pool of developers who understand and use Struts to build applications. This popularity makes it easier to find talent and information as you begin building applications with Struts. Knowing how to use Struts is also a marketable skill. A lot of companies are using Struts, and the demand for Struts developers is growing.
There are quite a few books, articles, examples, and tutorials available to help you learn how to build business applications with Struts. As you read about Struts, keep in mind that Struts is constantly evolving. Improvements are made by a team of volunteers and are released nightly. Periodically, those improvements are gathered and tested, and a stable version is released. With very few exceptions, a Struts application written for Struts Version 1.0 will work with the latest 1.2 version but there are enhancements that you will want to take advantage of.
GETTING YOUR OWN COPY OF STRUTS
Struts is available from the Apache Software Foundation. Currently, Struts is part of the Jakarta project, which is a collection of open-source, Java-based software. In the near future, Struts will become a top-level Apache project, and has its own Web site, at struts.apache.org. To use Struts, you also need a servlet container, like Tomcat or WebSphere Application Server (WAS).
From the main Struts page, select the binaries link, which will take you to the binary downloads page where you can download the latest stable zipped version of Struts. Extract that ZIP file to your PC. If you don’t already have a servlet container, follow this same procedure and download the latest stable version of Tomcat.
If you are not currently using an interactive development environment (IDE) or have not upgraded to WDSc 5.1, contact IBM or your IBM business partner and get a copy. If you are unable to get the latest version of WDSc, which is based on Eclipse 2.1, consider downloading and installing the latest version of Eclipse. In the next section, I will describe how to build Struts applications with WDSc or Eclipse, but you should be able to follow along with any IDE.
STARTING WITH STRUTS
To use Struts, you need to have a servlet container to run it in. Tomcat is the easiest servlet container to set up, and works well with Struts. Read “Installing and Configuring Tomcat on iSeries” to learn more about setting up and running Tomcat on the iSeries. In the next few paragraphs, I will describe how to install and run Tomcat in a development environment on your workstation.
Start WDSc or Eclipse and create a new project name for Tomcat. In the new project dialog, I created a simple project named jakarta-tomcat-5.0.19. Right-click that new project and select import, followed by file system. Browse to the directory where you unpacked Tomcat, and select every file and directory except webapps. Select the create selected folders only radio button and click finish. Your dialog should look something like that in Figure 1.
Figure 1: Import the latest Tomcat distribution into your WDSc workspace |
The next step is to configure Tomcat. Start by renaming the server.xml file, found in Tomcat’s conf directory, to server.old.xml. Next, rename the server-minimal.xml file to server.xml. Now configure logging by adding Valve and Logger elements. These entries go inside the Host element in the newly renamed server.xml file and should look something like the following.
<Host name="localhost" debug="0" appBase="webapps" unpackWARs="true" autoDeploy="true"> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="common"/> <Logger className="org.apache.catalina.logger.FileLogger" directory="logs" prefix="localhost_log." suffix=".txt" timestamp="true"/> </Host>
You are now ready to configure Tomcat to run a Struts application. The easiest way to try out Struts is to import some of the examples that are found in Struts’ webapps directory. Right-click your new Tomcat project and select import, followed by file system. Browse to the directory where you unpacked Struts, and select the webapps directory. Now click finish. Your screen should look something like that in Figure 2.
Figure 2: After running the import, your project should look like this |
Now you need some way to start and stop Tomcat within WDSc. I use the Sysdeo Eclipse Tomcat Launcher plugin. I am currently using Version 2.2.1 of the plug-in. After downloading the Tomcat launcher plug-in, unzip it to the WDSc or Eclipse plugins directory. On my system that is:
C:WSSDv5.1eclipsepluginscom.sysdeo.eclipse.tomcat_2.2.1
Restart WDSc or Eclipse, and open the Java perspective. Next, select Customize Perspective…, from the Window drop-down menu. Expand Other and check tomcat, which will put three new icons in your Java perspective that will allow you to start, stop, and restart Tomcat.
Now you need to configure the Tomcat launcher plug-in. Select Preferences from the Window drop-down menu, and click Tomcat, in the left panel. Your screen should look something like that in Figure 3.
Figure 3: Set up the Sysdeo plug-in to run Tomcat in WDSc |
Now select the Version 5.x radio button, and use the browse button to locate and select the directory where your Tomcat project resides. Now click the plus (+) sign next to Tomcat in the left pane, and click JVM Settings. Use the Add button to add the following settings.
-Dorg.apache.commons.logging.simplelog.defaultlog=debug -Dorg.apache.commons.logging.Log=org.apache.commons. logging.impl.SimpleLog -Dorg.iseriestoolkit.database.hibernate.configuration= /org/iseriestoolkit/span/db2.cfg.xml -Dorg.iseriestoolkit.database.connectionmanager.default-impl=org. iseriestoolkit.database.AS400ConnectionManager
These settings configure Tomcat to direct logging messages to the console and set up the span example so that it can connect to your iSeries system. After getting your applications to run, you should set the org.apache.commons.logging.simplelog.defaultlog property to warn. This will reduce the amount of logging. When you are done your screen should look like that in Figure 4.
Figure 4: Configure the Sysdeo plug-in properties and JVM |
If you have followed along so far, you are now ready to run the Struts examples. Click the start Tomcat icon. You should see some logging messages scroll by in the console, and after a few seconds you can run the examples. Open a browser, and try entering some of the URLs associated with the applications in the webapps directory, like http://localhost:8080/struts-example or http://localhost:8080/struts-validator. The source for these examples is included in the Struts source package available from where you downloaded the Struts binary package. The Struts examples demonstrate some Struts features, but there are no database examples.
The easiest way to create a new Struts application is to create a new Java project and use a utility like Winzip or the Java JAR utility to unpack the struts-blank.war file into the root directory of the new project. Right-click the new project and select Java Build Path. Now select Libraries and add all of the JAR files from your Tomcat common/lib and common/endorsed directories. Do the same to add all of the JAR files found in the WEB-INF/lib directory to your new project. Next, tell WDSc or Eclipse where to find Java source and class files for your new Struts application by selecting the Source tab, clicking add folder, and selecting the /WEB-INF/src directory. Now change the output folder to the project’s WEB-INF/classes directory. When you are done, your screen should be similar to that in Figure 5.
Figure 5: Set your Java build path and source directories |
A context entry in Tomcat’s server.xml file tells Tomcat how to load applications that are not contained in Tomcat’s webapps directory. The context entry goes under a host and looks something like the following example.
<Host name="localhost" debug="0" appBase="webapps" unpackWARs="true" autoDeploy="true"> <Context path="/span" reloadable="true" docBase="C:projectsspan" debug="99" /> </Host>
To continue where the Struts examples leave off, I wrote a sample Struts application named span, which demonstrates how to write a database application. You can download that application, which is part of the iSeries-toolkit, and run it using the context entry from the previous example. The Web Archive (WAR) version can be dropped into Tomcat’s webapps directory, or you can use a context entry, like the one shown above.
The span example builds on the example in “Sleep Soundly with Hibernate.” You will need to modify the sample properties files found in the WEB-INF/classes/org/iseriestoolkit/database directory to point to the correct URL, user, and password for your server. You will also have to create the database tables on your system by running the appropriate SQL script found in the sql directory or by temporarily setting the hbm2ddl.auto property to create in the db2.cfg.xml file.
At this point, you are ready to build and test your own Struts application. There is a lot more to learn, but reviewing the Struts examples and installing and modifying the Span application should get you a good start.
ANATOMY OF A STRUTS APPLICATION
The central component of Struts is the Struts action servlet. The action servlet takes information passed from HTML-based forms and loads that information into an action form, which stores information passed to and from the browser. After loading input to an action form, the action servlet calls your control logic. When your control logic is complete, the action servlet prepares the response for display and sends a response to the browser.
Struts uses a configuration file to associate action forms and classes with browser requests. This configuration file is defined in a Web deployment file (web.xml), located in the WEB-INF directory of a Struts application. You can have more than one Struts configuration file, separated by commas; however, most commonly there is a single struts-config.xml, defined as follows.
<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> <init-param> <param-name>debug</param-name> <param-value>3</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>3</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
The Struts action servlet simplifies Web programming in much the same way externally described files simplify green-screen programming on the iSeries with RPG or Cobol. The action servlet moves data between HTTP parameters and an action form, relieving you from the drudgery of parsing and interpreting servlet parameters passed from your HTML forms. The action servlet also simplifies message handing with action messages and message tags that provide functionality similar to a message subfile.
The diagram in Figure 6 shows the interaction between the components of a Struts application and how a typical Struts application processes a request. The Struts action servlet receives a request from a Web browser and loads HTML form data into an action form. After loading the action form, the action servlet calls the method in your action class associated with the request being made (add, update, or delete, for example). The method in your action class should do little more than invoke your business logic and interpret the results in order to send messages and determine the next page to display. Control then returns to the action servlet, which will generally invoke a JSP page, based on an action forward returned from your action class.
Figure 6: This is the basic flow of a typical Struts application |
In Figure 6, you see that MyAction receives an action form and calls your business logic. There are several types of action classes, but the one I recommend you use is dispatch action. A dispatch action extends org.apache.struts.actions.DispatchAction and contains a method for each action that a user can perform on a Web page. A dispatch action may also define an unspecified method that is called when no specific action is requested, like a refresh.
Although it is not a requirement, most Struts applications use JSP with embedded tags to display data. A JSP is a script that is compiled once at runtime into a servlet. Most JSPs that support Struts applications use custom Struts tags that encourage code reuse and help to overcome some of the problems associated with scriptlet code. Those problems include more difficult debugging and a minimal validation until runtime.
STRUTS ON TO THE ISERIES
Most of the work in getting Struts to run on the iSeries is getting WAS or Tomcat installed, configured, and running. If you need to install a servlet container on your iSeries, I recommend that you start with Tomcat, because it is free and easier to install. You can follow the instructions at the link I gave you earlier to install Tomcat; however the startup scripts I wrote for that article are now incorporated into the catalina.sh startup script, which comes with recent Tomcat builds. That means you can use the startup.sh script that comes with Tomcat to start and stop Tomcat.
I replaced the touch command in the original catalina.sh script to set the code page to ASCII, so that I could use Wordpad to view the log from a drive mapped to my iSeries system. Here are the replacement lines.
if $os400; then # Use ASCII code page rather than EBCDIC touch -C 819 "$CATALINA_BASE"/logs/catalina.out else touch "$CATALINA_BASE"/logs/catalina.out fi
You can simply export or copy your working Tomcat and Struts projects directly to the iSeries, to test on the iSeries, but in the long run you are better off learning how to use Ant to build and deploy your applications. See “Building Applications with Ant” to learn more about Ant.
SMOOTH LANDING
To build well-organized, enterprise-ready Web applications, you need a plan and experienced developers. Struts supplies the plan, along with a team of dedicated developers that have built a top-quality Web application framework. You can’t walk down the hall to talk to those developers, but who needs to, when you can get answers on the Struts user mailing list? Another selling point is price. Since Struts is free, all you have to invest to try out Struts is time, and no salesman will ever call.
The MVC design pattern Struts encourages helps you to build organized applications that are easy to understand and maintain. With Struts you spend less time worrying about how to connect the components of your applications and more time working on the code that really matters.
The “span” example I wrote for this article provides most of the functionality you will need to build Web applications, including basic security, connection pooling, multi-platform support, and a sample deployment script. To keep things simple, span doesn’t support features like concurrent updates to multiple database, but that doesn’t mean Struts isn’t up to the task.
David Morris is a software architect who writes Java applications during the day and started the iSeries-toolkit open-source project. E-mail: dmorris@itjungle.com.