A Techno Blog, mainly about Java

Struts2 Trainings

One of the struts 2 sample applications is the Mailreader application which has training course via Struts from Square One site .

Building Web Applications
Building Struts 2 Applications [ Welcome] [More …]

Struts 2 components

Action Handler, Result Handler, Custom Tags

Interceptor : bring custom code into call stack

  • Timer Interceptor
  • Prepare (able) – If the Action implements Preparable, calls its prepare method.

value stack : stack of objects that expression language can pull from

  • Action instance pushed onto stack

Jumpstarting JUnit (More …)

Capturing Input(More …)

Validating Input (More …)

Request Lifecycle in Struts 2 applications

  • User Sends request: User sends a request to the server for some resource.
  • FilterDispatcher determines the appropriate action: The FilterDispatcher looks at the request and then determines the appropriate Action.
  • Interceptors are applied: Interceptors configured for applying the common functionalities such as workflow, validation, file upload etc. are automatically applied to the request.
  • Execution of Action: Then the action method is executed to perform the database related operations like storing or retrieving the data from database.
  • Output rendering: Then the Result render the output.
  • Return of Request: Then the request returns through the interceptors in the reverse order. The returning request allows us to perform the clean-up or additional processing.

Display the result to user: Finally the control is returned to the servlet container, which sends the output to the user browser.
Struts 2 Big Picture

The diagram depicts the architecture of Struts 2 Framework. It shows the the initial request goes to the Servlet container, which is then passed through a standard filer chain.

  1. ActionContextCleanUp filter: The ActionContextCleanUp filter is optional. It is useful when integrating other technologies such as SiteMesh Plugin.
  2. FilterDispatcher: the required FilterDispatcher is called, which in turn consults the ActionMapper to determine if the request should invoke an action. If the ActionMapper determines that an Action should be invoked, the FilterDispatcher delegates control to the ActionProxy.
  3. ActionProxy: The ActionProxy consults the Configuration Files manager, which is initialized via the struts.xml file. Then the ActionProxy creates an ActionInvocation, which implements the command pattern. The ActionInvocation process invokes the Interceptors (if configured) and then invokes the action.
  4. Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml. The result is then executed, which often (but not always, as is the case for Action Chaining) involves a template written in JSP or FreeMarker to be rendered. While rendering, the templates can use the Struts Tags provided by the framework. Some of those components will work with the ActionMapper to render proper URLs for additional requests.
  5. Then the Interceptors are executed again in reverse order. Finally the response returns through the filters configured in web.xml file.
  6. If the ActionContextCleanUp filter is configured, the FilterDispatcher does not clean the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present then the FilterDispatcher will cleanup all the ThreadLocals present.


If you install the war on an application server (like tomcat ) you can easily run the sample projtect. Here is the struts 201 slides

Th version I have of the application mentions: “For more about the MailReader, including alternate implementations and a set of formal Use Cases, please visit the Struts University MailReader site” .

The full source code for MailReader is available as svn site, binaries, nightlies

Other Struts2 Trainings include Migrating to Struts2 the and JPA .


December 2, 2007 Posted by | AJAX, Struts | 1 Comment

A Roller 4.o experience

Just last week, I learned about what’s new with Roller in 4.0

Thought it was finally time to try my own installation after being a one time user of this Roller platform on JRoller as user on . I had forgotten my password over on that blog, and it did not seem to be stright forward on how you get your password reset.

Did I mention that Roller is now on Apache at ?

They have their own wiki now at

Anyway, I am using the mysql database (5.0.41 community edition) with roller 4
(apache-roller-src-4.0-rc9) which i placed in Tomcat’s webapps directory naming the folder roller4_0 .

I am using tomcat 5.5 with java5.

Setup: Tomcat’s common/classes folder have placed file

Important: You need to put the mysql driver, and two other jars into Tomcats’s common/lib directory:

  • mysql-connector-java-3.1.13-bin
  • activation (obtained from my java 5 lib folder)
  • mail (obtained from my java 5 lib folder)


AFter starting Tomcat, I go to the main screen via url http://localhost:8080/roller4_0/index.jsp

which says I have a successful connection but have no tables . So I click the button to create the tables.


Then, I get the page to create users and the blog.

References :

November 25, 2007 Posted by | Blogging, Struts, SW Tools | Leave a comment

Roller n Struts2

Just noticed that Dave Johnson has upgraded Roller in version 4.o to use Struts2 and OpenJPA.

After learning about Webwork last year, I played with using Struts2 examples in a 1.4.x environment.

Roller wiki

Install Guide

November 18, 2007 Posted by | Blogging, Hibernate & ORM, Struts | 1 Comment

Struts Next

More info On Struts2


I few months back I experimented with Struts2 and WebWorks

and then some

Here is a wiki entry i created on site.

May 29, 2007 Posted by | Struts | Leave a comment

Struts2 Samples

I downloaded Struts2 (2.0.1) for first time after experimenting with webworks.

My experience at this point with struts2/webworks is limited.

I figured I would start from scratch rather than migrating some old code.

The sample apps they have are

User List

Contents of  struts2-blank-2.0.1 war (folders in bold):

—    ExampleSupport extends com.opensymphony.xwork2.ActionSupport
— HelloWorld extends ExampleSupport
– struts.devMode = true
                                  struts.enable.DynamicMethodInvocation = false

– struts.xml:  <!DOCTYPE struts PUBLIC
                     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
… <include file="example.xml"/>

– example.xml: <!DOCTYPE struts PUBLIC
                     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
<package name="example" namespace="/example" extends="struts-default">

<action name="HelloWorld" class="example.HelloWorld">
                       <action name="Login!*" method="{1}" class="example.Login">
                            <result name="input">/example/Login.jsp</result>
                           <result type="redirect-action">Menu</result>
                      <action name="*" class="example.ExampleSupport">


— commons-collections-3.1

— freemarker-2.3.4

— spring-aop-1.2.8

— spring-context-1.2.8

— spring-web-1.2.8

— struts2-core-2.0.1

— commons-logging-1.0.4

— ognl-2.6.7

— spring-beans-1.2.8

— spring-core-1.2.8

— struts2-api-2.0.1

— xwork-2.0-beta-1

The Struts 2  home page states the Struts 2 requires  Java 5. However, an alternate set of jars for  Java 1.4.x are available.  The challenge here is for people using Java 1.4.X is that the sample apps  come with the Java 5 jars.The java 4 jars can be found here.  I extracted them to here:


But, the only file I needed from here was struts2-extras-j4-2.0.0.jar .

copy C:\java\struts2\struts-2.0.1\j4\struts2-extras-j4-2.0.0.jar

as I got the backport files from the nightlies:

which i copied to


Then i modified the translate.bat as follows:

java -jar retrotranslator-transformer-1.0.8.jar -srcjar struts2-core-2.0.1.jar -destjar struts2-core-j4-2.0.1.jar
java -jar retrotranslator-transformer-1.0.8.jar -srcjar struts2-api-2.0.1.jar -destjar struts2-api-j4-2.0.1.jar 
java -jar retrotranslator-transformer-1.0.8.jar -srcjar xwork-2.0-beta-1 -destjar xwork-2.0-j4.jar

The key thing is after the translate takes place to remove the following files:

  • struts2-core-2.0.1.jar
  • struts2-api-2.0.1.jar
  • xwork-2.0-beta-1

Again, a Java 5 version of struts2-extras-j4-2.0.0.jar was not in the struts2-blank-2.0.1 war.
In Summary, my lib folder contains the following jars for 1.4.x:

— commons-collections-3.1
— commons-digester-1.6
— commons-logging-1.0.4

— freemarker-2.3.4

— spring-aop-1.2.8

— spring-context-1.2.8

— spring-web-1.2.8

— retrotranslator-runtime-1.0.8
— retrotranslator-transformer-1.0.8

— ognl-2.6.7

— spring-beans-1.2.8

— spring-core-1.2.8

— struts2-core-j4-2.0.1

— struts2-api-j4-2.0.1

— xwork-2.0-j4
— backport-util-concurrent
— translate.bat

Refer to this issue here

November 24, 2006 Posted by | Struts | Leave a comment

Trying out Webworks

I have been reading up about Struts 2.

I figured checking out the webworks framework first might be a good idea.


Config Files –

C:\java\webworks\webwork-2.2.2\webapps>ant build -Dwebapp=shopping-cart
Buildfile: build.xml

   [delete] Deleting directory C:\java\webworks\webwork-2.2.2\webapps\tmp
    [mkdir] Created dir: C:\java\webworks\webwork-2.2.2\webapps\tmp
     [copy] Copying 58 files to C:\java\webworks\webwork-2.2.2\webapps\tmp
    [javac] Compiling 13 source files to C:\java\webworks\webwork-2.2.2\webapps\
     [copy] Copying 1 file to C:\java\webworks\webwork-2.2.2\webapps\tmp\WEB-INF
      [war] Building war: C:\java\webworks\webwork-2.2.2\webapps\dist\shopping-c
      [war] Warning: selected war files include a WEB-INF/web.xml which will be
ignored (please use webxml attribute to war task)


copy C:\java\webworks\webwork-2.2.2\webapps\dis
t\shopping-cart.war c:\java\apache-tomcat-5.5.17\webapps\

http://localhost:8080/shopping-cart/ has a basic Webworks example (WAR).

Snippet from xworks.xml:

<default-interceptor-ref name="paramsPrepareParamsStack"/>
        <action name="index" class="net.vaultnet.learn.action.EmployeeAction" method="list">
            <result name="success">/jsp/employees.jsp</result>
            <!– we don’t need the full stack here –>
            <interceptor-ref name="basicStack"/>
        <action name="crud" class="net.vaultnet.learn.action.EmployeeAction" method="input">
            <result name="success" type="redirect-action">index</result>
            <result name="input">/jsp/employeeForm.jsp</result>
            <result name="error">/jsp/error.jsp</result>

  1. ActionMapper – mapping between HTTP requests and action invocation requests and
    vice-versa; may return null if no action invocation request maps,
    or it may return an ActionMapping.
  2. Filter Dispatcher (com.opensymphony.webwork.dispatcher.FilterDispatcher) – filter and its mapping are located in web.xml and defines what requests will be intercepted. Before executing an Action, it loooks through stack of interceptors.

    Webworks Interceptors (defined in webwork-default.xml)can be invoked before and after your action is executed. paramsPrepareParamsStack- This is useful for when you wish to apply parameters directly to an object that you wish to load externally.

  3. <%@ taglib prefix="ww" uri="/webwork" %> : access to the tag library

November 18, 2006 Posted by | Struts | Leave a comment

Struts 2

After the release of WebWork 2.2.2, the WebWork and Struts communities began a merge that will eventually produce Struts 2. This merger combines these two "action based" frameworks  as it is told .

Compared to SpringMVC,
you sacrifice some cleanliness but there is a lot more work done in
certain areas, for example client-side validation, a strong Interceptor
framework and a nice graphical flow
designer – this latter is also a strong area, with WebWork being one of
the pioneer adopters of the freshly unbundled RIFE Continuations package.

Continue reading

November 2, 2006 Posted by | Struts | Leave a comment


Just noticed this weblog yesterday on the TarHeels .  They are calling themseleves THT, but I tend to prefer this THT – The Hardball Times

article on Spring with Struts

December 1, 2005 Posted by | Sports, Spring, Struts | Leave a comment

Struts (singleton)and the merger

Struts and WebWorks Frameworks are merging. The Struts message board details this.

Could it be that these are some reasons for merger?

Now , back from the commercial break.

The Action classes are singleton classes that are instantiated once per class type per JVM, and all requests for a specific action are routed through  the same Action class instance. This IBM article states this well:

"Struts will create a single instance of the Action and allow multiple threads to invoke execute(). This allows for faster request processing, as the framework is not continually creating new Action instances to handle each request. But because a single object is shared between multiple threads, you must observe proper threading considerations, as other threads are likely to pummel instance variables that hold state in the action. "

The thread safety thing always seems to comes into play. Now to the Struts Action Class Guidelines:

" Write code for a multi-threaded environment – Our controller servlet creates only one instance of your Action class, and uses this one instance to service all requests. Thus, you need to write thread-safe Action classes. Follow the same guidelines you would use to write thread-safe Servlets. Here are two general guidelines that will help you write scalable, thread-safe Action classes:

Only Use Local Variables – The most important principle that aids in thread-safe coding is to use only local variables, not instance variables, in your Action class. Local variables are created on a stack that is assigned (by your JVM) to each request thread, so there is no need to worry about sharing them. An Action can be factored into several local methods, so long as all variables needed are passed as method parameters. This assures thread safety, as the JVM handles such variables internally using the call stack which is associated with a single Thread.

Conserve Resources – As a general rule, allocating scarce resources and keeping them across requests from the same user (in the user’s session) can cause scalability problems. For example, if your application uses JDBC and you allocate a separate JDBC connection for every user, you are probably going to run in some scalability issues when your site suddenly shows up on Slashdot. You should strive to use pools and release resources (such as database connections) prior to forwarding control to the appropriate View component — even if a bean method you have called throws an exception.

Don’t throw it, catch it! – Ever used a commercial website only to have a stack trace or exception thrown in your face after you’ve already typed in your credit card number and clicked the purchase button? Let’s just say it doesn’t inspire confidence. Now is your chance to deal with these application errors – in the Action class. If your application specific code throws expections you should catch these exceptions in your Action class, log them in your application’s log (servlet.log("Error message", exception)) and return the appropriate ActionForward.

It is wise to avoid creating lengthy and complex Action classes. If you start to embed too much logic in the Action class itself, you will begin to find the Action class hard to understand, maintain, and impossible to reuse. Rather than creating overly complex Action classes, it is generally a good practice to move most of the persistence, and "business logic" to a separate application layer. When an Action class becomes lengthy and procedural, it may be a good time to refactor your application architecture and move some of this logic to another conceptual layer; otherwise, you may be left with an inflexible application which can only be accessed in a web-application environment. The framework should be viewed as simply the foundation for implementing MVC in your applications. Struts Action Framework provides a useful control layer, but it is not a fully featured platform for building MVC applications, soup to nuts. "

Lastly, note that :

"actions are cached, they must be thread-safe. That does’t mean that you can’t use instance variables. If those instance variables are thread safe, and the objects they reference are thread-safe, then everything is good. Servlets suffer the same problem because Servlets are pooled by the container. By default Spring delivers singletons. As long as the services are thread-safe (as all singletons should be), there is no danger."

November 29, 2005 Posted by | Struts | 3 Comments

The Application scope

getting an object that was placed in application scope (done in Struts Action):

In your Struts Action Class (inherits from org.apache.struts.action.Action) , like was done here just create the following method:

       protected Object getApplicationObject(String attrName) {
         return servlet.getServletContext().getAttribute(attrName);

setting an object into application scope can be done by implementing a struts plugin.

Create a class that extend org.apache.struts.action.PlugIn:

public class myPlugin implements org.apache.struts.action.PlugIn {

  public void init(org.apache.struts.action.ActionServlet servlet,
   ModuleConfig applicationConfig) throws ServletException {
     setApplicationObject(servlet, "object1", "YES");

protected void setApplicationObject(
   org.apache.struts.action.ActionServlet servlet, String attrName,
   Object obj) {
      ServletContext context = servlet.getServletContext();
      context.setAttribute(attrName, obj);

Don’t forget to define your plugin in struts config file:


plug-in className="myPath.myPlugin"/>

Lastly, remember the application scope is multithreaded

October 27, 2005 Posted by | Struts | 3 Comments

Dyna Forms

Denver Java Users Group has a talk on Dynamic Struts Forms.

I noticed they have a nice ppt presentation on Spring/Hibernate.

August 8, 2005 Posted by | Hibernate & ORM, IoC, Struts | Leave a comment

Business Methods

The web application I am working on has its execute method which go to the back end to perform a business object method if the action determines it is required.

However, prior going to the back end it will translate the form beans to a business bean.

Thus, after this is done, the container will set the applicable business method and begin the process of invoking it. 

Just to be clear, the high level flow starts by invoking the business process method specified by  the process. After it completes, it will check for various errors. If we get an excpetion back saying it failed some business process validation, we find out if we got warnings or errors which are then captured in the request. On a error an excption, we will throw the exception.

It is important to note that we can return without any business validation errors, but we can still get a warning back.

June 15, 2005 Posted by | Struts | Leave a comment


View – renders the content of the model – access data from model and decide how to present it – forward user input to controller.

Tiles provides a framework for defining and dynamically populating page layouts.

The JSP file will define a template with placeholders where the content should go.

When the JSP file is invoked, it replaces the place holders with content creating a page
which is an instance of the layout.

Enabling the Tiles plugin:
<plug-in className="org.apache.struts.tiles.TilesPlugin">
<set-property value="/WEB-INF/tiles-defs.xml" property="definitions-config" />
     <set-property value="0" property="definitions-debug" />
     <set-property value="0" property="definitions-parser-details" />
     <set-property value="false" property="definitions-parser-validate" />


A Tiles definition specifies the layout for a piece of content.

Tiles can insert into a JSP using the definition name which consists of:

  • name or identifier
  • set of attributes associated with the definition
  • a layout JSP name (instance file name of the given definition and attributes)

Using the Tiles Tag libray in JSP file:

<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

<tiles:insert> –  Inserts a tiles definition or attribute into a JSP page.
   Note: the attribute ‘template’ is deprecated (1.2)
         It is replaced by the attribute ‘page’ .
                 <tiles:insert template="/templates/Header.jsp" >

<tiles:put>    –  Defines an attribute (or parameter) for a definition.
   Note: the attribute ‘name’ specifies the name of the attribute
          <tiles:put name="page_title" direct="true">
          <bean:message key="head.title.prefix"/>
          <bean:message key="title.profile.create1"/>

Using the Bean Tag libray in JSP file:

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

<bean:define>    –  Defines a variable to be associated with a bean property
          <bean:define  id="codeText" name="securityListForm"
                              type="java.lang.String" property="code"
<bean:message>    –  Display a text replacement string associated with an identifier (prop file)
          <bean:message key="head.title.prefix"/>
<bean:write>    –  Display a bean properties value (name can be bean name or bean variable defined for jsp)

           <bean:write name="CodeListForm" property="code" />

Using the logic Tag libray in JSP file:

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

<logic:iterate>    –  Iterate over a list

<logic:iterate id="codes"              indexId="index"
                  name="securityListForm" property="list"



<logic:greaterThan>    –  execute logic if condition met

                 <bean:size id="listSize" name="listForm" property="list"/>
                 <logic:greaterThan name="listSize" value="0">


<logic:equal>    –  execute logic if condition met

              <logic:equal name="securityListForm" property="tabNumber" value="20">

Using the HTML Tag libray in JSP file:

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html:form>    –  form definition

<html:text >







Not Empty Tag

May 18, 2005 Posted by | Struts | Leave a comment

Online: 27 January 2005 – New Struts subproject: Shale

Link: Apache News Blog– Struts Classic and and (now) Struts Shale.

January 28, 2005 Posted by | Struts | Leave a comment

struts articles

JAX magazine : struts best practices
TSS: struts action mapping

December 22, 2004 Posted by | Struts | Leave a comment

Extending Struts

Link: Extending Struts.

December 8, 2004 Posted by | Struts | Leave a comment

Struts Recipes In Action

From Manning comes a couple of  sample chapters from the new Struts book.

December 6, 2004 Posted by | Struts | Leave a comment

Struts wiki articles

Wiki on struts

November 10, 2004 Posted by | Struts | Leave a comment

Request object in Struts when validation fails

I ran into a problem within struts where my validation fails on the form data that is submitted
from my jsp, and when control is returned back to the jsp as specified in the struts config file,
i lose my request data. In my case it was a string value that is populated in a
servlet using the request object prior to forwarding to the jsp the first time.  Seems this is a common
thing with struts as the issue is also described here

The way i got around it was to set the string value in a session object prior to submitting the data. Then, if the jsp form validation fails, and
the jsp is reinvoked where the request object is null, I can get the string value from the session object.

November 10, 2004 Posted by | Struts | Leave a comment

Tags for html



October 27, 2004 Posted by | Struts | 1 Comment

Struts De-Mystified series





October 17, 2004 Posted by | Struts | Leave a comment

Struts and JSF

Struts and JSF: The rationale between the two application from Craig.

October 13, 2004 Posted by | Struts | Leave a comment

Struts in action forum

Click here to enter the forum

October 11, 2004 Posted by | Struts | Leave a comment

First Time Strutter

Just a link to a nice source of information. This one happens to be on Struts. But there seems to be quite an array of good information [link].

Then there is this Struts with WSAD example.

October 11, 2004 Posted by | Struts | Leave a comment

Core Struts

Demystifying Apache Struts: A Quick Start Tutorial for Jakarta Struts

October 7, 2004 Posted by | Struts | Leave a comment


The page I am working on uses struts which means a validate method as well. So, I thought I should get a better understand the ActionError and ActionErrors classes. Note that these two classes are in the org.apache.struts.action package. I found this article.

The ActionError contains two pieces of information. A key and a value. The key is a string , and the value is an array of replacement values (i.e. error messages).

The ActionErrors stores a collection of ActionError objects. You add objects using its add method which stores the object in an internal hashmap. You pass in a property name and the ActionError object. The property name is just a property name or ActionErrors.GLOBAL_ERROR

The article is old, so I did run into some deprecations.

Here is a jsp snippet:

ActionErrors e = (ActionErrors) request.getAttribute(org.apache.struts.Globals.ERROR_KEY);
if ( e!=null && !e.isEmpty()){
out.println(e.size() + “errors(s) found”);
Iterator detail = e.get();
while (detail.hasNext()){
org.apache.struts.action.ActionError ae = (org.apache.struts.action.ActionError);
String s = ae.getKey();
String x = (String) (ae.getValues()) [0];
out.println(“-” + x + “br”);

October 7, 2004 Posted by | Struts | Leave a comment

Struts n JSF stuff

JSF vs Struts info

Faces info by James Holmes

September 22, 2004 Posted by | Struts | Leave a comment

Tiles Page for Struts

A link to Cedric’s (From Struts in Action) Tiles page.

Speaking of Struts in Action, I noticed there is another Struts book from Manning coming out titled Struts Recipes.

September 19, 2004 Posted by | Struts | Leave a comment

What is DynaActionForm?

“Suppose we have lots of JSP pages with forms that we want to validate. We could write an ActionForm with getter/setter pairs for each of the JSP pages, but, if we had 20 pages, we would have to write an ActionForm for each one. This is inconvenient. Instead, we can create a single DynaActionForm. A DynaActionForm can be reused in any number of Actions. A DynaActionForm will list all possible properties with their types that can appear on a Jsp page. “

September 19, 2004 Posted by | Struts | Leave a comment

Strut lessons

Struttin it [lessons and articles]

Speaking of Struts, their was a java world article on Struts best practices that was discussed at the server side.

Stuts is a competing technology with JSF, but Dion says Death of/Long live Struts

Nice tutorial on dynamic forms.

September 15, 2004 Posted by | Struts | Leave a comment

Struts multi select

After reading up on struts including reading parts of the Struts in Action book, I was looking for an example which had all types of inputs for a typical form (radio, select, multiselect, etc). Most examples with Struts show the typical user name and password logon example.

Best I found is here. However, it does not cover multiselect.

In the Sandbox struts forum, there was this.
Then there was Advanced Forms Handling in Struts 1.1.

In the end, I was looking for the type for storing my multiselect input:

Here is how I did it:
import org.apache.struts.action.*;
public class aForm extends ActionForm {
protected String [] username;
public String [] getUsername () {return this.username;};
public void setUsername (String [] username) {this.username = username;};

September 13, 2004 Posted by | Struts | 5 Comments

Java Tutorials


Exadel Java Topics

JDO, Struts, Java 1.5 etc.

September 1, 2004 Posted by | Hibernate & ORM, J2EE, JDO, Struts | Leave a comment


I am learning struts now. Reading the book Struts in action by Ted Husted. [ppt]

I am a little late to the Struts party, but it is a MVC like architecture.

Here is a nice overview on it.

Example workflow

Here is a tutorial by IBM

With WSAD 5

Struts install

JUG presentation
example with hibernate

J2ee masslight
J2ee masslight Forms Processing

java pro

Struts Howto with Tomcat
Best Practices

September 1, 2004 Posted by | Struts | Leave a comment

Second Struts Example

LogonForm (which extends ActionForm):
– getters/setters methods
– validate ((ActionMapping mapping,HttpServletRequest request) method
– reset(ActionMapping mapping,HttpServletRequest request) method

August 30, 2004 Posted by | Struts | 1 Comment

First Struts Example

Using WSAD 5.1.1 for the Struts register example.
Note that I had to apply this fix to WSAD due to an error I was having with the EAR files.
In WASD I create a blank struts web project (with struts 1.0.2) and imported the WAR example file.
Some of the files in the WEB-INF to know about:


Lets start out with the register.jsp file:

<%@ taglib uri=”/WEB-INF/struts-form.tld” prefix=”form” %>
<form:form action=””>

enter password:<form:password property=”password1″/>
re-enter password:

<form:submit value=”Register”/>

The key thing here is that the jsp makes use of the struts form tag library, and submits the data to

Now lets take a look first at the web.xml and then the struts-config.xml file:

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<!DOCTYPE web-app
PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN””&gt;

The key thing to note here is its using the web-app_2_2.dtd. Now on to the struts config file:

<?xml version=”1.0″ encoding=”ISO-8859-1″ ? >

<!DOCTYPE struts-config PUBLIC
“-//Apache Software Foundation//DTD Struts Configuration 1.0//EN””&gt;
<form-bean name=”registerForm” type=”app.RegisterForm”/>
<action path=”/register”
<forward name=”success” path=”/success.html”/>
<forward name=”failure” path=”/failure.html”/>

So, from the config xml file, its using the struts-config_1_0.dtd, specifies a form bean of
app.RegisterForm, specifies an action of app.RegisterAction, and contains two forwards of
success and failure.

So, in the java resources side of the project, we have a resources folder and a package called
app. One class in the app folder is the RegisterAction mentioned above, lets take a look:

package app;
import org.apache.struts.action.*;
import javax.servlet.http.*;
public class RegisterAction extends Action {
public ActionForward perform (ActionMapping mapping,
ActionForm form,
HttpServletRequest req,
HttpServletResponse res) {
// (1) Cast the form to the RegisterForm
RegisterForm rf = (RegisterForm) form;
String username = rf.getUsername();
String password1 = rf.getPassword1();

String password2 = rf.getPassword2();

// (2) Apply business logic
if (password1.equals(password2)) {

try {
// (3) Return ActionForward for success
return mapping.findForward(“success”);
} catch (UserDirectoryException e) {
return mapping.findForward(“failure”);
// (4) Return ActionForward for failure
return mapping.findForward(“failure”);

So in this RegisterAction class (which inherits from the Action class),
we have method perform. On of the parms to the method is the ActionForm
which I’ll show you in just a sec. We cast the ActionForm parm as RegisterForm which
was specified in the struts config file. Lets go to that RegisteForm class now.

package app;
import org.apache.struts.action.*;
public class RegisterForm extends ActionForm {
protected String username;
protected String password1;
protected String password2;
public String getUsername () {return this.username;};
public String getPassword1() {return this.password1;};
public String getPassword2() {return this.password2;};
public void setUsername (String username) {this.username = username;};
public void setPassword1(String password) {this.password1 = password;};
public void setPassword2(String password) {this.password2 = password;};


package app;
import java.util.Enumeration;
import java.util.Properties;
public class UserDirectory {
private static final String UserDirectoryFile = “resources/”;
private static final String UserDirectoryHeader = “${user}=${password}”;
private static UserDirectory userDirectory = null;
private static Properties p;
private UserDirectory() throws UserDirectoryException { i = null;
p = null;
i = this.getClass().getClassLoader().
if (null==i) {
throw new UserDirectoryException();
else {
try {
p = new Properties();
catch ( e) {
p = null;
throw new UserDirectoryException();
finally {
i = null;
} // end else
} // end UserDirectory
public static UserDirectory getInstance() throws
UserDirectoryException {
if (null==userDirectory) {
userDirectory = new UserDirectory();
return userDirectory;
public String fixId(String userId) {
return userId.toUpperCase();
public boolean isValidPassword(String userId, String password) {
// no null passwords
if (null==password) return false;
// conform userId to uppercase
String _userId = fixId(userId);
// no passwords for non-users
if (!isUserExist(_userId)) return false;
// does password match user’s password
return (password.equals(getPassword(_userId)));
public boolean isUserExist(String userId) {
// no null users
if (null==userId) return false;
// if not null, it’s a user
return !(null==p.getProperty(userId));
public String getPassword(String userId) {
return p.getProperty(userId);
public Enumeration getUserIds() {
return p.propertyNames();
public void setUser(String userId, String password) throws
UserDirectoryException {
// no nulls
if ((null==userId) || (null==password)) {
throw new UserDirectoryException();
try {
// conform userId to uppercase when stored
p.put(fixId(userId), password);
String o = this.getClass().getClassLoader().getResource(UserDirectoryFile).getFile(); FileOutputStream(o), UserDirectoryHeader);
catch (IOException e) {
throw new UserDirectoryException();

August 16, 2004 Posted by | Struts | 2 Comments

Using Struts

I started looking at struts recently.
I started off by downlaoding jdk1.4 and tomcat.
Make sure for some reason that your classpath has not only the location of the jdk bins, but also the tools jar file:
After extracting the tomcat zip file, I went to the the bin folder withinn the tomcat directory (c:/apache/jakarta-tomcat-5.0.27), clicked the startup bat file, and then in my web browser invoked the default url: http://localhost:8080/ and the tomcat home page is presented.
Next, it is on to the Apache Struts page. I went to the same apache downloads page and got the Struts 1.1 zip file.
The Struts zip file was extracted to c:/apache/jakarta-struts-1.1. In that folder there is a webapps folder with several war files. I will place the war files in the webapps folder in the tomcat folder. After placing the war files in the tomcat webapps folder, i noticed that new folders corresponding to the war files are created in the webapps folder. Also, you can grab the (war files) examples from Struts in action.

August 8, 2004 Posted by | Struts | 1 Comment