Professional Documents
Culture Documents
Summary
Software Consultant and Developer
Resources
08 Apr 2004
About the author
This article shows you how to develop a Struts application in the Eclipse IDE, with the help of the Easy
Related content:
Struts plug-in. You'll get an introduction to Easy Struts, installation and configuration steps, and All Eclipse articles on developerWorks
instructions on building a basic Struts application through a progressive example. Different ways of
enhancing the Struts application -- such as connecting to a database, modularizing the application, Books on Struts application development
internationalizing and localizing content, handling exceptions, and creating custom plug-ins -- are also Tune Eclipse's startup performance with the Runtime Spy, Part 1
covered. Finally, you will learn how to deploy your Struts application on the Tomcat Web server. Tune Eclipse's startup performance with the Runtime Spy, Part 2
The Easy Struts plug-in manages all the complex configuration files, so you can focus on developing logic. Let's
Extend Eclipse's Java Development Tools
look at the 10 functions of Easy Struts that help you build a complete application:
Debugging with the Eclipse Platform
1. Add Easy Struts support. Adds all the necessary Struts libraries to the project classpath, and creates Subscriptions:
the configuration files and the default resource properties file. dW newsletters
2. Easy Form. Creates a JSP file with the form properties, as well as a Form bean class with form dW Subscription
properties getter and setter methods, and adds a form bean definition to the configuration file. (CDs and downloads)
3. Easy Action. Creates an Action class and adds an action mapping definition to the configuration file.
4. Easy Action associated with a form. Creates a JSP file with the form properties, a Form bean class with form properties getter and setter
methods, and an Action class. Also addes a form bean definition and an action mapping definition to the configuration file.
5. Easy Forward. Creates local forwards and global forwards, which define where the control will be forwarded to.
6. Easy Exception. Handles exceptions.
7. Easy Message resources. Creates resource properties files, which is especially important for internationalization and localization of content.
8. Easy Plug-in. Creates plug-ins.
9. Easy Datasource. Connects the application to a data source.
10. Easy Module. Modularizes the application.
In this article, we will cover 8 of the 10 functions (we will not cover functions 2 and 3: Easy Form and Easy Action). Before you can start developing a
Struts application, you should have all the necessary programs and plug-ins installed, and know the basics of Java programming, HTML, and JSP
scripts, as well as XML and XSLT.
Installation
See the Resources section below for download links to the following:
1. Download Eclipse v2.1 from the Eclipse Web site. You can install it by unpacking it to any folder of your choice, which we will refer to as
eclipse_home in this article.
2. Download Struts 1.1 from the Apache Web site. You can install it by unpacking it to any folder of your choice, which we will refer to as
struts_home in this article.
3. Download the Tomcat Web server from the Apache Web site. You can install it by unpacking it to any folder of your choice, which we will
refer to as tomcat_home in this article. This article assumes v4.1.18.
4. Download the latest Tomcat plug-in for Eclipse from the Sysdeo Web site. You can install it by unpacking it to eclipse_home/eclipse/plugins.
This article assumes v2.2.
5. Download Easy Struts for Eclipse plug-in v0.6.4 from SourceForge. You can install it by unpacking it to eclipse_home/eclipse/plugins.
6. Download the J2SE SDK from the Sun Web site. You can install it in any folder of your choice, which we will refer to as java_home in this
article. This article assumes v1.4.2.
7. Download the MySQL database server from the MySQL Web site. You can install it in any folder of your choice.
8. Download the JDBC driver for MySQL from the MySQL Web site. You should unpack it and copy and paste mysql-connector-java-x.x.xx-
stable/mysql-connector-java-x.x.xx-stable-bin.jar to your project workspace. We will return to this later. This article assumes v3.0.
Configuration
Configuring the Sysdeo Tomcat Plug-in
1. Start Eclipse.
2. Configure the Tomcat plug-in. To do this, go to the "Window" menu, select the "Preferences" item, and choose the "Tomcat" option on the
popup view. Then do the following:
❍ Set "Tomcat version" to your Tomcat version.
❍ Set "Tomcat home" to tomcat_home/jakarta-tomcat-4.1.18.
❍ Set "Perspective to switch when Tomcat is started" to Java.
❍ Under Option "Tomcat", suboption "JVM Settings" -> "Classpath", add the Jar/Zip for tools.jar, which is in the folder java_home/lib/.
This is for compiling JSPs.
3. Set the classpath variable TOMCAT_HOME for project classpath reference. To do this, choose the option "Java" on the same popup view as
in step 2, select suboption "Classpath Variables" and add a new variable "TOMCAT_HOME" whose path is tomcat_home/jakarta-tomcat-
4.1.18.
4. Ensure that the "Tomcat" menu and the 3 toolbar buttons are accessible. By now, you should be able to see a "Tomcat" menu and 3 Tomcat
toolbar buttons (as shown in Figure 1) in the Java perspective. If not, go to the "Window" menu, choose the "Customize Perspective..." item,
open the option tree marked "Other" and check the "Tomcat" suboption.
5. Make sure the Sysdeo Tomcat plug-in works. To verify, use the menu or toolbar to Start/Stop Tomcat.
To configure the Easy Struts Plug-in, refer to Figure 2 and do the following:
1. Select a Struts version. To do this, go to the "Window" menu, choose the "Preference" item, choose the "Easy Struts" option and select the
"Struts 1.1" tab.
2. Add JARs. You should add "Add JARs" for all .jar files in struts_home\jakarta-struts-1.1\lib.
3. Add TLDs. Next, add "Add TLDs" for all .tld files in struts_home\ jakarta-struts-1.1\lib.
1. Go to the "Java" option, select "Tomcat Project" and click "Next" (see also Figure 3).
2. Fill in the project name and click "Next" (see also Figure 4).
3. Check "Can update server.xml file". The system will update your server.xml file of the Tomcat Web server automatically. You may click
"Finish" to complete the task now (see also Figure 5).
1. Click the "New" toolbar button, select the "Easy Struts" suboption from the "Java" option, choose "Add Easy Struts support" and click "Next"
to forward to the next step (see also Figure 7 -- we will refer to this view as the Easy Struts functions view in the rest of this article).
2. Do the configurations shown in Figure 8. Ensure "Copy Struts binary" and "Copy Struts TLD" are checked.
Figure 7 shows the 10 functions provided by Easy Struts. We have looked at "Add Easy Struts Support". In the rest of this article, we will look at the 7
remaining functions (excluding "Easy Action" and "Easy Form"). In the rest of this section, we will use the "Easy Action associated with a form" and
"Easy Forward" to build a simple but complete Struts application. "Easy Message resources", "Easy Plug In", "Easy Datasource", "Easy Exception"
and "Easy Module" will be covered in the next section.
1. Type in Use case; the Form name and Form type will be generated based upon the Use case by the system. You can modify the Form name
and Form Type manually (see also Figure 10).
2. Click "Add" in the Form properties block; use the view shown in Figure 11 to add form properties. For example, as shown in the figure, we
are trying to add a text input field with the name "tel" and the value of "tel" should be of type int. We set "tel" to the initial value of zero. We
can type in or use "Browse" for the "Type". We can type in or use pull down selection for the "JSP input type". The Struts system will
generate a pair of getter and setter methods for each form property in the form bean class. Therefore, for a selection list, you should only
create one <html:select> but not all the <html:option>s.
3. Since you are developing a Web application, check the first two check boxes.
4. click "Next" to continue.
By now, you should see something very similar to Figure 12. By default, the input value is "/form/owner.jsp", which means the JSP file is put in the
"easyStruts/form" folder. You can change the JSP file location manually or by changing the preference setting. To change the preference setting, go
to the "Window" menu, select "Preferences", click the "Easy Struts" option, choose the "Style" tab and set the "JSP form location" to blank. For
example, in this article, we prefer the JSP files are stored directly in the easyStruts (project name) folder. So, change it to "/owner.jsp" as shown in
Figure 12.
● Path. Is the context-relative path of the submitted request. The path must have a prefix "/" and be unique.
● Type. Is the name of the Action class being described by this ActionMapping.
● Attribute. Is the name of the request-scope or session-scope attribute under which the form bean is accessed, if the name is not the same
as the bean's specified name.
● Scope. Specifies how long the values of a form bean, associated with this mapping, should be saved.
● input. Specifies the context-relative path of the input form to which control should be returned if a validation error is encountered.
● Validate. If this is set to true, it indicates the ActionForm.validate() method should be called on the form bean associated to this mapping.
● Parameter. Can be used to pass extra information to the Action selected by this mapping.
Click "Next" and you should see something very similar to Figure 13. The properties shown in Figure 13 are action mapping properties, as follows:
● Forward. Specifies the context−relative path of the servlet or JSP resource by which this request will be processed. ActionMapping can use
findForward() to forward the control to the servlet or JSP resource.
● Exception. The ExceptionHandlers associated with this mapping.
The forward and exception here are both local. We will discuss the global forward and exception later.
After you click "Finish" (see Figure 14), the system will generate com.asprise.struts.form.OwnerForm. Local forward attributes:
java and com.asprise.struts.action.OwnerAction.java in easyStruts/WEB-INF/src/. Another file
generated at the same time is easyStruts/owner.jsp. You will make some changes to the three files in
● name is the unique identifier, which can
the following sections, to complete the form, add user inputs validation methods and process the be used in the action mapping's
validation errors. findForward() method to return the path.
● The contextRelative tag tells Struts that:
❍ If it is set to true, path should
Figure 14. Add forward be considered relative to the
entire Web application.
❍ If it is set to false, path should
be considered relative to the
module of a modular
application.
● If redirect is true, control will be
transferred to the page with a redirect but
not a forward. It means that a new request
is created.
"error.noEmail" in ActionError("error.noEmail") is a key defined in the resource properties file, which is equal to "<li><font color=red>Enter your
email</font> ". <html> code can be used in resource properties files. The argument property, in the method add(java.lang.String property,
ActionError error) of ActionErrors class, is the name of a form property. This ActionError will only associate with the specified form property. For
example, if email address is null or only contains spaces, the message "Enter your email" will be shown when the form is validated. If there is no "@"
character in the email address, "Correct your email" will be shown, which is defined in the resource properties file with the key "error.wrongEmail".
Both errors are only associated with the form property "email" (refer to Listing 1). We will return to this later.
Listing 1. OwnerForm.java
package com.asprise.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
<html> code can be used in resource properties files. The content of a resource property file is key-value pair (see Listing 2). The keys can be called
in a source code file. The two keys errors.header and errors.footer are required by the system in every resource properties file.
Listing 2. ApplicationResources.properties
errors.header=<h4>Validation Error(s)</h4><ul>
errors.footer=</ul><hr>
Listing 3. OwnerAction.java
public class OwnerAction extends Action {
return (mapping.findForward("success"));
}
}
Listing 4. owner.jsp
Now, code success.jsp to display a message like "Thank you, Miss Nancy Chen". "Miss" is the greet of owner and "Nancy Chen" is the name of
owner. The resulting file is shown in Listing 5.
Listing 5. success.jsp
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<logic:present> is one of the Struts logic tags. When the logic tag is with attribute "name", it is to check for the existence of a JSP bean with the
specified name, in any scope. For the full list of <logic:present> attributes and the full list of Struts logic tags, refer to the Struts User Guide.
<bean:write> is one of the Struts bean tags. It is used to render the value of the specified bean property to the current JspWriter. When the bean tag
has the attribute "name" and attribute "property", it specifies the attribute name of the bean whose property is accessed to retrieve the value
specified by "property". If no "property" attribute is specified, the value of this bean itself will be rendered. For the full list of <logic:present> attributes
and the full list of Struts logic tags, refer to the Struts User Guide.
Go to the Easy Struts functions view and click "Easy Forward". As a result, you should see something similar to Figure 19. If you leave the "Visibility"
as blank, the result forward will be global. If you click the "Browse" button and choose "/owner", as shown in Figure 20, the result forward will be a
local forward. Regardless of whether the forward is global or local, they can be referred in the Action class as mapping.findForward("failure");
We have already discussed "name", "Redirect" and "Context relative" attributes, shown in Figure 19, in the "Easy Action associated with a form"
section.
For example, the code shown in Listing 6 is our .xsl file. For each form property, it generates "property" and "value" attributes. For example, if you
specify a text input named "name" with an initial value "nancy", the generated line in the JSP file will be name: <html:text property="name"
value="nancy"></html:text>
Listing 6. myJsp.xsl
Note: for the full list of two letter ISO-639 language codes, visit the languages page at Unicode.org. And for the full list of two letter ISO-3166 country
codes, visit the countries page at Unicode.org
Figure 21. Create Chinese message resource Easy message resource attributes:
Resource properties files can be easily edited. You can use Notepad for the Chinese resource properties file. ApplicationResources_zh_CN.
properties should be saved as Unicode (UTF-8) encoding. Next, set the local language to Chinese and location to China (in the case of Windows,
you can do so using the Regional and Language Options in the Control Panel). Restart Tomcat to reflect the changes, and go to
http://127.0.0.1:8080/easyStruts/owner.jsp. Now the validation errors are displayed in Chinese, as shown in Figure 22.
Next, start the MySQL server, and create the database "crm" and the table "owner" as shown in Listing 7.
Next, modify the execute() method in the OwnerAction class to connect to the database (refer to Listing 8). As you can see, this is where the key
property used in the Easy Datasource comes into play. "org.apache.struts.action.DATA_SOURCE" is our key for datasource. Note that we catch the
SQLException and rethrow it. In the next section, you will code your own exception handler to handle the SQLException.
You should restart the Tomcat server to let it connect to the data source on starting up and go to http://127.0.0.1:8080/easyStruts/owner.jsp. If all the
inputs are correct, a record will be inserted into the "owner" table and control will be forwarded to success.jsp. You can check with the database
whether there is a new record in the table "owner".
After clicking on "Finish", the exception is declared. Then you should code the MyExceptionHandler.java (see Listing 9). It extends the
ExceptionHandler class and like the Action class, it also implements the execute() method to return an ActionForward. As you can see, the "path"
property of the Easy Exception can be retrieved using the getPath() method of ExceptionConfig class. You can get the key property using the getKey
() method of ExceptionConfig class.
Listing 9. MyExceptionHandler.java
package com.asprise.struts.exception;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.config.*;
In the exception declaration, if an SQLException occurs, the control will be redirected to exception.jsp. Our exception.jsp displays the message
defined in the default resource properties file with key "error.database", the exception type and the exception message when the exception is thrown.
You can retrieve the exception key in MyExceptionHandler. You supply the key retrieved to the <bean:message> tag as shown in Listing 10.
<%
OwnerForm myForm = (OwnerForm)request.getAttribute("myForm");
if (myForm != null) {
out.println("<font color=red>Sorry, "+myForm.getGreet());
out.println(" "+myForm.getName()+"</font>");
}
%>
<ul><bean:message key="<%=request.getAttribute(\"myKey\").toString()%>" />
<%
Object obj = request.getAttribute("myException");
if (obj != null) {
Throwable ex = (Throwable)obj;
out.println("<li><b>Type:</b>"+ex.toString());
out.println("<li><b>Message:</b>"+ex.getMessage());
}
%>
Define "error.database=<h3>An Exception Handled by MyExceptionHandler:</h3>". When an SQLException occurs, you should see something
similar to Figure 25.
Restart Eclipse to reflect the new module. If there is an error org.xml.sax.SAXParseException: The content of element type "servlet"
must match "(icon?,servlet-name,display-name?,description?,(servlet-class|jsp-file),init-param*,load-on-startup?,run-as?,
security-role-ref*)"when the Web application starts, you can solve it by moving the new module configuration part directly below the one of
default module in web.xml.
There are two ways to switch to the new module. First, create a new forward "success" as global or local in struts-config.xml (see Listing 11). Then
you can switch to the new module by using mapping.findForward("success").
Next, code easyStruts/newModule/index.jsp. The index.jsp displays only one message "<h1>You are in module: newModule</h1>".
Now, start the Tomcat server, and enter http://127.0.0.1:8080/easyStruts/switchTo.do?prefix=/newModule&page=/index.do. The result is shown in
Figure 27. If you want to switch back to the default module, you can enter http://127.0.0.1:8080/easyStruts/switchTo.do?prefix=&page=/owner.jsp
Note: You can specify the module name in all the Easy Struts functions except "Add Easy Struts support".
To create a plug-in, go to the Easy Struts functions view, select Easy Plugin, type in Plugin class and add "Add" for properties. Add proxy and port
properties, as shown in Figure 28.
Then, code the MyPlugin class, as shown in Listing 13. It implements the Plugin class. When the Web application starts, it displays a message
saying "MyPlugin starting" and sets the system's proxy and port. When the Web application shuts down, a "MyPlugin Stopping" message is
displayed.
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.action.ActionServlet;
public MyPlugin(){
}
In the source code of JSP or another Java file, you can use getServletContext().getAttribute("proxy") to get the proxy value.
1. Go to the "Project" menu, choose the "Properties" menu, select the "Tomcat" option and click the "Export to WAR settings" tab.
2. Click "Browse" of the "WAR file for export", and set the value to folder-of-your-choice/easyStruts.war. Save the setting.
3. Then go to project popupmenu, select "Tomcat project" and click "Export to the WAR file sets in project properties" from the submenu.
4. After the message "Operation successful" is displayed, you can go to the location specified in step 2 to get the WAR file.
Summary
In this article, we walked through the Easy Struts functions to develop a Struts application running on the Tomcat Web server. You learned how to
process form properties validation, how to create local and global forward and exception, as well as how to do exception handling, how to connect to
a data source, internationalize/localize the content, modularize the application, create custom plug-ins, as well as distribute the application to your
clients.
Resources
● Get a hands-on tutorial on using the Jakarta Struts Framework to build Java Web applications in Mastering Jakarta Struts by James
Goodwill (John Wiley & Sons, 2002).
● Solid coverage of the Struts framework is in Struts Kick Start by James Turner & Kevin Bedell (SAMS, 2002).
● For a Struts guide for experienced programmers, see Struts in Action by Ted N. Husted, Cedric Dumoulin, George Franciscus & David
Winterfeldt (Manning Publications Company, 2002).
● For a comprehensive guide to Eclipse plug-in development, see The Java Developer's Guide to Eclipse, by Sherry Shavor, Jim D'Anjou, Dan
Kehn, Scott Fairbrother, John Kellerman, and Pat McCarthy (Addison Wesley Professional, 2003).
● Find more articles for Eclipse users in the Open source projects zone on developerWorks. Also see the latest Eclipse technology downloads
on alphaWorks.
● You'll find hundreds of books on open source topics in the Open source section of the Developer Bookstore, including several books on
Eclipse and books on Struts application development.
Killer! (5) Good stuff (4) So-so; not bad (3) Needs work (2) Lame! (1)
Comments?
Submit feedback