Struts 1 & Eclipse - First Steps
MyStrutsHelloWorld
(Note: Struts 2 Tutorial is Available!)
(Free Web Tutorial)
by Michael Thomas
Struts Home Page
NOTE: A Struts 2 tutorial is available! I'm
keeping this version of the Tutorial for those still working with Struts 1.
This web page will help you get started with Struts 1.2.8 framework
running on Tomcat 5.5 Web Application Server using the Eclipse 3.1.1 IDE.
This tutorial needs to be updated to the current versions but it should work as
is.
The next section is "Reference Info". Refer to it as needed. Now
skip to the section "First Steps - Struts & Eclipse (IDE)"
Reference info - Refer to this
section as needed. Now skip to the next section.
- You can download the final solution for reference
- Stop/Start the "Apache Tomcat" service - (Start, Control Panel,
Administrative Tools, Services). You can stop and/or start the service
"Apache Tomcat" here.
- Reload a Web App (using Tomcat Manager)
- Goto: http://localhost:8080/
- Click on "Tomcat Manager"
- User: admin
Pswd: <enter your password>
- Click "Reload" (Or you can click Stop, then Start)
- Note: You will need to do a "Reload" when ever you do the
following:
- Change a property file.
- Change a Java source/class file.
- Change an XML file used for configuration: web.xml, struts-config.xml,
etc...
- Note: You DO NOT need to "Reload" when you do the following:
- Change a JSP file.
- Change a HTML file.
- Tomcat install directory location:
C:\Program Files\Apache Software Foundation\Tomcat 5.5
- Tomcat common library directory
- C:\Program Files\Apache Software Foundation\Tomcat
5.5\common\lib
- Location of the Web App we will create:
Directory: C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\mystruts-helloworld
URL:
http://localhost:8080/mystruts-helloworld
- Additional Notes
- Caching problems - Tomcat does keep a working directory copy
of the webapps. If you reuse directory names, copy files with
older dates into a directory, or are having weird cache issues delete
the working directory for the web app. Make sure you stop the
"Apache Tomcat" service first. You may want to try Stop/Starting
the web app first.
C:\Program Files\Apache Software Foundation\Tomcat 5.5\work\Catalina\localhost\
First Steps - Struts & Eclipse (IDE)
Setup Eclipse & the Struts Webapp
- Pre-requests: Java SDK, Eclipse, Tomcat & Struts. If you
need help with the pre-requests click on this link
Free Java Training & Resources
- struts-blank Web App - Test the web app.
- After completing the Struts installation you should have the file "struts-blank.war"
in your Tomcat webapps directory.
- Launch the application with the following URL:
http://localhost:8080/struts-blank
- You should see a welcome page.
- Create a blank Struts Web Application called: mystruts-helloworld
Choose one of the following options
- Option A - copying a directory
- Stop the "Apache Tomcat" service (see Reference
Info).
- In Win Explorer go to the Tomcat install directory and locate
the "webapps" folder (see Reference info above).
- Make a copy of the directory "struts-blank" to a
directory
called "mystruts-helloworld".
- Start the "Apache Tomcat" service.
- Option B - using a .war file.
- In Win Explorer go to the Tomcat install directory and locate
the "webapps" folder (see Reference info above).
- Make a copy of the file "struts-blank.war" to a
temporary directory (ie: c:\temp
etc...) and rename the file to: "mystruts-helloworld.war".
You can find the .war file in the Tomcat install directory (see
Reference info above).
- Copy the file back to the Tomcat install directory.
Note: Tomcat will automatically create the web application
(directories & files) from the .war file.
- At your convenience you can remove the .war file by following
the following steps:
- Stop the "Apache Tomcat" service (see
Reference Info).
- Delete the .war file
- Start the "Apache Tomcat" service.
- Note: If you don't stop the service first I've
noticed that Tomcat may remove the directory also (weird in my
opinion).
- mystruts-helloworld Web App - Test the web app.
- Eclipse - Create a Java Project
- Launch Eclipse
- File, New, Project, Java Project, Next
- Project Name: mystruts-helloworld
- Contents: "Create project from existing source".
- Click "Next"
- Click "Browse" and locate the directory in the Tomcat WebApp
directory.
Click "OK"
- On the "Java Settings" screen change the "Default output folder" to:
mystruts-helloworld/WEB-INF/classes
- If you see the prompt "The output folder has changed ...." click
"Yes"
- Click "Finish"
- Eclipse - Build Path - Tomcat lib jars - add these files
to the build path.
- Right click on the project.
- Click "Build Path", "Configure Build Path", then
click the tab "Libraries"
- Click "Add External JARs"
- Browse to the Tomcat common library directory (see Reference info
above)
- Select all of the JAR files and click "Open".
- Click "OK" to leave the "Java Build Path" screen.
- Now you can compile java programs that access Struts classes.
- Eclipse - Struts Library Files - FYI
- Eclipse - Source Folder
- We need to create a source folder where we can place our Java Source
code. Currently we have a folder but we need to let Eclipse know
it is a source folder.
- In Eclipse, Right click on the mystruts-helloworld project and
choose "New", "Source Folder".
Folder name = WEB-INF\src
- MessageResources.properties - currently this file is sitting in a
package called "java". If we were to make changes to this file in
Eclipse, Eclipse will automatically copy the updated file to our output
folder:
mystruts-helloworld/WEB-INF/classes/java
- With Win Explorer notice that the file doesn't exist in the /classes/java directory. It did originally exist in the
/classes when we first installed the web app from "struts-blank".
- Using Eclipse, open the file: WEB-INF\src\java\MessageResources.properties
- Add a blank line to the end and then delete the blank line.
Now press CTRL-S to save the file.
- Using Win Explorer, notice that the updated file was also copied to
the: /classes/java directory
- In the next step we will tell our web app where to find the new file
and then delete the one in the /classes directory.
- struts-config.xml - MessageResources.properties
- We need to tell Struts to get the property file from the new
location where Eclipse automatically copies changes to the source file.
- Edit the following file: WEB-INF\struts-config.xml
- Make the following change:
Was: <message-resources parameter="MessageResources"
/>
Now: <message-resources parameter="/java/MessageResources"
/>
- Save the file.
- Now delete the old resource
file, unless Eclipse deleted it earlier for you, at: WEB-INF\classes\MessageResources.properties
- mystruts-helloworld Web App - Test the web app.
- Eclipse - Create a Package: com.michaelthomas.mystrutshelloworld
- We need to create a Package where we can place our Java Source code.
- In Eclipse, Right click on the "WEB-INF/src" source folder and
choose "New", "Package".
Name = com.michaelthomas.mystrutshelloworld
Code Changes via Eclipse (IDE) & Code Walk-through
- For the purpose of learning we will strip down the source code
of the web app to the bare bones.
- Edit WEB-INF\web.xml
- Change the "display-name" tag to read:
<display-name>My Struts Hello World Example</display-name>
- Notice the following entries:
- The servlet's "config" property = /WEB-INF/struts-config.xml
- The servlet's "debug" property = 2
- The servlet's "detail" property = 2
- The servlet's "load-on-startup" property = 2
- All action servlets start with: *.do
- The <welcome-file> = index.jsp
- Then there is a list of standard Struts Tag Libraries (<taglib>)
FYI - notice the taglib: /tags/struts-logic. This will be
referenced in index.jsp.
- Edit WEB-INF\index.jsp
- When the web app is launched with
http://localhost:8080/mystruts-helloworld
this is the web page that displayed.
Notice the following code:
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<logic:redirect forward="welcome"/>
- FYI (optional) - for the techy guy, looking at struts-logic.tld the
shortname tag = "logic". Also, the tag "redirect" uses the class "org.apache.struts.taglib.logic.RedirectTag".
- The logic:redirect tag uses the Struts servlet container to locate
the forward called "welcome" in the <global-forwards> section of struts-config.xml.
- Edit WEB-INF\struts-config.xml
- Find the the <global-forwards> tag. Locate the
forward property named "welcome". Notice that is will forward to
path="/Welcome.do". All references to *.do according to web.xml
will call an Action.
- Look for the <action-mappings> tag section and find the action with
path="/Welcome". This logic then forwards us to: forward="/pages/Welcome.jsp".
- The next file we will look at is the "Welcome.jsp". Remember
that the "index.jsp" does a redirect to this page.
- mystruts-helloworld Web App - Test the web app.
- Edit WEB-INF\pages\Welcome.jsp
- The servlet container sees the tag "bean:message" and replaces the
key mentioned with the matching value found in the file resource
property file: WEB-INF\classes\MessageResources.properties
Ex: <p><bean:message key="welcome.message"/></p>
- Add the following code at the bottom of the file before the tag
</body>
<p><html:link action="/Logon"><bean:message key="welcome.logonlink"/></html:link><bean:message
key="welcome.logonmessage"/></p>
<p><html:link action="/Help"><bean:message key="welcome.helplink"/></html:link><bean:message
key="welcome.helpmessage"/></p>
- Save the file.
- NOTE: You will need to make a change to the resources file for
this change to work.
Launch the web app and see the error (HTTP Status 500):
javax.servlet.ServletException: Missing message for key "welcome.logonlink"
The next section will correct this error.
- Edit WEB-INF\src\java\MessageResources.properties
- We need to add the following keys: welcome.logonlink &
welcome.logonmessage. Add the following code to the bottom of this
file:
welcome.logonlink=Logon
welcome.logonmessage= -
logon
page
for
the
webapp
"mystruts-helloworld"
(jsp).
welcome.helplink=Help
welcome.helpmessage= -
help
instructions
(html).
- Save the file and Eclipse will copy it to: WEB-INF\classes\java
- "Reload" the web app via Tomcat Manager.
- Notice the addition of the logon link on the welcome screen.
- Change the following: (leave the other code as is)
welcome.title=My
Struts
Hello
World
welcome.heading=Welcome
to
"My
Struts
Hello
World"
welcome.message=This
web
app
is
an
example
of
a
"Hello
World"
type
Struts
application.
- Save the file.
- Test the web app without doing a "Reload". Notice that the
changes did not take effect.
- "Reload" the web app via Tomcat Manager.
- Notice that the changes are now visible.
- The Welcome Screen should look like this.
Welcome to "My Struts Hello World"
This web app is an example of a "Hello World" type Struts
application.
Logon-
logon page for the webapp "mystruts-helloworld" (jsp).
Help-
help instructions (html).
- Help Link - Error
- Click on the "Help" link and see the error.
Message: Invalid path was requested
- The Address bar (URL) of IE will give you a hit as to where the
problem lies.
http://localhost:8080/mystruts-helloworld/Help.do - (Note: Help.do is an invalid path.)
- Also the "catalina.yyyy.mm.dd" log in the directory "Tomcat
5.5\logs" has the details to the error.
ex: SEVERE: Invalid path was requested /Help
- Help Link fix - help.html
- In Eclipse right click on the "pages" directory then choose New,
File.
File name = help.html
Click "Finish"
(Now close the file in Eclipse. It tried to load the empty .html
file.)
- Right click on "help.html", "Open with", "Text Editor".
- Enter the following code and save:
<html>
<title>Help Screen</title>
<body>
<h1 align="center">Help Screen</h1>
<p>Help info goes here.</p>
</body>
</html>
- Help Link Fix - WEB-INF\struts-config.xml
- Add the following code to the <action-mappings> section:
(before the closing tag: </action-mappings>)
<!-- Display the "Help" documentation -->
<action
path="/Help"
forward="/pages/help.html">
</action>
- Save the file.
- Delete the Commented Sample Code - you may delete the sample
actions that are commented out (between the tags: <!-- --> ).
There are 3 sample action entries: Input, InputSubmit, /edit*
- mystruts-helloworld Web App - Test the web app.
- Logon Link Fix - WEB-INF\struts-config.xml
- Add the following code to the <action-mappings> section:
<!-- Display the "Logon" page -->
<action
path="/Logon"
forward="/pages/logon.jsp">
</action>
- Logon Link Fix - WEB-INF\pages\logon.jsp
- In Eclipse right click on the "pages" directory then choose New,
File.
File name = logon.jsp
Click "Finish"
- Enter the following code and save:
Logon.jsp (A)
- cut-n-paste (if you type it you will learn more!) the contents of this file into your file.
- Save the file.
- Logon Link Fix - WEB-INF\src\java\MessageResources.properties
- Logon - Add Form - logon.jsp
- Now we need to add an HTML form to the JSP page to get the User name
& Password.
- We will use the following Struts tags so that the servlet container
will server out the necessary HTML code.
html:form
html:text
html:password
html:submit
html:reset
- Add the following code before the </body> tag:
<html:form action="/LogonSubmit"
focus="username">
<table>
<tr>
<td><bean:message key="logon.username"/></td>
<td><html:text property="username" size="16" maxlength="18"/></td>
</tr>
<tr>
<td><bean:message key="logon.password"/></td>
<td><html:password property="password" size="16" maxlength="18"
redisplay="false"/></td>
</tr>
<tr>
<td> </td>
<td><html:submit property="Submit" value="Submit"/> <html:reset/></td>
</tr>
</table>
</html:form>
- Logon - Add Form - logon.jsp - WEB-INF\src\java\MessageResources.properties
- Add the following keys to the properties file.
logon.username=User
Name
logon.password=Password
- Save the file and Eclipse will copy it to the /classes/java
directory.
- Logon - Add Form - WEB-INF\struts-config.xml
- Add the following code to the <action-mappings> section.
<!-- Process a user logon -->
<action path="/LogonSubmit"
type="com.michaelthomas.mystrutshelloworld.LogonAction"
name="logonForm"
scope="request"
input="/Logon.do">
<forward name="success" path="/MainMenu.do"/>
<forward name="failure" path="/Logon.do"/>
</action>
- My Comment: The login.jsp page will post the "logonForm"
to the servlet "LogonAction.class" via the request object. If
LogonAction returns a "success" then Struts will resolve the
action /MainMenu.do. If LogonAction returns "failure" then
Struts will resolve the action /Logon.do.
- Add the following code to the <form-beans> section.
<!-- Logon form bean -->
<form-bean
name="logonForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="username" type="java.lang.String"/>
<form-property name="password" type="java.lang.String"/>
</form-bean>
- Commented Sample Entries - You may delete the sample XML
entries in this section if you want. There is 2 sample
sections that are currently commented out between the tags: <!--
--> . The sample form beans are: inputForm & logonForm
- My Comment: Here we describe the "logonForm" Form Bean
that we made reference to in the <action> tag above. We also state
that we will use Struts Validator "DynaValidation" to validate the
Form. This way we can do basic validation from an XML file
without having to creating a java "ActionForm" object to validate
the form.
- Logon - Test Screen.
- "Reload" the web app via Tomcat Manager.
- Test the web app. You should see the addition of a
form with 2 text fields, a submit button and reset button.
- Test - Logon Validation
- Don't enter any values in the 2 fields.
- Click "Submit"
- The Validator comes back with:
- User Name is required.
- Password is required.
- We want to add some additional instruction when there is an error.
- Logon Validation - WEB-INF\src\java\MessageResources.properties
- The DynaValidator gets is message values from the properties file.
- Edit the properties file.
- Notice the following key: errors.invalid={0}
is
invalid.
- FYI: This is where the Validation message for the User Name
and Password comes from. Words "User Name" and "Password" comes
from entries in the tag "<arg key>" (ie: <arg key="logon.username"/>)
in the file "validation.xml".
- The header & footer (also prefix & suffix) for the error message
comes from the key values: errors.header & errors.footer. Lets
change this to give a more user friendly message. Make the
following change to the properties file.
errors.header=<h3><font
color="red">Validation
Error</font></h3><p>You
must
correct
the
following
error(s)
before
proceeding:</p><UL>
- Logon - Test Screen.
- Validation - validation.xml
- Note: There is 2 other files involved in the Validation:
validation.xml & validator-rules.xml. These files came from the
"struts-blank" webapp. Review the following file: WEB-INF\validation.xml.
Look for the first tag in the <formset> section called <form name="logonForm">.
The example form happens to be exactly what we want for the form "logonForm".
The default form tag is in English (no language specified). There is
another tag <formset language="fr"> which has the code for then language
"French".
- struts-config.xml - look for the tag "plug-in" and locate the
property for the Validator Plugin.
- validation.xml - change the XML comment:
From: <!-- An example form -->
To: <!-- Logon Form used by logon.jsp -->
- While you are in this file to the <formset> section. This
section happen to be already created for you when you made a copy of the
web app "struts-blank". Anytime you create a new form you will
need to make an entry in the .xml file for your custom form.
- Study the tag: <form name="logonForm">.
- <arg key="logon.username"/> - this tag tells the Validator to look
in the properties file for the key "logon.username" and pass the value
(text message) as an argument ( {0} )
to build the validation message you see (Note: errors.invalid={0}
is invalid. ).
This is a little techy so I suggest that you make some changes to these
properties and see the effects. If you change the <arg key> value
to a key that is not in the properties file you will see the words "null
is invalid". I'm sure you will make these types of coding errors
in the future so I suggest that you play with this code now!
- Logon - Test Screen.
- "Reload" the web app via Tomcat Manager.
- Go to the logon page.
- Now enter values in both the "User Name" and "Password". Click
"Submit" and notice the next error.
- Error: No action instance for path /LogonSubmit could be
created
- Error - LogonSubmit.do
- Look at the html code created by the servlet container for Logon.do.
To do this launch the web app and go to the Logon Screen. Now
right click and "View Source".
- Notice the following HTML code:
<form name="logonForm"
method="post" action="/mystruts-helloworld/LogonSubmit.do">
- Notice that when the "Submit" button is pressed the action
"LogonSubmit.do" is called, however, the Struts Framework will first
perform a validation check. If the validation check passes then
action "LogonSubmit.do" is resolved.
- Look in the struts-config.xml file in the <action-mappings> section.
Notice that the following Java class is called:
com.michaelthomas.mystrutshelloworld.LogonAction.
<action path="/LogonSubmit"
type="com.michaelthomas.mystrutshelloworld.LogonAction"
- Next, we will need to create this file.
- Logon Submit - LogonAction.java
- In Eclipse, Right click on the "WEB-INF/src" source folder and
choose "New", "Class".
Name = LogonAction
- Enter the following code and save:
LogonAction.java (A)
- cut-n-paste (if you type it you will learn more!) the contents of this
file into your file.
- Save the file and Struts will compile it and place the class file in
the directory:
WEB-INF/classes/com/michaelthomas/mystrutshelloworld
- My Comments:
- In the source code notice how the elements from the posted form
is accessed:
String username = (String) PropertyUtils.getSimpleProperty(form,
"username");
- Notice how I created a string value that is passed to the next
action and/or JSP page:
request.setAttribute("fullName", "John Doe");
- Notice how I can communicate back to the web page that posted to
this Action with an error message. The key
"errors.logon.invalid" must exist in the properties file.
errors.add(
ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors.logon.invalid"));
- Notice how I return back to the Struts framework what the next
action is. The struts controller will determine the next
action.
return (mapping.findForward("success"));
return (mapping.findForward("failure"));
- Logon Submit - Test Screen.
- "Reload" the web app via Tomcat Manager.
- Go to the logon page.
- Now enter the following values in "User Name" and "Password".
User Name: test
Password: test (Note: Do not use "password". I want a
validation error created.)
- Click "Submit" and notice the next problem.
(Problem: There is no text that describes the Validation error.)
- My Comments: Our action "LogonAction" (called by the
controller via LogonSubmit.do and passed the logonForm) has done
additional validation (in addition to the DynaValidator) and has
determined that this user is not a valid user. Normally this
validation would be done against a database. In our program, for
quick training purposes, we only have 1 valid user/password. Also the
struts controller (via struts-config.xml) will send a "failure" to
path="/Logon.do". Then the logon.jsp page can display the Validation
errors. The reason why we have no text describing the Validation
error is because the properties message key doesn't exist in the
property file. Next we will correct that.
- Logon Submit - Additional Validation - WEB-INF\src\java\MessageResources.properties
- Make the following changes to the properties file. Add this
entry at the end of the error keys.
# -- validator (Custom) --
errors.logon.invalid=Invalid
password.
Try
username='test'
and
password='password'
- Logon Submit - Test Screen.
- "Reload" the web app via Tomcat Manager.
- Go to the logon page.
- Now enter the following values in "User Name" and "Password".
User Name: test
Password: test (Note: Do not use "password". I want a
validation error created.)
- Click "Submit" and notice the problem is now corrected.
- Logon Submit - Error - mainMenu.jsp is missing.
- Now enter a valid user/password:
User Name: test
Password: password
- Notice the error:
Invalid path was requested
- My Comments: In the struts controller ( struts-config.xml ) a
forward of "success" goes launches "/MainMenu.do". Currently we
don't have an action entry in the struts-config.xml file for this
request therefore we have an invalid path.
- We will correct this in the next steps.
- Logon Submit - WEB-INF\struts-config.xml
- Add the following code to the <action-mappings> section
<!-- Display MainMenu page -->
<action path="/MainMenu"
forward="/pages/mainMenu.jsp"/>
- Logon Submit - mainMenu.jsp
- Now we need to create the JSP page.
- In Eclipse right click on the "pages" directory then choose New,
File.
File name = mainMenu.jsp
Click "Finish"
- Enter the following code and save:
mainMenu.jsp
(A) - cut-n-paste (if you type it you will learn more!) the
contents of this file into your file.
Save the file.
- My Comments: Notice how I access the request object passed
from LogonAction and display the info:
<bean:write name="fullName" /> ( <bean:write name="logonID"
/>
- Logon Submit - mainMenu.jsp - WEB-INF\src\java\MessageResources.properties
- Add the following keys to the properties file.
mainmenu.title=Main
Menu
Screen
mainmenu.heading=Main
Menu
Screen
mainmenu.message=The
main
menu
goes
here.
mainmenu.welcome=Welcome
- When you save the file, Eclipse will copy it to the classes\java
directory.
- Logon Submit - Test Screen.
- "Reload" the web app via Tomcat Manager.
- Go to the logon page.
- Now enter the following values in "User Name" and "Password".
User Name: test
Password: test (Note: Do not use "password". I want a
validation error created.)
- Click "Submit" and notice the problem is now corrected.
Congratulations, You have completed your Struts First Steps
Later possibly add the following:
- Ant build
- Log a message to a log file.
- Java Script Validation
- Logon Submit - logon.jsp - Add JavaScript Validation
- <html:javascript
formName="logonForm"
dynamicJavascript="true"
staticJavascript="false"/>
- onsubmit="return validateLogonForm(this);"
**************************
- Logon Validation - logon.jsp
- Currently there is no form validation so lets add it and fix one of
the "Submit" errors in the JavaScript: "object is not found".
- Note: We are making use of the DynaActionForm classes instead
of creating ActionForm classes.
- Add the following code:
<html:javascript formName="logonForm"
dynamicJavascript="true"
staticJavascript="false"/>