jump to navigation

Difference between Struts 1 & Struts 2 October 30, 2009

Posted by Allu in Struts.
Struts 1 Struts 2
Action classes Struts 1 requires Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces. An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provide a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object.
Threading Model Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized. Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)
Servlet Dependency Struts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked. Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.
Testability A major hurdle to testing Struts 1 Actions is that the execute method exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts 1. Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler.
Harvesting Input Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. SinceĀ  other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. DynaBeans can used as an alternative to creating conventional ActionForm classes, but, here too, developers may be redescribing existing JavaBeans. Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties. The Action properties can be accessed from the web page via the taglibs. Struts 2 also support the ActionForm pattern, as well as POJO form objects and POJO Actions. Rich object types, including business or domain objects, can be used as input/output objects. The ModelDriven feature simplifies taglb references to POJO input objects.
Expression Language Struts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called “Object Graph Notation Language” (OGNL).
Binding values into views Struts 1 uses the standard JSP mechanism for binding objects into the page context for access. Struts 2 uses a “ValueStack” technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows reuse of views across a range of types which may have the same property name but different property types.
Type Conversion Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons-Beanutils for type conversion. Converters are per-class, and not configurable per instance. Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.
Validation Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator. Classes can have different validation contexts for the same class, but cannot chain to validations on sub-objects. Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.
Control Of Action Execution Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle. Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.

Struts FAQs May 25, 2006

Posted by Allu in Struts.
comments closed

java_L.gifWhat is Struts?

Struts is a java framework based on Model 2 architecture of JSP or popularly called Model-View-Controller architecture.It provides a controller for this architecture.

Explain Struts navigation flow?

Struts Navigation flow.

1) A request is made from previously displayed view.
2) The request reaches the ActionServlet which acts as the controller .The ActionServlet Looksup the requested URI in an XML file (Struts-Config.xml) and determines the name of the Action class that has to perform the requested business logic.
3)The Action Class performs its logic on the Model Components associated with the Application.
4) Once The Action has been completed its processing it returns the control to the Action Servlet.As part of its return the Action Class provides a key to determine where the results should be forwarded for presentation.
5)The request is complete when the Action Servlet responds by forwarding the request to the view, and this view represents the result of the action.

What is the difference between Struts 1.0 and Struts 1.1?


The new features added to Struts 1.1 are
1. RequestProcessor class
2. Method perform() replaced by execute() in Struts base Action Class
3. Changes to web.xml and struts-config.xml
4.Declarative exception handling
5.Dynamic ActionForms
7.Multiple Application Modules
8.Nested Tags
9.The Struts Validator
10.Change to the ORO package
11.Change to Commons logging
12.Removal of Admin actions
13. Deprecation of the GenericDataSource.


What is the purpose of tiles-def.xml file, resourcebundle.properties file, validation.xml file?

1. tiles-def.xml
tiles-def.xml is used as a configuration file for an appliction during tiles development
You can define the layout / header / footer / body content for your View.


<definition name="siteLayoutDef" path="/layout/thbiSiteLayout.jsp">
<put name="title" value="Title of the page" />
<put name="header" value="/include/thbiheader.jsp" />
<put name="footer" value="/include/thbifooter.jsp" />
<put name="content" type="string">
Content goes here

<definition name="userlogin" extends="siteLayoutDef">
<put name="content" value="/dir/login.jsp" />

2. validation.xml

The validation.xml file is used to declare sets of validations that should be applied to Form Beans.

Each Form Bean you want to validate has its own definition in this file
Inside that definition, you specify the validations you want to apply to the Form Bean's fields.


<form name="logonForm">
<field property="username"
<arg0 key=" prompt.username"/>
<field property="password"
<arg0 key="prompt.password"/>

3. Resourcebundle.properties

Instead of having hard-coded error messages in the framework, Struts Validator allows you to specify a key to a message in the ApplicationResources.properties (or resourcebundle.properties) file that should be returned if a validation fails.


In ApplicationResources.properties

errors.registrationForm.name={0} Is an invalid name.

In the registrationForm.jsp

<html:messages id="messages" property="name">
<font color="red">
<bean:write name="messages" />

Output(in red color) : abc Is an invalid name


1. Purpose of tiles-def.xml file is used to in the design face of the webpage. For example in the webpage "top or bottom or left is
fixed" center might be dynamically chaged.
It is used for the easy design of the web sites. Reusability

2. resourcebundle.properties file is used for lot of purpose. One of its purpose is internationalization. We can make our page to view on any language. It is independent of it. Just based on the browser setting it selects the language and it displayed as you mentioned in the resourcebundle.properties file.

3. Validation rule.xml is used to put all the validation of the front-end in the validationrule.xml. So it verifies. If the same rule is applied in more than one page. No need to write the code once again in each page. Use validation to chek the errors in forms.


tiles-def.xml – is required if your application incorporates the tiles framework in the "View" part of MVC. Generally we used to have a traditional JSP's (Which contgains HTML & java scriplets) are used in view. But Tiles is an advanced (mode or less ) implementation of frames used in HTML. We used to define the frames in HTML to seperate the header html, footer html, menu or left tree and body.html to reuse the contents. Hence in the same way, Tiles are defined to reuse the jsp's in struts like architectures, and we can define the jsp's which all are to be display at runtime, by providing the jsp names at runtime. To incorporate this we need tile-def.xml and the Class generally which extends RequestProcessor should extend TilesRequestProcessor.

resourcebundle.properties — It is to incorporate i18n (internationalization) in View part of MVC.

validation.xml – This file is responsible for business validations carried at server side before processing the request actually. It reduces the complexity in writing _JavaScript validations, and in this way, we can hide the validations from the user, in View of MVC.



What we will define in Struts-config.xml file. And explain their purpose?


In struts-config.xml we define Date Sources / Form Beans / Global Exceptions / Global Forwards / Action Mappings / Message Resources / Plug-ins

Example :

<!– Date Sources –>
<data-source autoCommit="false" description="First Database Config" driverClass=" org.gjt.mm.mysql.Driver" maxCount="4" minCount="2" password="admin" url="jdbc: mysql://localhost/ARTICLEDB" user="admin">
<!– Form Beans –>
<form-bean name="registrationForm" type="com.aaa.merchant.wsp.ActionForms.RegistrationForm">

<!– Global Exceptions –>
<exception key="some.key" type="java.io.IOException" handler="com.yourcorp.ExceptionHandler"/>


<!– A global-forward is retrieved by the ActionMapping findForward method. When the findForward method can't find a locally defined forward with the specified name, it searches the global-forwards available and return the one it finds.–>
<forward name="logoff" path="/logoff"/>
<forward name="logon" path="/logon.jsp"/>

<!– Actionn Mappings –>
<action path="/validateRegistration" type="com.dd.merchant.wsp.Actions.ValidateRegistration" validate="true" input="" name="registrationForm">
<forward name="success" path="/logon.jsp">

<!– Message Resources –>
<message-resources parameter="wsppaymentsweb.resources.ApplicationResources"/>

<!– Plug-ins –>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>


Struts-Config.xml is one of the most important part of any web application based on Sturts. This file is responsible for instructing the Struts what forms are available, what actions are available, and also allows a number of plug-in models to be added to the base Struts package. It can contain Data Source Configuration,Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions, Message Resources Definitions etc.

The most important are Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions.

The <form-bean/> is configured using only two attributes, name and type and doesn't contain any body. The form-bean tag is used to describe an instance of a particular Form Bean that will be later bound to action.

The attribute name specifies the name of the form bean, which is a unique identifier to this form bean & the attribute type specifies the absolute path of the class file.

<global-forwards/>: It is also configured using only two attributes, name and path and there is also an optional attribute redirect. The <forward/> specifies the mapping of a logical name to a context-relative URI path. In the above sample xml file we can see, one of the <forward/> is specified with the name as failure and its corresponding path as index.jsp. That means whenever the logical name failure is encountered the action will be forwarded to the index.jsp page.

The optional attribute redirect is set to false by default. When it is set to true it causes the ActionServlet to use HttpSevletResponse.sendRedirect() method.

<action-mappings/>: The action mapping mainly defines the mapping between the logical Action name and the physical action class. Now lets have an understanding about its attributes.

· The attribute path must be compulsorily defined and it should start with a '/' character. It specifies the context relative path of the submitted request.

· The type attribute specifies the absolute path of the fully qualified class name of the Action class.

· The attribute name must be the same as that of the form bean name for which you want to associate the action.

· The attribute scope specifies the scope of the particular form bean which is an optional one and its default value is session.

· The next attribute validate is also an optional one which by default is set to true. When set to true, the validate() method in the form bean is called which gets associated with a particular Action.

· The next attribute, input is also optional. Whenever a validation error is encountered then the control returns to the path specified in the input attribute.

<controller/>: The <controller/> can be used to modify the default behaviour of the Struts Controller i.e, we can define a RequestProcessor.

In struts-config.xml, we define all the global-forwards, action mappings, view mappings, form-bean mappings, controller mapping and finally message-resources declaration if any.
Why we need to declare means, the Controller servelet defined in struts internally looks for this xml file for its proceddings. In real scenario, that the controller servlet inplemented internally is nothing but a slave to this struts-config.xml. The information provided in this file is nothing but like the intelligence to the controller servlet to say – what to do in which situation ?
So, Controller servlet, needs this file to proceede/ run the application.

What is DispatchAction?

DispatchAction is specialized child of Struts Action class. It combines or group the methods that can further access the bussiness logic at a single place. The method can be anyone from CRUD [Create,Retrieve,Update or Delete] or it can be security check one like autheniticate user etc.
This class apart from having thread-safe execute method also can have user-defined methods.
In struts-config.xml files following changes are required for Dispatch action to work:

<action path="/login"
type ="com…..LoginAction"
name ="loginForm"
parameter ="task"
scope = "request"
validate = "false"
input = "/index.jsp">
<forward name="success" path="/jsp/common/index.jsp"/>
<forward name="loginagain" path="/index.jsp"/>

If above is your struts-config.xml file structure and LoginAction extends DispatchAction instead of normal Action class. And assuming [keep assuming] your LoginAction class have method named authenticateUser, then in your login.jsp add any hidden parameter called task with value as your method name and on submit of that page following will be the url:


Thus if we try to combine the last part of this puzzle we get the climax at struts-config.xml file's action-mapping tag described above. The parameter property of <action> tag have the task as it's value pointing to task variable in the request having it's value as authenticateUser hence the framework search in the LoginAction a method called authenticateUser through reflection and forwards the execution flow to it. This is all folks, the briallancy of Struts framework. Note DispatchAction class is included in 1.1 version.


How to call ejb from Struts?


We can call EJB from struts by using the service locator design patteren or by Using initial context with create home object and getting return remote referenc object.

What is the difference between ActionErrors and ActionMessages?

There is no differnece between these two classes.All the behavior of ActionErrors was copied into ActionMessages and vice versa. This was done in the attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to the view — where as errors being only one kind of message.

The difference between saveErrors(…) and saveMessages(…) is simply the attribute name under which the ActionMessages object is stored, providing two convenient default locations for storing controller messages for use by the view. If you look more closely at the html:errors and html:messages tags, you can actually use them to get an ActionMessages object from any arbitrary attribute name in any scope.


What are the various Struts tag libraries?

The Struts distribution includes four tag libraries for the JSP framework (in struts-config.xml) :
* Bean tag library [ struts-bean.tld ] : Contains tags for accessing JavaBeans and their properties. Developers can also define new beans and set properties
* HTML tag library [ struts-html.tld ] : Contains tags to output standard HTML, including forms, textfields, checkboxes, radio buttons
* Logic tag library [ struts-logic.tld ] : Contains tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library [ struts-tiles.tld / struts-template.tld ] : For tiles implementation
* Nested tag library [ struts-nested.tld ] : allows the use of nested beans.

The libraries are designed to:

* Facilitate the separation of presentation and business logic.
* Dynamically generate Web pages.
* Implement the flow of control to and from the ActionServlet.

How you will handle errors and exceptions using Struts?

Struts exception handling can be done by two ways:
1. Declarative (using struts features via struts-config.xml)

key ="errors.exception2"

This makes coding in the Action class very simple
Since the execute method declares throws Exception we don't need a try-catch block.
Struts saves the exception using one of its global constants. You may use the field G lobals.EXCEPTION_KEY to retrieve it from the request object.

2. Programmatic (using the usual try-catch exception handling in Action Class)


We can Handle the errors by holding them into ActionError or ActionErrors classes defined by struts Framework. The other way around is by using the methods say saveErrors()….etc defined in Action class and can throw the error messages.


Struts handles errors by providing the ActionErrors class which is
extended from org.apache.struts.action…
To install your customized exception handler, the first step is to
create a class that extends org.apache.struts.action.ExceptionHandler. There are
two methods that you can override, execute() and storeException().
For handling exceptions you have to mention in <global-exceptions> tag
of struts-config.xml which accepts attributes like exception type,key and

How you will save the data across different pages for a particular client request using Struts?

One simple and general way is by using session Object.

In specific, we can pass this by using request Object as well.

Create an appropriate instance of ActionForm that is form bean and store that form bean in session scope. So that it is available to all the pages that for a part of the request.


What is Action Class? What are the methods in Action class?

An Action class is some thing like an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.
The controller (RequestProcessor) will select an appropriate Action for each request, create an instance (if necessary), and call the execute method. Struts Action class is a unit of logic. It is where a call to business function is made. In short the Action class acts like a bridge between client side(user action) and business operation(on server.
Some of the impotant methods of Action class are, execute()
generateToken() resetToken() getServlet()

Explain about token feature in Struts?


Use the Action Token methods to prevent duplicate submits:
There are methods built into the Struts action to generate one-use tokens. A token is placed in the session when a form is populated and also into the HTML form as a hidden property. When the form is returned, the token is validated. If validation fails, then the form has already been submitted, and the user can be apprised.
on the return trip,

What is the difference between ActionForm and DynaActionForm

# The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.

# The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.

# ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.

# ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).

# DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

# Time savings from DynaActionForm is insignificant. It doesn t take long for today s IDEs to generate getters and setters for the ActionForm attributes. (Let us say that you made a silly typo in accessing the DynaActionForm properties in the Action instance. It takes less time to generate the getters and setters in the IDE than fixing your Action code and redeploying your web application)