You are on page 1of 39

An Introduction to Struts 1.

3 Frameworks
Introduction:
Apache Struts 1.3 is the most famous, classic and Model-View-Controller (MVC) web
application framework. As we said earlier, Struts 2 is nt just a new release of the older
Struts 1 framework. A web application can interact with different databases and business
logic.
There are hundreds of thousand companies are implemented and used Struts 1.3 and never
consider upgrade.
In this tutorial you will learn about struts1.3 from starting to end. This tutorials covers all
struts1.3 stubs from beginning to end .We proceed step by step so that you can take more
advantage.
We explain here

How to create struts 1.3 web application ?

How you can add web application and struts1.3 application?

We cover all topics with appropriate examples in struts1.3 .

We cover here up to tiles implementation in struts 1.3.

We cover here how to make test case in struts 1.3?

How you can use ant with struts1.3 ?

We also cover history of struts1.3.

Advantage of struts 1.3.

Limitations of struts 1.3.

Disadvantage of struts 1.3etc.

Descriptions:

Struts 1.3 framework provide the facility to developed web application in


Java platformed. Through this framework we are create dynamic web application.
This dynamic web application provide user to simple way to access the web page.

History of Struts Frameworks

Introduction:

Struts was created by "Craig McClanahan" than it was donated to the Apache Software
Foundation in May, 2000. Now struts is an open source code sponsored by Apache Software
Foundation in 2005. This open-source web application framework provide the facility to
developed dynamic web application in java enterprise edition. This web application
framework extends the Java Servlet API which are using the concept of MVC(Model View
Controller) pattern.

Descriptions:
In July 2001, version 1.0 was released very first. After that Apache Foundation released
more versions .Which are:
Struts Scripting-1.0.1
Struts-1.0.2
Struts-1.1
Struts-1.2.4
Struts-1.2.7
Struts-1.2.8
Struts-1.2.9
Struts-1.3.5
Struts-1.3.8
Struts-1.3.10
Struts-2.0.6
Struts-2.0.8
Struts-2.0.9
Struts-2.0.11
Struts-2.0.11.1
Struts-2.0.11.2
Struts-2.0.12
*Struts-2.0.14
Struts-2.1.6
Struts-2.1.8
*Struts-2.1.8.1
**Struts-2.2.11
*best available **latest version of struts

Different views on Struts Frameworks

Introduction:
There are different views by developers for Struts1.3 Frameworks.Struts 1.3 is one of the
most used frameworks in Java/J2EE web based enterprise applications. Struts 1.3 is the
most famous, classic framework.

Descriptions:

As struts1.3 provides a centralized controllers and Struts1.3 follows MVC-2 Design Pattern.
So Struts1.3 is good option for web based applications.It has clear separation for model
view and controller.The view developer have only focus on GUI ,The controller developer
have focus on controller and networks securities and model developer have focus on writing
business logic, so it is cost effective .The maintaining cost of struts1.3 application is less in
term of money and as well as time.It also provide Struts1.3 tag libraries .Using these tag
libraries a developer can make a jsp page easily. But as Struts1.3 takes more attention and
need time to be expertise .

Advantages of Struts Frameworks

Introduction:
Struts1.3 is a Frameworks which is an implementation of MVC-2 at server side. Struts1.3
have many advantages over the standard servlet and JSP API alone.

Descriptions:

Advantages Of Struts1.3
Struts1.3 have following advantages are:
1.Centralized:- Struts1.3 provides centralized controller and centralized xml file to
configure all actions, plug-in ,form bean etc. and also provides XML or properties file in
which we can write valuable information rather than hard-code into our java code file.
Struts2 also provides centralized controller .A network security developer have to focus only
security and traffics so it is easy to handle it as in Struts1.3 there is only one serevlet
controller.
2.Maintaining and development:- As in struts1.3, There is clear separation of model,
view and controllers so its maintaining cost is low and at development time GUI .Developer
have focus only GUI ,business logic developer have focus on writing business logics and
controller developer have focus on only networks securities ,traffics etc.Our developer can
work on different mode, views and controllers .So it will take less time. We can assign
different task on the behalf of the skill set so development cost can be optimized.There is
clear separations between presentation and transaction layers so its allow us change the
look and feel of applications without recompiles models.As MVC lets us allow multiple types
of views all can use same server-side code. Struts used MVC-2.
3.ActionForm Beans:- When we are using JSP to send form data we have use
property="*" with jsp:setProperty .This will automatically populate data a JavaBean
component based on incoming request parameters. Unfortunately there is no any standard
API throught wich we can do this into serevlets. Apache Struts extends this capability to

Java code and adds in several useful utilities, all of which serve to greatly simplify the
processing of request parameters.
4.Struts-Tags Library:- Apache Struts provides a set of Bean tags (bean:write, in
particular) that let us easily output the properties of JavaBeans components.Apache Struts
provides a set of HTML Tags to create HTML forms that are associated with JavaBeans
components. This bean/form association serves two useful purposes: It lets you get initial
form-field values from Java objects.It lets you redisplay forms with some or all previously
entered values intact.
5.Form Field Validation:- Apache Struts provides validate frameworks to validate data like
formats, minimum length, maximum lengths. Also maintains the previous stats of from
data.This validation can be performed on the server (in Java), or both on the server and on
the client (in JavaScript).
6. Fast Deployment :- In struts 1.3,development time can be significantly reduced.
7.Advantage Utilities :-Struts1.3 provides lots of utilities derived from Apache commons
to make our life easier like ready made Form Beans for request parameters,Validation
controls and Custom tags

Disadvantages of Struts Frameworks

Introduction:
Struts1.3 have several advantages but also have some disadvantages.Struts is not easy to
learn .struts1.3 is complex framework and it is used for large project only.so Struts2 have
many disadvantages.

Descriptions:
Disadvantage of Struts1.3 are:
1.Need more Learning:- Struts1.3 is not for small project .As Struts1.3 need more
learning any developer can not work on struts2 directly. Before work on struts1.3
developers must have knowledge of Core Java, JSP, Servlets, HTML, Custom JSP Tags, Tags
library and also Struts2 need more clear knowledge of Struts1.3 frameworks also like is
follow, working of different Action classes ,way of configuring XML file and plug-in etc .That
mean any developer must need expertise before work on Struts2 application .but This is not
an issue with experienced developers.
2. Not More Documentation:- As Compare Servelet, JSP struts1.3 have no more online
free help materials. Only Apache has provided some help which is not sufficient and has
note covers sufficient examples. So developer needs more works on study.
3. Less Transparent In a Struts applications:- In Struts1.3 there is a so many things
are going on behind the scenes than with normal Java-based Web applications.

As a result, Struts1.3 applications are: not easy to understand and not easy to benchmark
and optimize.
4.Disadvantage Imposing :- You want to use Struts then you will have to just follow the
rules set by this framework.
5.Disadvantage Performance :-This frameworks bigger call stacks due to various
function calls which results in lesser performance.

Why we need Struts Frameworks

Introduction:
As we have JSP and Servlet then what is need of Struts1.3? Struts1.3 have many more
benefits rather than it is server side MVC-2 implementation .So that today struts is used into
web based enterprise applications. Today Struts1.3 is used with Spring and Hibernate to
make our web based application secure and faster. Today Struts1.3 used in project for
telecom, e-Learning and banking/finance domain etc.

Descriptions:

Struts1.3 framework is more efficient than other framework like Spring web MVC,JavaServer
Faces and Hibernate etc.

Struts1.3 As a developer point of view:- As a developer point of view a developer


must have focus on there core skill area. Like a GUI developer wants to work on GUI
as their skill set.But a business logic developer never wants to write code for GUI
he/she wants code for business logics. Similarly a security and traffic control
programmer want to focus on controller.As Struts1.3 is serer-side implementations of
MVC-2 .So it offers clear separations between model, view and controller.

Due to clear layer of MVC model,struts1.3 reduced of developers time and costs.

Struts1.3 as a maintains point of view Maintains in easy and have less cost in case of
struts.

The Struts1.3 is not only thread-safe but thread-dependent (instantiates each Action
once and allows other requests to be threaded through the original object).

The Struts1.3 tag libraries provide general-purpose functionality.

ActionForm beans minimize subclass code and shorten subclass hierarchies.

The Struts1.3 is neutral model and easier integrated with other framework like
Struts1.3 with Hibernate, Struts1.3 with Spring web MCV, and Struts2 with JSF.

The Struts1.3 are lightweight and its components are reusable by the application.

Where we use Struts Frameworks

Introduction:
Jakarta Struts is incredibly useful in helping you to create excellent Web applications
because Struts uses a specific paradigm, or design pattern, to structure any application and
the design pattern is called Model-View-Controller (MVC). So, struts framework is widely
used and widely adapted.

Descriptions:

Struts 1.3 framework has widely adapted so used in most of projects like:

Telecom domain applications.

Finance/banking domain applications.

e Learning and e Shopping applications.

Defiance application.

Web based enterprise applications.

We can also use Struts where we need to implements a centralized controller and
application has MVC design pattern. We can use Struts where we need becaues

High Reliability.

Easier Maintainability.

High Reuse and adaptability.

Very Low Development Cost.

Rapid Development.

The Model-View-Controller (MVC) Design Pattern

Introduction:
Struts1.3 framework implementation of Model-View-Controller (MVC) design patterns in JSP
web applications, which offers many benefits to the web application developer. The MVC
Model 2 paradigm applied to web applications lets you separate Presentation logic (for
example, HTML and Custom Tag libraries) from Workflow control logic (Filter Dispatcher)
and model logic( Action Class).

Descriptions:

Brief description of

Model-View-Controller (MVC):-

The Model portion of an MVC-based system typically comprises JavaBean classes that
define the internal state of the system; they also specify the actions that can be
taken to change that state.Data Access from any data source database, flat file, web
service, Entity Bean, LDAP server etc.

The View manages the display to the end user and portion of a Struts-based
application is generally constructed using JSP technology. JSP pages can contain
static HTML and Custom Tag library.Which are handle by Result component of
Struts1.3 framework.

The view have following tasks :1. Show hypertext, images, forms to the user
2.Retrieve processed data from the model and display to the user along with
hypertext, images.
3.Client side validations
4.Server side validations

Controller is the layer between View and Model.The Controller portion of the
application is focused on receiving requests from the client (typically a user running a

web browser), deciding what business logic function is to be performed, and then
delegating responsibility for producing the next phase of the user interface to an
appropriate View component.Which is handle by FilterDispatcher component of the
struts1.3 framework.
The controller have following tasks :1.When a View sends the request, the Controller finds appropriate Model component and
forwards the request to this component.
2.Receives the response from the model and routes the data to appropriate View
component.

Types Model-View-Controller ('MVC') Design Pattern

Introduction:
MVC play biggest role in struts1.3 framework because MVC separates design concerns (data
persistence and behavior, presentation, and control), centralizing control, decreasing code
duplication, and making the application more easily modifiable.

Descriptions:

There are two types of MVC design pattern

MVC-1 Design Pattern:- MVC -1 have more than one controllers .Each request may
have own controller in case of MVC-1.We can create controller using JSP or Servlet.

MVC-2 Design Pattern:- MVC-2 has only one controller .The servelet is used to
create controller for MVC-2.All request must be handled by single controller and only
this controller can decide the response GUI on the basis of model calculation and
manipulations.

Struts and Model-View-Controller (MVC) Design Pattern

Introduction:
Struts1.3 Frameworks is used to build Java-based Web applications. Struts solved many
problems associated with developing high-performance, business-oriented Web applications
that was in Servlets and Java Server Pages (JSP) by using the Model-View-Controller -2
(MVC-2) design patterns

Descriptions:
Struts ActionServlet class:-The Struts Framework gives developers to make an
application that has flexibility to use any approach or technology for building the Model layer
code like Object Relational Mapping (ORM) Frameworks (e.g. Hibernate or TopLinkor or
iBatis), Enterprise JavaBeans (EJB), Java Data Objects (JDO), or the Data Access Objects
(DAO) pattern.Model is where Struts1.3 is ends and our application code (code for business
logic) beginnings .Struts provides ActionServlet class which is part of controller layer.
The org.apache.struts.action.ActionServlet is the backbone of all struts application.This
is the main controller component the handle client request and processing each request .It
serves as an Action Factory based on the user's request.
All the Action class in the Struts model extends the org.apache.struts.action.Action
class. The subclasses of Action class interact with the Model via interfaces and use its Data
Transfer Objects to pass and retrieve data.If we are using data code or business logic on
subclasses of Action class then we are making a bypass the separation of the Model layer
and the Controller layer. Doing so is violating the separations of model and controller.Struts
Result Component- Struts provide a so many numbers of functionality and features for
developing the View layer. We can use HTML/JSP, XML/XSLT, Velocity, and Swing, to make
view in Struts based applications. This is the power of Struts and MVC. Because HTML/JSP is
the typical View technology used for Java-based Web applications, Struts provides the most
functionality and features for developing your application this way. The remainder of this
chapter focuses on Struts support for creating the View layer using HTML/JSP.

The Model:- System State & Business Logic JavaBeans

Introduction:
A model represents appication's data and state and contains the business logic for accessing
and manipulating that data.where data that is part of the persistent state of the application.
ActionForm bean represents the Model state and not at a persistent level.The controller can

accessed model services effecting a change in the model state.The model notifies the view
when a state change occurs in the model.

Descriptions:
Set of one or more JavaBeans represents the internal state of the system .Entity Enterprise
JavaBeans (Entity EJBs) are also commonly used to represent internal state. The actions are
part of Controller. In struts1.3 we are using model, the model represent data and business
logic which are present in JavaBean and Action class in this tutorial we are see the format of
JavaBean which are following and format of Action class also which are following
HelloForm.java
package com.r4r.struts;
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class HelloForm extends ActionForm {
private String userName;
private String userDOB;
private String userCourse;
private String userCity;
private String userState;
private String userCountry;
private String userPhone;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserDOB() {
return userDOB;
}
public void setUserDOB(String userDOB) {
this.userDOB = userDOB;
}
public String getUserCourse() {
return userCourse;
}
public void setUserCourse(String userCourse) {
this.userCourse = userCourse;
}
public String getUserCity() {
return userCity;
}
public void setUserCity(String userCity) {
this.userCity = userCity;
}
public String getUserState() {
return userState;
}

public void setUserState(String userState) {


this.userState = userState;
}
public String getUserCountry() {
return userCountry;
}
public void setUserCountry(String userCountry) {
this.userCountry = userCountry;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
}
HelloAction.java
package com.r4r.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
import
import
import

org.apache.struts.action.Action;
org.apache.struts.action.ActionForm;
org.apache.struts.action.ActionForward;
org.apache.struts.action.ActionMapping;

public class HelloAction extends Action {


public ActionForward execute(ActionMapping mapping,ActionForm
form,HttpServletRequest request,HttpServletResponse response){
return mapping.findForward("success");
}
}

The View: -JSP Pages & Presentation Components

Introduction:
JavaServer Pages (JSP) technology is used to make the View portion of a Struts-based
application.
View serves as the screen representation of the model .It present the current state of the
data object.

Descriptions:
Struts HTML/JSP View layer support can be broken down into the following major
components:- >>JSP page >>Form Beans >>JSP tag libraries includes Struts include an
extensive custom tag library that facilitates creating user interfaces that are fully
internationalized. These are :1. The HTML Tag Library.
2.The Bean Tag Library.
3. The Logic Tag Library.
4.The Nested Tag Library.
Resource bundles In this tutorial provide the information of view in the struts1.3 framework.
The view portion are written in JSP,Velocity,etc. The view provide the presentation logic of
this MVC pattern. The following format provide the example of view:success.jsp
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
UserName:-<bean:write name="helloForm" property="userName"/><br/>
UserDOB:-<bean:write name="helloForm" property="userDOB"/><br/>
UserCourse:-<bean:write name="helloForm" property="userCourse"/><br/>
UserCity:-<bean:write name="helloForm" property="userCity"/><br/>
UserState:-<bean:write name="helloForm" property="userState"/><br/>
UserCountry:-<bean:write name="helloForm" property="userCountry"/><br/>
UserPhone:-<bean:write name="helloForm" property="userPhone"/>
index.jsp
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html:form action="helloAction">
User Name:-<html:text property="userName"/><br/>
User Date Of Birth:-<html:text property="userDOB"/><br/>
User Course:-<html:text property="userCourse"/><br/>
User City:-<html:text property="userCity"/><br/>
User State:-<html:text property="userState"/><br/>
User Country:-<html:text property="userCountry"/><br/>
User Phone:-<html:text property="userPhone"/><br/>
<html:submit></html:submit>
</html:form>

The Controller: ActionServlet and ActionMapping

Introduction:
The controller's main job is to map requests to action i.e. the controller is the first
component to act in the processing. So, controller function as a backbone for
a struts based application. Struts have Action class and ActionServlet class which is used as
controller. Controller servlet is most core of a Struts based application.
The Controller handles all requests from the user and selects the view to return. When the
Controller receives a request from user, Controller forwards the request to the
appropriate handler, which interprets what action to take based on that request.
Struts provides a ActionServlet class which is responsible for initializing a Struts applications
configuration file and receiving all incoming request and on the behalf of request
ActionServletpopulating the Form Bean with data, validating the From bean and then
selecting the appropriate Action class to execute.The Action class is where the Struts
Frameworks is ends and applications model(code) begins.After doing calculations and
manipulations Action class returns a key on the behalf of this key ActionServlet class
will decides the next view.
The ActionServlet Class is controller class that receives all incoming requests for the
application. ActionServlet is responsible for initializing the Struts framework for your
application.
Like other servlet ActionServlet must be configured in web.xml (in Web application
deployment descriptor).

Descriptions:
There are two ways that ActionServlet can be configured to receive requests in web.xml.

First, ActionServlet can be configured using path mapping, as shown here: Path
mapping routes to ActionServlet all requests that match a specified path.
The default path is /do/*. action org.apache.struts.action.ActionServlet
config /WEB-INF/struts-config.xml 1 action /do/*

The second way to map requests to ActionServlet is to use extension mapping.


Extension mapping maps to ActionServlet all requests with the specified extension.
The default extension to use is *.do action
org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml 1
action *.do

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="helloForm" type="com.r4r.struts.HelloForm"/>
</form-beans>
<global-exceptions />
<global-forwards>
<forward name="helloAction" path="/helloAction.do"/>
</global-forwards>
<action-mappings>
<action path="/helloAction" type="com.r4r.struts.HelloAction"
name="helloForm">
<forward name="success" path="/success.jsp"/>
</action>
</action-mappings>
<message-resources parameter="com.r4r.struts.ApplicationResources" />
</struts-config>

Getting Started a Struts Frameworks application

Introduction:
This chapter is a tutorial that covers getting started with Struts just the basics, nothing
more, nothing less. This tutorial assumes knowledge of Java, JDBC, Servlets,J2EE (with
regards to Web applications) and JSP. Although you can follow along if you are not an expert
in all of the above, some knowledge of each is assumed.

Descriptions:
This is stating point of struts .In next topics we will learn working about struts frameworks .

We covers Pre-Requirement for struts applications?

Where you can download?

We make an example.

How you can configure?

How you can works on view?

How you can make and configure ActionForm, Action and ActionServerlet?

Where you can store data?

How you can make response view.

Before starting struts we assume that you have good knowledge of Core Java, JDBC,
JSP/Servlet,J2EE (with regards to Web applications) and tomcat Server. We also covers
configuration with different version of eclipse. We will cover more examples into our next
tutorial. "Struts Basic
Example" http://r4r.co.in/java/struts/basic/example/index.php You will learn more
examples here.

Pre-requirement for struts applications

Introduction:
Before starting Struts Frameworks we need some pre requirement.We require some basic
knowledge of J2SE, JDBC, HTML, CSS, JavaScript, JSP/Servlet, J2EE and TomCat or
GlassFish Server( or similar type of server).

Descriptions:

Pre Pre-requirement Knowledge of:-Core Java/ JDBC/Collections JSP/Servelet


J2EE (with regards to Web applications) Tomcat Server or HTML/CSS/JavaScript/XML

Hardware:- Struts does not required any special Hardware.

Software/Jars:- Struts application need following software and jars.

Java Development Kits:- JDK1.5: You can download Java Development Kits
from http://developers.sun.com/downloads/

Struts Frameworks (Jars):-You can download Apache Struts http://struts.apache.org/

Servers Tomcat:- You can download Apache Tomcate http://tomcat.apache.org/

Server GlassFish Server:-You can download open source GlassFish


Server http://glassfish.java.net/public/downloadsindex.html

IDEs :-Today, All companies are using following IDEs for create, run and debugs a
Struts application. You can use notepad or any other IDEs .But we suggest use one
of following two--

Eclipse You can download eclipse http://www.eclipse.org/downloads/

NetBean You can download NetBean IDE


from http://netbeans.org/downloads/index.html

Operating System Environments:- Struts application can make run and debug on
Window/Linux

Downloading and configuring Struts

Introduction:
The minimum requirements for Struts applications are jdk, a web server(like tomcat and
GlassFish Server) and the Jars of the Struts Frameworks. Then you need to install jdk and
server and then configure the JDK, web server like tomcat and GlassFish Server and struts

frameworks. Here you will learn from where you can download? and how you can configure
it?

Descriptions:
Note:- We are using jdk1.6 and tomcat 6.0 in our all examples you can choose latest one.

Download JDK ,Tomcat and Struts Framework You can download it from following
given like.

Java Development Kits:- Download jdk1.6 http://developers.sun.com/downloads/

Struts Frameworks (Jars):-Download Struts


1.3.10 http://struts.apache.org/download.cgi#struts1310

Servers Download Tomcat 6.0.26:-Released Tomcat http://tomcat.apache.org/

Install JDK, Tomcat and GlassFish Server.

Set Java_Home (if you are using IDEs only)

Make a Web Work Space (like R4RSTrutsExaples) or make a j2ee workspace in


C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\ROOT
directory.Which includes WEB-INF . WEB-INF includes lib, web.xml, classes The
structure of Web Work Space (like R4RSTrutsExamples will be : R4RSTrutsExamples
WEB-INF Lib web.xml classes index.jsp

Now extract the struts framework and copy all jars from lib and past it into lib folder
of your workspace.

Make a struts-congif.xml into your WEB-INF and configure it into deployment


descriptor file ( web.xml file) e.g. R4R Struts
Examples action org.apache.struts.action.ActionServlet

config /WEB-INF/struts-config.xml 1 action *.do Or R4R Struts Examples action


org.apache.struts.action.ActionServlet config /WEB-INF/strutsconfig.xml 1 action /do/*

We will cover more about this web.xml configuration files into our next section.
Following is black struts-congif.xml .In struts-config.xml we configure Action classes ,
ActionForm plug-in etc

We will discus more about struts-config.xml in our next topic.

Your final workspace looks like R4RSTrutsExamples WEB-INF Lib(All jars will put into lib
folder) *****.jar ****.jar web.xml struts-congif.xml classes(All classes will put here) index.
jsp All JSP files,images,CSS etc will put here Now your Struts Workspace is ready. Now you
can start to develop a struts application. Download this blank Workspace from our website.
Just copy and past on
your http://r4r.co.in/java/struts/basic/tutorial/R4RSTrutsExamples.zip Here we had added only
struts core jar file you can add rest all as per as your need.
We will cover full example into our next topic.

Welcome Program using Struts

Introduction:
This is basic examples of how you can make a struts application. Here we are going to make
only View using JSP Struts Tag Library files. The purpose of this topic is taught you how you
can make, run and debug struts application?

Descriptions:
You can download "r4r-welcome-program-using-struts.zip" from our website. To do so just
copy and past following URL into address bar of your browser
http://r4r.co.in/java/struts/basic/tutorial/r4r-welcome-program-using-struts.zip and then
change its extension to .war then import it into your workspace by using any IDEs(eclipse or
Netbeans).If you are not using IDEs .Then extract it and save it into root folder into tomcat
webapp or you can deploy it on tomcat.Then you can see .Here you can see two xml files
(web.xml and struts-config.xml ) , one jsp (index.jsp)file,lib folder which includes all
required jars. The source code for these files are given below you can explorer these sours
code into your work space. To run our struts application start web server and type following
on browser http://localhost:8080/r4r-welcome-program-using-struts/index.jsp. Then you
will see the output on your browser.
Directory Structure of Welcome Example in Struts 1.3 Using MyEclipse IDE

index.jsp
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<logic:redirect forward="welcomeAction"/>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="welcomeForm" type="com.r4r.struts.WelcomeForm"/>
</form-beans>
<global-exceptions />
<global-forwards>
<forward name="welcomeAction" path="/welcomeAction.do"/>
</global-forwards>
<action-mappings>
<action path="/welcomeAction" type="com.r4r.struts.WelcomeAction"
name="welcomeForm">
<forward name="success" path="/success.jsp"/>
</action>
</action-mappings>
<message-resources parameter="com.r4r.struts.ApplicationResources" />
</struts-config>
WelcomeForm.java
package com.r4r.struts;
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class WelcomeForm extends ActionForm {
String welcomeMessage;
public String getWelcomeMessage() {
return welcomeMessage;
}
public void setWelcomeMessage(String welcomeMessage) {
this.welcomeMessage = welcomeMessage;
}
}
WelcomeAction.java
package com.r4r.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
import
import
import

org.apache.struts.action.Action;
org.apache.struts.action.ActionForm;
org.apache.struts.action.ActionForward;
org.apache.struts.action.ActionMapping;

public class WelcomeAction extends Action {


public ActionForward execute(ActionMapping mapping,ActionForm
form,HttpServletRequest request,HttpServletResponse response){
WelcomeForm wel=(WelcomeForm)form;
wel.setWelcomeMessage("Kumar Bal Mukund r4r.co.in");
return mapping.findForward("success");
}
}
success.jsp
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<h3>Welcome Example in struts1.3 framework</h3>
Welcome,<bean:write name="welcomeForm" property="welcomeMessage"/>
Output

What is directory structure of struts framework application?

Introduction:
The directory structure of a struts application is same as dynamic web application's.The
struts has one more xml file to configure ActionServelet, ActionForms, Actions etc. Struts

also added two other xml file(optional) to validate the data entered by users. Struts use
resources files to implements I18N in our application.

Descriptions:
The directory structure of struts is as following Assume project is name r4r.

r4r /WEB-INF:- This is not public .No file into this can used by clients directly

r4r /WEB-INF/lib:- (Includes jars )

r4r /WEB-INF/classes:- (All classes will put here. Basically all Servelets, business
logic and utility files )

r4r/ :- WEB-INF+ All JSP and static web resources(like images, html, css etc) are
stored into r4r or subfolder of r4r like for all css files may be into r4r/css etc .

The following Directory Structure in Struts 1.3 Using MyEclipse IDE

Set up a J2EE Web Application Project That Uses Struts


Frameworks

Introduction:
J2EE Web Application Project is dynamic web project. It is combination of Java, Servelet,
JSP and Static Web Recourses(like html, css, images, etc ). In J2EE only one xml is
required. That is deployment descriptor file (e.g. web.xml).This deployment descriptor file is
used to define all configuration of the J2EE web based application like welcome file,
securities, tag lib ,Servelet configurations and Servelet mapping etc.

Descriptions:
In struts only on more extra file is required that is struts-config.xml. Which is used to
configure the Actions, ActionForms, add plug-in etc. Here in Struts application we have
configured and mapping ActionServet into web.xml .The ActionServet works as controller in
Struts based application. We also need some Jars which we can download
from http://struts.apache.org/download.cgi#struts1310 Extract it and copy it and past it into lib
folder of your J2EE web application project. So we can say we have following steps to set up
a J2EE web application project into struts

Add struts frameworks jars into lib folder.

Create a struts-config.xml file.

Configure ActionServelet and add ActionServelet mapping into web.xml and add
struts-config.xml into web.xml

Create Subclasses ActionForm to gather the data of input JSPs and make Actions
class which is called by ActionServelet and call appropriate models and finally returns
a key. This key is used by ActionServelet to decide next view to user.

Directory Structure of UserInformation Example in Struts 1.3 Using MyEclipse IDE

index.jsp
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html:form action="userInfoAction">
User Name:-<html:text property="userName"/><br/>
User Date Of Birth:-<html:text property="userDOB"/><br/>
User Course:-<html:text property="userCourse"/><br/>
User City:-<html:text property="userCity"/><br/>
User State:-<html:text property="userState"/><br/>
User Country:-<html:text property="userCountry"/><br/>
User Phone:-<html:text property="userPhone"/><br/>
<html:submit></html:submit>
</html:form>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>

<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="userInfoForm" type="com.r4r.struts.UserInfoForm"/>
</form-beans>
<global-exceptions />
<global-forwards>
<forward name="userInfoAction" path="/userInfoAction.do"/>
</global-forwards>
<action-mappings>
<action path="/userInfoAction" type="com.r4r.struts.UserInfoAction"
name="userInfoForm">
<forward name="success" path="/success.jsp"/>
</action>
</action-mappings>
<message-resources parameter="com.r4r.struts.ApplicationResources" />
</struts-config>
UserInfoForm.java
package com.r4r.struts;
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class UserInfoForm extends ActionForm {
private String userName;
private String userDOB;
private String userCourse;
private String userCity;
private String userState;
private String userCountry;
private String userPhone;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;

}
public String getUserDOB() {
return userDOB;
}
public void setUserDOB(String userDOB) {
this.userDOB = userDOB;
}
public String getUserCourse() {
return userCourse;
}
public void setUserCourse(String userCourse) {
this.userCourse = userCourse;
}
public String getUserCity() {
return userCity;
}
public void setUserCity(String userCity) {
this.userCity = userCity;
}
public String getUserState() {
return userState;
}
public void setUserState(String userState) {
this.userState = userState;
}
public String getUserCountry() {
return userCountry;
}
public void setUserCountry(String userCountry) {
this.userCountry = userCountry;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
}
UserInfoAction.java
package com.r4r.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
import
import
import

org.apache.struts.action.Action;
org.apache.struts.action.ActionForm;
org.apache.struts.action.ActionForward;
org.apache.struts.action.ActionMapping;

public class UserInfoAction extends Action {


public ActionForward execute(ActionMapping mapping,ActionForm
form,HttpServletRequest request,HttpServletResponse response){
return mapping.findForward("success");

}
}
success.jsp
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
UserName:-<bean:write name="userInfoForm" property="userName"/><br/>
UserDOB:-<bean:write name="userInfoForm" property="userDOB"/><br/>
UserCourse:-<bean:write name="userInfoForm" property="userCourse"/><br/>
UserCity:-<bean:write name="userInfoForm" property="userCity"/><br/>
UserState:-<bean:write name="userInfoForm" property="userState"/><br/>
UserCountry:-<bean:write name="userInfoForm" property="userCountry"/><br/>
UserPhone:-<bean:write name="userInfoForm" property="userPhone"/>

Adding Struts to an existing Web application

Introduction:
You can add Struts Frameworks into your existing Web based Projects. Struts have very
easy steps to add struts into existing web projects.

Descriptions:
To add Struts Frameworks into existing web application.

Downloads struts frameworks jars.

Add it into lib folder into your existing web application.

Make struts-config.xml file and placed it with web.xml file.

Configure struts-config.xml into web.xml.

If you are see the all directory structure in MyEclipse IDE which are following

Output

Create web.xml and struts-config.xml

Introduction:

To make struts based application. We need minimum two XMLs that are web.xml and strutsconfig.xml .The web.xml is a deployment descriptor file which is most impartent file. For
Struts based application we need one more file struts-config.xml file to configure actions of
struts.

Descriptions:
The web.xml file provides configuration and deployment information for the Web
components that comprise a Web application. Web components are:

Servlet parameters,

Servlet and JavaServer Pages (JSP) definitions, and

Uniform Resource Locators (URL) mappings.

In deployment descriptor we can describe following deployment descriptor elements.

ServletContext init parameters

Localized context

session configuration

Servlet/JSP definitions

Servlet/JSP mappings

Tag Library

MIME type

Welcome file list

Error pages

Security information

A Sample Example of web.xml is for Servlet 2.4 application : The Servlet 2.4
application r4r WelcomeServlet welcome /r4r.welcome r4r.welcome 404 /error404.html .The
web.xml file must palaces into WEB-INF directory.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<web-app>
<servlet>
<servlet-name>welcome</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>/welcomeServlet</url-pattern>
</servlet-mapping>
</web-app>
In struts based application we have to configure

The Struts ActionServlet

The struts tag libraries files

The welcome files

The error pages.

and action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml validati


ng true 1 action *.do index.jsp /taglibs/struts-tiles /WEB-INF/taglibs/struts-tiles.tld 404 /err
or404.html. The most important configuration in web.xml is configuring strutsconfig.xml. We must have configured struts-config.xml (using the init-param tag) in
web.xml with in ActionServlet configuration.
e.g. action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml
.. Here we are mapping action servlet using two different url patterns..

This will receives all requests coming from URL Pattern .do extension .This request is
directed to ActionServlet action *.do e.g. http://localhost:8080/r4r/home .do this is
directed to ActionServlet and ActionServlet Lookup home (URI )into struts-congif.xml
called appropriate action.

This will receives all requests coming from URL Pattern /pages/*.This request is
directed to
ActionServlet action /pages/* e.g. http://localhost:8080/r4r/pages/home.

Note: These two ways are just only you can see URL pattern in browser and using this URL
pattern you can request to server.
When request is directed to ActionServlet then working will be same in both cases. strutsconfig.xml is most important file in struts based application .We can use more than one
struts-config.xml file into struts based application. The struts-config.xml can be placed in
WEB-INF folder.In struts-config.xml file we can configure ActionForm, Action
,DynaActionForm etc. All struts based components are configured here.
web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="loginForm" type="com.r4r.struts.LoginForm"/>
</form-beans>
<global-exceptions />
<global-forwards>
<forward name="login" path="/login.do"/>
</global-forwards>
<action-mappings>
<action path="/login" type="com.r4r.struts.LoginAction" name="loginForm">
<forward name="success" path="/success.jsp"/>
<forward name="error" path="/error.jsp"/>
</action>
</action-mappings>
<message-resources parameter="com.r4r.struts.ApplicationResources"/>
</struts-config>

Configure struts-config.xml into web.xml

Introduction:
The main xml file of an web based application is web.xml file.when request come from client
then first web.xml is call by server .On the behalf of configurations into web.xml the server
performs some task and lastly give response to client. For struts based application strutsconfig.xml and web.xml are required .We must have configure struts-config.xml into
web.xml so that when request come from client then struts-config.xml file will loaded. Here
we will learn how to configure struts-config.xml into web.xml.

Descriptions:
To configure struts-config.xml file into web.xml see following code action:org.apache.struts.action.ActionServlet config:- /WEB-INF/struts-config.xml validating true.
web.xml
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="loginForm" type="com.r4r.struts.LoginForm"/>
</form-beans>
<global-exceptions />
<global-forwards>
<forward name="login" path="/login.do"/>
</global-forwards>
<action-mappings>
<action path="/login" type="com.r4r.struts.LoginAction" name="loginForm">
<forward name="success" path="/success.jsp"/>
<forward name="error" path="/error.jsp"/>
</action>
</action-mappings>
<message-resources parameter="com.r4r.struts.ApplicationResources"/>
</struts-config>
Here at time of Standard Action Servlet Configuration in web.xml we have to configure
struts-config.xml.This is because load struts-config.xml at time of call ActionServlet . We
can add more than one struts-config.xml file by creating sub-modules. e.g. Say we have
two module report module and her module .

Configure the Action, ActionForm and Forward in the Struts Configuration File

Introduction:
In this section, We will learn how to configure the subclass of Action & ActionForm and
Forward the request to next view page.

Descriptions:
All Action subclasses and subclasses of ActionForm must be configure into struts-config.xml.
The struts framework provides some rules and tags to configure it. Forward must be
configure with in <action>tags. Which are show following example:
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
<form-beans>
<form-bean name="loginForm" type="com.r4r.struts.LoginForm"/>
</form-beans>
<global-exceptions />
<global-forwards>
<forward name="login" path="/login.do"/>
</global-forwards>
<action-mappings>
<action path="/login" type="com.r4r.struts.LoginAction"
name="loginForm" scope="request/session" validate="true/false/yes/no">
<forward name="success" path="/success.jsp"/>
<forward name="error" path="/error.jsp"/>
</action>
</action-mappings>
<message-resources parameter="com.r4r.struts.ApplicationResources"/>
</struts-config>
Path attributes:-The value of path attribute of <action>tag must be same as
<html:form>action attribute. eg.<html:form action="/login"><action
path="/login">.The input attribute of <action>tag consist the name of Input JSP View.
<action-mappings>
<action path="/login">
<forward name="success" path="/success.jsp"/>
<forward name="error" path="/error.jsp"/>
</action>
</action-mappings>
Scope attributes:-The scope attribute is used to define scope for request or session .
<action-mappings>
<action path="/login" scope="request/session">
<forward name="success" path="/success.jsp"/>
<forward name="error" path="/error.jsp"/>
</action>
</action-mappings>
Type attributes:-The type attribute is fully qualified name of Action subclass.
<action-mappings>
<action path="/login" type="com.r4r.struts.LoginAction"
scope="request/session">
<forward name="success" path="/success.jsp"/>
<forward name="error" path="/error.jsp"/>
</action>
</action-mappings>
Validate attribute:-The validate attribute is for enable/disable the for check form
validation.
<action-mappings>
<action path="/login" type="com.r4r.struts.LoginAction"
scope="request/session" validate="true/false/yes/no">
<forward name="success" path="/success.jsp"/>
<forward name="error" path="/error.jsp"/>

</action>
</action-mappings>
Name attributes:- The name attribute is used to tell controller for lookup the name of
action form to store input data. The value of name attribute must be same as appropriate
name attribute. We can configure more than one Action within tag. To configure Forward
struts provides tag. This tag has two attributes name and path.The value of name attribute
is the key which will matched with key returned by appropriate action subclass and this
value is used to forward to next view (to the value of path attribute).We can configure more
than one forward with in tag. Struts provides tag to configure the subclass of ActionForm.
tag have two attributes name and type .The type attribute is fully qualified name of subclass
of ActionForm and the name is through which controller lookup to store the data coming for
Input JSP View.
<action-mappings>
<action path="/login" type="com.r4r.struts.LoginAction"
name="loginForm" scope="request/session" validate="true/false/yes/no">
<forward name="success" path="/success.jsp"/>
<forward name="error" path="/error.jsp"/>
</action>
</action-mappings>

ActionForm Overviews

Introduction:
An ActionForm is a JavaBean .It associated with one or more ActionMappings. ActionForm
represents the Form input contaning the request parameters from the view referencing this
Action bean. ActionForm bean will have only getter and setter methods but no business
logic.

Descriptions:
We can used validator Framework with static ActionForms and Dynamic ActionForms.The
ActionForm object also offers a standard validation mechanism.We can define a getter and
setter method for each field that is present in the form. The field name and property name
must match according to the usual JavaBeans conventions.
LoginForm.java
package com.r4r.struts;
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class LoginForm extends ActionForm {
private String name;
private String password;

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

What is an ActionForm?

Introduction:
An ActionForm is also called JavaBean. When client will enter the data from the form than
this object is automatically populated on the server side.

Descriptions:
ActionForm class maintains the session state for web application.The ActionForm class
extends from org.apache.struts.action.ActionForm. ActionForm class have getter and
setter method. Getter method is used to get the value from the form and setter method is
used to set the value.
Struts Framework provides the functionality to validate the form data. When client enter the
input from form if We want to add some validation than We can add the validate() method
in the ActionForm class. Error messages are added to the ActionMapping object. We can be
use to validate the data on the users browser as well as on the server side.
LoginForm.java
package com.r4r.co.in;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
public class LoginForm extends org.apache.struts.action.ActionForm{
private static final long serialVersionUID = 11112;
private String username,password;
public String getPassword() {
return password;

}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public ActionErrors validate(ActionMapping mapping, HttpServletRequest
request) {
ActionErrors errors = new ActionErrors();
if (username == null || username.length() < 1) {
errors.add("username", new ActionMessage("error.username.required"));
}
else if (password == null || password.length() < 1) {
errors.add("password", new ActionMessage("error.password.required"));
}
return errors;
}
}

Configure ActionForm into struts-config.xml

Introduction:
In struts-config.xml,The form bean definition section contains one or more entries for each
ActionForm but each bean have a unique logical name. The type represent the fully qualified
class name of this ActionForm.

Descriptions:
In action mapping section ,Name attibutes define the logical name of the Form bean. Action
Mapping associated the Actual ActionForm. ActionMapping is found by looking in the Formbean definition section for a form-bean with the matching name.
In this example ,Action Mapping associated the LoginForm that is found by looking in the
Form-bean definition .
LoginForm.java
package com.r4r.struts;
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class LoginForm extends ActionForm {

private String name;


private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="loginForm" type="com.r4r.struts.LoginForm"/>
</form-beans>
<global-exceptions />
<global-forwards>
<forward name="login" path="/login.do"/>
</global-forwards>
<action-mappings>
<action path="/login" type="com.r4r.struts.LoginAction" name="loginForm">
<forward name="success" path="/success.jsp"/>
<forward name="error" path="/error.jsp"/>
</action>
</action-mappings>
<message-resources parameter="com.r4r.struts.ApplicationResources"/>
</struts-config>

Understanding the Life Cycle of an ActionForm

Introduction:
In this chapter, We will discuss the lifecycle of an ActionForm. ActionForm class maintain the
session state of web application.

Descriptions:
ActionForm sits between the View and Controller.ActionForm play the role of transfer object
between the presentation layer and Business layer.
Life Cycle of an ActionForm:Request is submitted.The ActionServlet controller matches the URI for the request against
the path of an action-mapping.

Create or recycle ActionForm

The ActionServlet then calls reset() on the new or pre-existing ActionForm from the
request.

You can store ActionForm in desired scope

When passing ActionForm beans between Actions.It is important to populate


ActionForm from Request. If you modify a value, you must be sure to protect it from
auto populate or reset

If Validate is set to true,the ActionServlet call the validate method.

This return any errors message.then forward back to input attribute page actionForm
in scope.If no errors found then call execute() with the ActionForm.

Forward to success

You might also like