Struts:-: Struts Framework Is A Piece of Software Which Contains The Solutions To

Download as pdf or txt
Download as pdf or txt
You are on page 1of 130

Struts :-

Struts Framework is used to develop the web based application. It simplifies the
development of web based applications.

By using Struts we can develop only web based applications. We can’t develop the
standard alone applications.

We can use any of the following frameworks to develop the web based
applications.

The y are :

1. Struts 2.Spring 3.Jsf 4.Web work 5.OpenSymphony

Struts framework is a piece of software which contains the solutions to


commonly repeatedly occurred problems across multiple projects.

The following are the advantages of Frameworks like Struts and spring:-.

 Frameworks resolve the problems of identifying the architecture. Every


framework like Struts and Spring is delivered with MVC2 architecture.
 If we use Servlets and Jsps we have to develop our own Controllers. If we
use frameworks like Struts and Spring internally they came with Controllers
Eg: ActionServlet in Struts
DispatcherServlet in Spring
 When we use any framework we no need to use RequestDispatcher code as
well as we no need to hard code the resource path names. By using these
frameworks we can configure them in the configuration files.
 If we use JDBC, Servlets, Jsps to develop the form based applications we
have to write huge amount of code to take care of Server side validations
and displaying errors in the same form.
 By using JDBC, Servlets, Jsps we have to provide huge amount of code to
develop the I18n applications. (The programs which displays the output
based on client regional Languages)
 The frameworks like Struts and spring delivered with set of predefined tag
libraries. If we use Servlets and Jsps we have to develop our own tag library
which is difficult.
 When we use the frameworks like Struts and spring we can use
pdf/velocity/jsf as view components.

Most of the experienced guys are develops the new frameworks.

Every Company uses their own frameworks to develop the projects .all these
frameworks internally uses the other frameworks.

Infosys is using Pinacle framework.

Apache Company has released Struts framework to develop web based


applications based on Model2 Architecture.

Apache guys has released Struts framework in 2 versions.

They are: 1) Struts 1.x

2) Struts 2.x

We can download the framework from in multiple flavors. i.e. we can download
only the Struts jar file or we can download only documentation or example
applications. We can download struts from following link
http://struts.apache.org/

When we download the Struts software majorly we get the following 3 files.

1. Set of Struts related jar files (struts-core.jar, struts-taglib.jar).


2. The documentation is available in Docs folder.
3. All the sample examples are available in apps folder.

Developing First Struts based application:

We can create the Struts based application by copying the jar files manually and
we can configure them in web.xml.
Instead of doing manual work we can develop our first struts based application
from struts-blank.war.

Create a folder whose folder name is project name. and copy the struts-
blank.war file into above created folder and extract the contents of it by
using following command
Jar -xvf struts-blank.war

When we download struts framework we get the following four components :-

1. A servlet whose name is org.apache.struts.action.ActionServlet.


2. Set of predefined classes , some of them are :
Action, ActionMapping, ActionForward, ActionErrors, ActionError,
ActionMessage, ActionForm.
3. Set of Struts tag libraries
a. Html
b. Bean
c. Logic
d. Nested
4. Get the struts-config.xml and validation.xml .

The following is the struts configuration file :


The following steps will be carried out when we deploy Struts based project :

1. Server will read the contents from web.xml file and store the information
in jvm’s memory.

2. As there is <load-on-startup> tag for ActionServlet server has created


ActionServlet object.

3. After server has created ActionServlet object server executed 1st


init(ServeltConfig) method and it will call the 2nd init() method. As part of
init() method it will find the configuration file name details and by using
parser program it read the contents from configuration file and store it in
jvms memory.
The following is sample code available in predefined class ActionServlet

Whenever any client sends any request to server whose url pattern end with .do
ActionServlet service() throws an exception saying InvalidPathException: No
action config found for the specified url.

A framework defines a procedure to carry out a task/ work.

We will get the path of the resource from url when remove the .do from path
In struts if we would like to carry out any work we need to develop Action classes.
Without Action class we can’t carry out any work.

What is an Action class?

ans) A class which is a subclass of org.apache.struts.action.Action is called as


Action class.

Developing Action classes:

The following is Action class


ex:

To compile the above program we have to set the CLASSPATH to servlet-api.jar


and struts-core.jar.

We must configure every Action class in struts-config.xml file.

Whenever we deploy a project in server it reads the content from web.xml file.
Server represents the every tag in the form of Object. When we deploy the Struts
project server has created the following two objects.
Whenever server has encounter an <action> tag in struts configuration file. It is
creating an ActionMapping object . and it’s containing the the path and type as
shown below.

The following steps will be carried out when a client has send request to server
whose url pattern end with .do.

1. Server creates request and response objects and handover to ActionServlet


service().
2. ActionServlet service() get’s the servletPath information using request
object as shown below
request.getServletPath() Then it will remove the .do from that. Then it will
get Path of the resource of Action class.
3. service() method checks is there any ActionMapping object is available
whose path is matches to /ao.
4. If there is no ActionMapping object is available whose url pattern matches
to /ao then server throw an exception InvalidPathException.
5. If ActionMapping object is available server gets the name of the Action
class. then it will check is there any ActionOne object is available or not. If
available it will not create any new ActionOne object other wise it will
create a ActionOne class object using Class.forName(ActionOne). So always
we have to main default constructor in Action classes. Then ActionServlet
service () will call the execute() using ActionOne object.
6. As ActionOne class execute() method returning ActionForward object with
null value.
7. Whenever ActionServlet service() method has encountered a null value as
part of ActionForward object. It stops execution of request. It will display a
blank screen to the user.

To get the values from ActionMapping object for that we can use getXxx()
methods of ActionMapping class as follows
Whenever we change struts configuration file we must restart the server. This is
because ActionServlet reads the contents from configuration file at the time
deployment only.

We use parameter attribute in configuration file to supply an extra information to


that particular action.

<action path=”/ac” type=”ActionMappingDemo” parameter=”one” />

name attribute is used as logical name to identity a particular action. This name
attributed used mainly in developing form based application.

As part of the Struts configuration file added an extra tag as <forward>

when we deploy the Project for the above configuration server reads the
web.xml and then creates the ActionServlet object and call the init() .

As part of this server reads the configuration file and when Parser encounters the
<action> tag and <forward> then it will creates ActionMapping and
ActionForward objects as shown below
To check whether an ActionMapping object contains a specific ActionForward
object or not . we can use a method mapping.findForward(“Forwardname”)

syntax:

ActionForward findForward(String forwardName);

when we call findForward() method if the ActionForward object is available it


return the reference of that Object. with that name if no ActonForward object is
not available it return null value.

For the above code it returns ActionForward object for af1 and af2. For af3 it
returns a null value.

Developing an Action class which forwards the request to one.jsp

The following steps are carried out when client sends the request to Action class

1. ActionServlet service() creates the Action class object if required.


2. ActionServlet service() finds the path of the Action class in ActionMapping
object and call the execute() (ActionServlet service() supplies the
ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse
objects).
3. server execute execute() method and return ActionForward object to
ActionServlet service().
4. Once if the ActionForward object returns to service() method. it checks the
path of the resource and It gives input to RequestDispatcher object and it
will dispatch the request to appropriate jsp.

Develop a struts based application to retrieve all the records from emp table and
display to the client. we should not write the any java code in jsps.

we have to follow the following steps:

1. Develop an Emp javaBean class to store Emplopee details


2. Develop an Action class to interact with database server and retrieve the
records and store it in request scope. For that develop one DAO class
which will return the ArrayList object.
Now develop the Action class as follows.

3. The following is the jsp which display output to the client by using core tag
libraries.
JSTL :

jstl has given sql taglibrary. This tag library contains set of tags which are used to
interact with database server.

It’s not recommended to use sql tag library in the jsps . This is because if we use
sql tag library we are clubbing business logic and presentation logic.

The following DataSource and update querys are used to write jdbc code in jsp.

The following <query> tag is used to display all the records from Emp table.
I18N Applications :-

The application which display the output to the client based on their regional
language.

We can use property files to develop I18N applications.

I18N applications can be developed for both standalone applications as well as


web based applications.

By using properties files we can remove hard coding also.

Every property file must end with an extension called as .properties

In a project we maintain multiple properties files

In a properties file we supply the data in the form of key and value.

eg:

The following is an example demonstrates how to read the contents from


properties file.
Eg:
The following program for write the contents to Properties file

The following properties file created when we run above program.

We can write the comments in Properties file using # symbol. We can observe
that in above example.

In web based applications to read the contents from properties file we are using
getResourceAsStream (“properties filename”); which is available in Class class.

To read the properties file by using this method we have to place the properties
file in classpath if the program doesn’t contain package statement. If the program
contains package statement we have to place this properties file inside package
folder. we have to place properties files where .classes file is available.
ex: without package in a program we have to keep properties file in classes
folder. Otherwise we have to place that in package folder ex.
blmse/jee/struts/DBUtil.properties.

An organization ISO has assigned the two letter code for every country and every
language.

Generally the country letter code will be representing in Capitals e.g.: IN, US

Generally the language letter code will be represent in small letters e.g: te, en

To develop I18N application we required regional and language information of


that computer.

To find the current computer regional and language information we can use
java.util.Locale object.

To find the Locale information of our computer we have to get the Locale object.
From the Locale object we can get country code and language code.

ex:

To develop I18n applications we need to create multiple properties files. These


properties files are called as Bundle.
Procedure to use I18N applications in standalone applications:

1. We need to create the properties files. The no. of properties files are based
on the languages supported by our project.
In our project we would like to support to 2 languages they are: English and
Telugu.

2. To read the contents from properties fie based on client regional language
we have to take the help of java.util.ResourceBundle class

The following example demonstrates how to read the contents from


ResourceBundle.
When we are retrieving a key from ResourceBundle which is not available it
throws an Exception saying:

When we test our application for the properties files which doesn’t support other
languages application then it throws an Exception saying:

The project supports two languages and when we run the same project in the
computer which doesn’t support the other languages we should not get any
exception rather than that we should display the default language.

To achieve this from the properties file name we have to remove the country
code and language code. ex

Procedure to use I18N applications in webbased applications:

We have developed the following jsp to display the output based on the Client
regional language. But it is always displaying output in English language only. This
is because we have hardcoded the values in jsp.

From the following jsp we have to remove the highlighted hardcoded values.
When the client sends the request to a server, Server creates request and
response objects. Now server finds the client’s regional language from Accepted-
Language header and creates the Locale object. That Locale object is associated
with request object.
The following is the jsp demonstrates that how to do we find the Locale object of
client and send it back.

<% Locale objLocale = request.getLocale();

out.println(objLocale);

%>

Procedure to use I18N applications in webbased applications:

1. Create the properties files to support multiple languages as shown below.

2. Copy all the properties files into classes’ folder. This is because all the web
based application classpath is set to classes folder.
3. Develop a jsp to find the client regional language and based on that read
the contents from properties file and display message to the user.
The disadvantage of above jsp is we have provided lot of java code. It’s not
recommended to write java code in Jsps. To remove the java code from above
jsp we have to use jstl tag library as shown below.
Procedure to use I18N applications in Struts based applications:

1. Create the properties files to support multiple languages as shown below.

2. Copy all the properties files into classes folder. This is because all the web
based application classpath is set to classes folder.
3. Configure the properties files in struts-config.xml file by using
<message-resources> tag.
ex:
<struts-config>
<message-resources parameter="messages" />
</struts-config>
4. Develop a jsp to display the output to the user based on the struts tag
library. Use message tag of bean tag library. as shown below
When we use the message tag for a key which is not available it will throw an
exception saying Missing message key for bundle.

Generally when multiple people are working on same project and they want to
share properties files and whenever we are using a key which is not available my
application should not throw any exception. To achieve this we have to configure
null=false in the struts configuration file as shown below

<struts-config>
<message-resources parameter="messages” null = “false”/>
</struts-config>

By default struts uses null=”true” the meaning of null= true is if the key is not
available if returns a null value to struts. When it returns null value to struts it
throws an exception.

When we specify null=false even if the key is not available it will not throw any
exception it throws the following error.

eg: ???en_US.msg.ls???

It is nothing but client regional language and which key is not available.

Using multiple bundles in struts:


We are trying to use multiple bundles in struts based projects. As shown below.

1. Develop the properties files for multiple bundles as shown below


3. Copy all the properties files into classes folder. This is because all the web
based application classpath is set to classes folder.
4. Configure the properties files in struts-config.xml file by using
<message-resources> tag.
ex:
<struts-config>
<message-resources parameter="resone" />
<message-resources parameter="restwo" />

</struts-config>

5. Develop a jsp to display the output to the user based on the struts tag
library. Use message tag of bean tag library. as shown below
When we run above program it will throw an exception Missing key for resource
userName and password . we have observed that for the above configuration in
struts configuration file it is able to read the contents from only one resource
bundle that is which is configured as last file in struts configuration file. in our
example it is able to read the messages from only restwo bundle. When we are
reading keys in resone bundle server throwing an exception.

To resolve the above the problem we have made changes in struts configuration
file by adding an attribute key in message-resources tag.

<struts-config>
<message-resources parameter="resone" key=”rone”/>
<message-resources parameter="restwo" key=”rtwo”/>

</struts-config>

While we are using the message tag in the jsp we need to specify in which bundle
It have to search by using an attribute called as bundle.
Explanation:

When we configure ResourceBundles without keys they try to store two bundles
into application scope (ServletContext object) by using same key as
org.apache.sturts.action.Message whenever server has encountered

<message-resources > tag Server is creating a org.apache.struts.util.


PropertyMessageResources object.

<struts-config>
<message-resources parameter="resone" />
<message-resources parameter="restwo" />

</struts-config>

When the above configuration is executed it will try to create two


PropertyMessageResources objects. And trying to store these objects In
application scope with default key (org.apache.sturts.action.Message).

eg:

application.setAttribute(Globals.MESSAGE_KEY, objPropertyMessageResources1);

application.setAttribute(Globals.MESSAGE_KEY, objPropertyMessageResources2);

in this example objPropertyMessageResources2 is overrides the first value. that ‘s


why we are able to read the values from only one ResourceBundle.
When we modify the properties files we need restart the server. Because
properties files read by server only once. ie at the time of deployment.

org.apache.sturts.action.Message value is available as key for


Globals.MESSAGE_KEY.

The logic tab library contains set of tags which are used to check the logical
conditions. for example Present, notpresent, greaterthan and lessthan etc .

<logic:present name=” Globals.MESSAGE_KEY” scope=”application ”>


The key is available
</logic:present>
When we specifiy key attribute in message-resources then with that key
PropertyMessageResources object will be stored in application scope as shown
below
application.setAttribute(“rone”, objPropertyMessageResources1);

application.setAttribute(“rtwo”, objPropertyMessageResources2);
How to deal with errors in struts?
In struts 1.2 they have given 4 different classes to deal with errors/Messages .
They are
1. ActionErrors
2. ActionError
3. ActionMessages
4. ActionMessage
But in struts 1.3 they removed the ActionError class . so in struts 1.3 we have only
three classes to deal with errors.
If we want to deal with ActionErrors we have to create ActionErrors object and
add Error message by using ActionMessage object.

Requrirement : Develop an action class which generates 5 errors and display it in


the jsp.
Step1: create the properties files and add all the errors to properties files. then
place those properties files in classes folder then configure that in the struts
configuration file.
ex:
step2: Develop an action class which generates errors and add it to the request
scope.

Step3: Configure Action class into struts configuration file. As shown below

Step4: Display errors in one.jsp


To display errors in struts we use <errors> tag in html tag library.
Explanation:
When client sends the request to the server to execute TestErrorAction the
following steps are carried.
step1: Server has handover request object response object to the ActionServlet
service() method. ActionServlet service() creates the Action class object if
required.
step2: ActionServlet service() finds the path of the Action class in ActionMapping
object and call the execute() (ActionServlet service() supplies the ActionMapping,
ActionForm, HttpServletRequest, HttpServletResponse objects).

step3: execute() method create ActionErrors object and add the ActionMessage
object’s to that. ActionMessage is taking the error key as parameter.

Step4: When the saveErrors(aes, request) method is called ActionErrors object


will be stored in request scope by using a key org.apache.struts.action.ERROR

Step5: server execute execute() method and return ActionForward object to


ActionServlet service(). Once if the ActionForward object returns to service()
method. it checks the path of the resource in ActionForward object and It gives
input that to RequestDispatcher object and it will dispatch the request to
error.jsp.

Step6:One.jsp displays the errors.

when the <html:errors /> tag is evaluated it will get error key from request scope
and get all the error messges from the properties files and display to the client.
To display error messges we are using a tag <html:errors /> This tag is uses html
tags which are configured in properties file. The following are the tags which are
available in properties file.

# -- standard errors --
errors.header=<UL>
errors.prefix=<LI>
errors.suffix=</LI>
errors.footer=</UL>

It’s recommended to use <html: messages> tag to display errors

To display the specific errors based on a group we use property attribute as


shown below. Here e1 is group name with which we stored ActionMessage
object into ActionErrors object. eg: aes.add(“e1”, am1);

<html:messages id="msg" property="e1">

<li><bean:write name="msg" /></li>

</html:messages>

We achieve same thing using <html:errors /> tag also. eg:

<html:errors property=”e2” />


In Struts we can use any URL pattern in web.xml file. for eg: we can use *.htm

for Action servlet as shown below.

Generally struts people follow any of the following URL patterns .

1. *.do
2. /do/*

eg: as shown below configuration in web.xml


When client sends the request to server which ends with .do or which start with
/do/ then that URL matches to ActionServlet so ActionServlet service() method
will be executed.

eg:

1. login.do
2. /do/login

In both examples it will invoke the login Action class whose path is login
configured in struts-config.xml in ActionMappings tag.

If we want to work with Messages in struts we have to create ActionMessages


object and add the messages to ActionMessage object then add the
ActionMessage object to ActionMessages object . eg:

Requrirement : Develop an action class which generates 5 messages and display it


in the jsp.
Step1: create the properties files and add all the messages to properties files.
then place those properties files in classes folder then configure that in the struts
configuration file.
step2: Develop an action class which generates messages and add it to the
request scope.

When saveMessages() method is executed all messages are stored into request
scope by using a key org.apache.struts.action.MESSAGE

Step3: Configure Action class into struts configuration file. As shown below

Step4: Display messages in messages.jsp


To display messages in struts we use <messages> tag in html tag library as shown
below.

By default messages tag get the data from ERROR KEY. To get the data from
org.apache.struts.action.MESSAGE KEY we must specify message=true attribute.
For<html: messages > tag we can use property attribute to display based on the
location or group.
eg: <html: messages id=”msg” property=”header” message=”true”>
In program it self we can create the ActionForward object and give an input to the
jsp file to which jsp we want to forward the request.
ActionForward af = new ActionForward(“/one.jsp”);
It’s not recommended this approach. This is because we are hard coding the path
of the resource.
Form based application in Struts :
Majorly in struts we have 3 ways to develop the form based applications: They
are :
1. ActionForm
2. DynaActionForm
3. DynaValidatorForm
Form based application using ActionForm :
we have to follow the following steps to develop form based apps
Step1 : Get the Prototype. From the prototype identify the following three
elements
1. Identify the field names (Property name) for every field available in that
form.
2. Identify the form name (the name shouldn’t contain any spaces)
3. Identify the all the validations required on that form.
eg:

Step2: Develop the FormBean class


What is FormBean class?
A class which is a subclass of org.apache.struts.action.ActionForm directly or
indirectly
Developing StudentFB class with 3 properties and override the reset() and
validate() methods as shown below.
Step3: configure the FormBean class in struts configuration file
1. copy all the formbean classes into classes folder.
2. provide all the error messages in properties files and configure them in
struts configuration file.

3. configure the Formbean class in sturts configuration file in <form-beans>


tag

Step4: Develop the input form or form view


The following form responsible to display the form as like prototype which uses
html tag library.
Step5: Develop an action class which is responsible to capture the data and store
it database server.
The struts internal code is responsible to create FormBean object and capture the
data and store it in FormBean object. This formbean object supplied to
parameter to execute() method .
In the execute() method from the actonform object we get the data and store in
database server.
Step6: Configure the action class in struts configuration file

Step7: develop a success form (success view).


This is responsible to display success message to the user.
Deploy the project and test it. Once we have deploy the above project we have to
start testing the project from the jsp(studentregform.jsp).
When we starting executing the studentregform.jsp we have observed that the
internal code is creating FormBean object and doing a lot of other work.
Explanation:
When we send the request to the server for studentregform.jsp server start’s
executing that. As part of that when server encounters <html:html > it will
evaluated by jsp compiler has converted into regular <html> tag.

We can provide an attribute called as lang to the html tag. This attribute will find
the language setting of the client and sent it back. The advantage of this attribute
is to fix some language specific problem.
<html:html lang=”true” />
When the jsp compiler encountered head, title, body tags it is treated as
template text and sent to the client.
<html:form >
To create the form in jsp we use <html:form > tag. Whenever we are using
<html:form > tag without action attribute it throwing an exception.
<html:form >
</html:form >
The above tag will throw an NullPointerException. this is because we doesn’t
supply the action attribute to the form tag.
When <html: form > tag is evaluated (evaluating the java code) it takes the value
of the action attribute. From the value it will remove the .do if it is available .
Now we got the path of the resource. Now struts internal code checks is there any
ActionMapping object is available whose path matches to it. If ActionMapping
object is not available it throw an Exception saying : Can’t retrieve mapping for
action
If ActionMapping object is available it gets the name from ActionMapping object.
For that name Struts internal code checks is there any FormBean object is
available whose name matches to it. If not available it throw an Exception saying:
Matching FormBean object is not available.
If matching fomBean object is available then it gets the name of the FormBean
class. Now struts internal code checks what is specified scope attribute in action
tag. In that scope it will check whether FormBean object is available or not. If
FormBean object is not available then it’s creates the FormBean object using
Class.forName().
After creating the FormBean object it will call the reset() method. This FormBean
object is added to specified scope.
Now html:form tag will sent regular html form tag to the client.
From the above diagram we have understand that FormBean object is added to
request scope. When the server sends the output to the client immediately server
removes request and response objects. Now the server remove the FormBean
object also when scope is request.
If we don’t specify the scope attribute in configuration file by default the scope it
uses as Session. scope=”session” --- default value for scope attribute.
<html:text />
Whenever <html:text /> is evaluated the following steps will be carried out:-
1. It checks whether the mandatory attribute property is provided or not. If
not available send error messages.
2. If the property attribute is available it gets the value of property attribute
and check whether this property is available in FormBean object or not? If
not available it sends an error message.
3. if matching property is available then struts internal code will call the
getXxx() methods.
The struts internal code uses return value of getter () methods and generates
regular html tags as shown below.

<html:submit />
When the above tag is evaluated it will generate regular submit button.
For submit button we no need to provide the property attribute. If we supply
property as attribute it takes property as name. This attribute is used to uniquely
recognize the button.
<html:errors />
When above tag is evaluated it will check any errors are available in request
scope or not. If not available it will not display any errors. If it is available it will
display errors to the user.

<html:base />
When this tag is evaluated it will find the corresponding jsp which is getting
executed and it gives that URL as value to the base tag. The advantage of this is
the maintenance of project becomes easy.

For the <html: form /> tag we can supply the attributes like disabled, focus, and
onsubmit attributes. By using onsubmit attribute we can perform client side
validations.
disabled=”true” : To disable the form .
ex: <html:form action=”sa.do” disabled=”true” /> then form is not available to
do any operation
focus=”propertyName” : To focus on the element or put cursor on specified field
<html:form action=”sa.do” focus=”sno”/>
onsubmit=”return validate()” :
If we want to make sure that the form is submitted only once, The user clicks on
submit button we need to disabled submit button so that form is submitted only
once.
The following steps will be carried out when we submit the form: ---
The request will go to the server. Request and response objects will be created
then ActionServlet service () method will execute as part of this it will check is
there any name attribute. If it finds the name attribute then it gets the value of
that with that name it will check is there any FormBean object is configured if it
finds then it will get the FormBean class name.
1) Now server will check is there any FormBean object is available in specified
scope. If required the struts ActionServlet service() (struts internal code)
Create FormBean object and call the reset().
if scope=”request” every time when we submit the form every time it will
create FormBean object.
If scope=”session” FormBean object is created only once.

2) Struts internal code (ActionServlet service ()) will capture the data and store
the data into FormBean object by calling setXxx () methods.
Note: Internally struts uses request.getParameterNames () and reflection API to
store the values to FormBean object.
3) Struts internal code (ActionServlet service() ) checks whether validate
attribute is available or not in struts configuration file. If we are not writing
any validate attribute in configuration file then the default value for
validate is true from struts 1.3
Before that validate =”false” up to struts 1.2 .
 If value is true it will call the validate () method of FormBean class.
 if validate=”false” it will not call validate () method. Struts internal
code (ActionServlet service () method ) will create Action class object
and call the execute() method. execute() method is responsible to
store the data into database server and forward the request to
appropriate success form.

4) if the validate() method returns errors to ActionServlet service() method


then it will check the input attribute value specified in <action > tag and
get’s the value and forward the request to student.jsp.
<action name=”a” input=”/student.jsp” />
 If there are no errors return by validate() method to ActionServlet
service() method then struts internal code(ActionServlet service()
method ) will create Action class object and call the execute()
method.
 execute() method is responsible to store the data into database
server and forward the request to appropriate success form.
Validations:
We can perform two types of validations on the form. They are:
1. Server side validatations.
2. Client side validatations.

Server side validatations:-


The server side validations will be carried out in the server. The
disadvantage of this is it consumes more resources of server. The
advantage is we write the validation code in java.
If we are performing server side validations if multiple clients send the
request at the same we can find more load on the server. To resolve this
type of operation we can use client side validations.
Client side validatations :-
The client side validations will be carried out in the browser itself. For client
side validations we will write in JavaScript.

We want to develop a form based application where we want to get city and state
data from the user. But the information about city and state available in a table
called as city-state table. In this example if we want to perform client side
validations we have to write huge amount of JavaScript code to carryout
validations. In this type of scenarios not recommended to use client side
validations.
When do we use Server side validations?
If we want to check the data entered by the user with the data available in
database server we have to use server side validations.
When do we use Client side validations?
If we want to check the data entered by the user is not dependant on the data
which is available in database server we have to use client side validations.
In a project if we want we can carry out both server side validations and client
side validations.
Form based application using DynaActionForm :
We have to follow the following steps to develop form based apps
When we are working with DynaActionForm we no need to write setter() and
getter() methods in FormBean class. Internally it is implementing to DynaBean as
part of this interface it is providing the setter and getter() methods. DynaBean is
available in commons-beanutils.jar file.
Step1 : Get the Prototype. From the prototype identify the following three
elements
4. Identify the field names (Property name) for every field available in that
form.
5. Identify the form name (the name shouldn’t contain any spaces)
6. Identify the all the validations required on that form.
eg:

Step2: Develop the FormBean class based on DynaActionForm


What is FormBean class?
A class which is a subclass of org.apache.struts.action.ActionForm directly or
indirectly
Developing ProductFB class :
in formbean class override the reset() and validate() methods as shown below.
To store the data into a property we use setter() method. To get the data from
property we use getter().
Syntax: void set(String propertyName, Object value)
Object get(String propertyName)
Step3: configure the FormBean class in struts configuration file
4. copy all the formbean classes into classes folder.
5. provide all the error messages in properties files and configure them in
struts configuration file.

6. configure the Formbean class in sturts configuration file in <form-beans>


tag
Step4: Develop the input form or form view
The following form responsible to display the form as like prototype which uses
html tag library.

Step5: Develop an action class which is responsible to capture the data and store
it database server.
The struts internal code is responsible to create FormBean object and capture the
data and store it in FormBean object. This FormBean object supplied to
parameter to execute () method.
In the execute() method from the actonform object we get the data and store in
database server.
Step6: Configure the action class in struts configuration file

Step7: develop a success form (success view).


This is responsible to display success message to the user.

Deploy the project and test it. Once we have deployed the above project we have
to start testing the project from the jsp (productForm.jsp).
PlugIns:

Plugin is a piece of software. We can integrate plugin software with any other
software. Once if you integrate a plugin software with any other software the
capability of existing software will be increased.

By using IDE’s like eclipse we can’t perform the operations like developing AWT
and Swing application quickly. If we want eclipse IDE to carryout AWT and swings
we need to download a plugin and add the plugin to eclipse software.

We can use a plugin visual editor to develop AWT and swing applications in
eclipse IDE. The advantage of this approach is we can finish the work quickly
when we compared with manual work.

To work with hibernate in eclipse IDE we have to integrate JBossTools Plugin with
eclipse ide.

There are multiple ways are available to integrate the plugins with eclipse ide.

1. Download the plugin, Extract the contents of plugin and place them in
eclipse folder.
2. We can directly install the plugin in eclipse software .

Help--- Install New software ------> add ---- Provide plugin name and url

and click on ok.

1. Know your Eclipse & JBoss Tools version to download

First, you have to find out the correct version of Hibernate/JBoss tool for your Eclipse IDE. Go
here – http://www.jboss.org/tools/download for the available combination version to download.

For example,

1. If you are using Eclipse 3.6 / Helios , download JBoss Tools 3.2
2. If you are using Eclipse 3.5 / Galileo, download JBoss Tools 3.1

2. Eclipse update site for JBoss Tools

Point to your correct version, right click to copy the Eclipse update site for JBoss tools. For
Eclipse 3.6, the URL is ” http://download.jboss.org/jbosstools/updates/stable/helios/ ”
3. Install It

In Eclipse IDE, menu bar, select “Help” >> “Install New Software …” , put the Eclipse update
site URL.

Type “hibernate” in the filter box, to list down the necessary components for Hibernate tools.
Select all the “Hibernate Tools” components and click next to download.
Warning
Do not select all components, it will take much longer time download many unnecessary components.
You want Hibernate tools only, not others.

4. Restart Eclipse

After the download progress is completed, restart Eclipse to take effect.

5. Verification

If Hibernate tools is installed properly, you are able to see the “Hibernate Perspective” in
“Windows” >> “Open Perspective” >> “Others“.
Done.
In Struts we can develop our own plugins and we can integrate.

Procedure to use plugins struts:

1. Develop a plugin class


2. Configure a plugin class into struts configuration file

What is plugin class?

A class which provides the implementation of plugin interface is called as Plugin


class.

Developing a plugin class:

public class TestPlugIn implements PlugIn {


public void init(ActionServlet servlet, ModuleConfig config){
System.out.println("Init() is called");
}
public void destroy(){
System.out.println("destroy() is called");
}
}
2) configuring that in struts configuration file.
we can supply property to the <plug-in> tag . To do that in the plug-in class we
have to supply a property and we need to supply the value to it.

//read the contentes of configuration file

public class TestPlugIn implements PlugIn {

String fileName;

public void setFileName(String fileName){

this.fileName= fileName;

public String getFileName(){

return fileName;

public void init(ActionServlet servlet, ModuleConfig config){

System.out.println("Reading the configuration from " + fileName);

ServletContext application = servlet.getServletContext();

application.setAttribute("fileName", fileName);

public void destroy(){

fileName = null;

System.out.println("removing contents from jvm memory");

}
We have to configure the Plugin class in struts configuration file.

When struts 1.0 is released they have not taken care of performing validations. In
struts 1.1 they have provided the code to take care of validations. But the Struts
guys are released the software in the form of Plugin. The advantage of this we can
integrate this software with any other software.

From Struts 1.1 onwards apache guys itself has integrating validator plugin and
releasing Struts software we need to use validator plugin directly in our project.

Form based application using DynaValidatorForm :


we have to follow the following steps to develop form based apps:
When we are working with DynaValidatorForm we no need to write setter() and
getter() methods in FormBean class. Internally it is implementing to DynaBean as
part of this interface it is providing the setter and getter() methods. DynaBean is
available in commons-beanutils.jar file.
Step1 : Get the Prototype. From the prototype identify the following three
elements
7. Identify the field names (Property name) for every field available in that
form.
8. Identify the form name (the name shouldn’t contain any spaces)
9. Identify the all the validations required on that form.
eg:

Validations to carry out the above form:


1. All fields are mandatory
2. UserName must be minimum of 5 characters
3. Password and retype password must be same
4. Dob must be date format
5. age must be numeric
6. age must be >= 21 and <= 30
Step2: Develop the FormBean class based on DynaValidatorForm
Developing UserRegistrationFB class :
We no need to write any thing in UserRegistrationFB class. this is because setter
and getter() methods are inherited from DynaBean and validate() inherited from
DynaValidatorForm.
In DynaValidatorForm they have override a validate() to take care of validations.
public class UserRegistrationFB extends DynaValidatorForm {
}

Step3: configure the FormBean class in struts configuration file


1. copy the FormBean classes into classes folder.
2. configure the FormBean class in struts configuration file in <form-
beans> tag
Step4: Develop the input form or form view
The following form responsible to display the form as like prototype which uses
html tag library.

Step5: Develop an action class which is responsible to capture the data and store
it database server.
The struts internal code is responsible to create FormBean object and capture the
data and store it in FormBean object. This formbean object supplied to
parameter to execute() method .
In the execute() method from the actonform object we get the data and store in
database server.
Step6: Configure the action class in struts configuration file

Step7: develop a success form (success view).


This is responsible to display success message to the user.

Deploy the project and test it. Once we have deploy the above project we have to
start testing the project from the jsp (UserRegister.jsp).
We have to configure the all validations in validation.xml file as follows
Validator Plugin takes care of some predefined validations only. These are the
common validations which are available across multiple projects.

Instead of we develop the code to take care of validations struts guys developed
the code to take care of validations. All these code is available inside common-
validator.jar.

Apache guys have developed some predefined classes to take care of validations.

Every validator is mapped with an error key. These error keys are configured in
default properties file (MessageResources.properties).

eg: required----errors.required

The following are some of the validators and corresponding error codes:-

email -----errors.email

minlength -----errors.minlength

maxlength ----errors.maxlength

date ----errors.date

All these validators are configured in validation-rules.xml. This xml file is available
in struts-core.jar.
The following is an example of validation-rule.xml

we can find all these validators in the documentation.

To use predefined validations we must configure all the validations in


validation.xml file.

When we submit the form it will execute validate() of DynaValidatorForm.

The internal code of () of DynaValidatorForm validate () read the contents from


validation.xml and perform the validations.

<bean:message>

By using <bean:message > tag we can read the value of Configurable


messages(Which have parameters in that message ) from properties file.

eg: errors.maxlength={0} can not be greater than {1} characters.

<bean:message key=” errors.maxlength” />

when we run above program it will display the message as “null can not be
greater than null characters.”

But we want to replace parameter with a value like Age and 5.


To do that we use an attribute arg .

<bean:message arg0=”UserName” arg1=”10” key=” errors.maxlength” />

when we run above program it will display the message as “UserName can not be
greater than 10 characters.”

In the above example arg0 is used to replace parameter value with UserName
and arg1 is used to replace parameter value with 10.

When we configuring validations we have to check what is the errorcode return


by that Validator. we need to get the Configurable message for that validator. If
message contains parameter we have to supply the value to it by using <arg > tag

for Eg: we are using required validator. This validator will return the
errors.required error key. So we need to get the message for errors.required key
from the properties file that is “{0} is required”. This message contains a
parameter {0} . So we have to supply the value to parameter {0} by using <arg>
tag

<arg name=”” postion=”0” key=”” resource=”” />

<arg> tag is taking four attributes as shown above tag.

1) position :
This attribute indicates to which parameter number we are supplying the
values. If we are not supply these attribute by default it will takes the value
as zero. Afterwards it will increment by one.

Eg: <arg postion=”0” key=”User Name” resource=”false” />

(or)

<arg key=”User Name” resource=”false” />

2) key :
This attribute is dependent on resource attribute. The key attribute value is
supply as input to parameter.
3) resource :

when resource=”false” the key attribute value is supply as input to


parameter.

eg: <arg key=”User Name” resource=”false” />


for above tag it will display as
User Name is required

when resource=”true” It takes the key attribute value and check whether
the key value is specified in properties file or not. If key is not configured in
Properties file it returns a null value. If it is configured it get the value of it
and display to the client.

eg: <arg key=”User Name” resource=”true” />

For above tag it will check in properties file for UserName key. If it is there
it will get the value of that and display to the user.

User Name is required

otherwise it displays null is required.

4) name :
We can supply name attribute to <arg> tag. This name indicates to which
validator the argument value has to be supplied.

According to the above configuration the first <arg> tag is used by required
validator. and second <arg> tag is used by minlength validator.
Note: If we don’t specify the name attribute by default the <arg> is applicable to
all validators. i.e above first <arg> tag is applicable to all validators

By default the error groupName is same as propertyName in DynaValidatorForm.


we use these groupNames to display the error messages at specific location.

eg: <html:errors property=”userName” />

If we supply a validator which is not available in predefined list it will throw an


Exception saying: validatorException : no validator found

Different validators uses different variables we can find the all variables in
manual. We can configure the variables in validation.xml as shown below.

By default date validator uses a class java.text.SimpleDateFormat. When ever the


object is created to this class it uses month-date-year format. If we would like to
change the format we have to supply the value based on requirement. To supply
our own date format we are using a variable datePattern.

If we want the date pattern which is used in xml file and datePattern enrered by
the user must be same, in this scenario we use another variable
datePatternStrict. When we use datePatternStrict it will verify the no.of
characters which we entered.
The disadvantage of above configuration is when ever customer ask us to change
minlength we have to do in two places. Because this we get maintainance related
problems. To resolve this can define constant in global as shown in below

To use the above constant variable in our program we use ELExpressions as


shown below.
Standard Built In Validations

Validator ships with a set of pre-defined validators, as follows:

required - mandatory field validation. Has no variables.

<field property="name" depends="required">


<arg position="0" key="customer.name"/>
</field>

validwhen - validator for checking one field against another.

minlength - validate input data isn't less than a specified minimum length. Requires a minlength
variable.

<field property="name" depends="required,minlength">


<arg position="0" key="customer.name"/>
<arg position="1" name="minlength" key="${var:minlength}"
resource="false"/>
<var><var-name>minlength</var-name><var-value>3</var-value></var>
</field>

maxlength - validate input data doesn't exceed a specified maximum length. Requires a maxlength
variable.

<field property="name" depends="required,maxlength">


<arg position="0" key="customer.name"/>
<arg position="1" name="maxlength" key="${var:maxlength}"
resource="false"/>
<var><var-name>maxlength</var-name><var-value>30</var-value></var>
</field>

mask - validate format according to a regular expression. Requires a mask variable to specify the regular
expression. Since version 1.1, the regular expression must start with a ^ and end with a $ (see example
below).

<field property="name" depends="required,mask">


<msg name="mask" key="registrationForm.lastname.maskmsg"/>
<arg position="0" key="registration.name"/>
<var><var-name>mask</var-name><var-value>^[a-zA-Z]*$</var-value></var>
</field>

byte - validates that a field can be converted to a Byte.

<field property="age" depends="byte">


<arg position="0" key="employee.age"/>
</field>

short - validates that a field can be converted to a Short.

<field property="productnumber" depends="short">


<arg position="0" key="order.prodno"/>
</field>

integer - validates that a field can be converted to an Integer.

<field property="ordernumber" depends="integer">


<arg position="0" key="order.number"/>
</field>

long - validates that a field can be converted to a Long.

<field property="ordernumber" depends="long">


<arg position="0" key="order.number"/>
</field>

float - validates that a field can be converted to a Float.

<field property="amount" depends="float">


<arg position="0" key="sale.amount"/>
</field>

double - validates that a field can be converted to a Double.

<field property="amount" depends="double">


<arg position="0" key="sale.amount"/>
</field>

date - validates that a field can be converted to a Date. This validator uses
java.text.SimpleDateFormat to parse the date and optionally either a datePattern or
datePatternStrict variable can be used. If no pattern is specified the default short date format is
assumed. The difference between using the datePatternStrict and datePattern variables is that
datePatternStrict checks additionally that the input data is the same length as the pattern specified
(so for example 1/1/2004 would fail with a pattern of MM/dd/yyyy ).

<field property="saledate" depends="required,date">


<arg position="0" key="myForm.saledate"/>
<var><var-name>datePattern</var-name><var-value>MM/dd/yyyy</var-
value></var>
</field>
<field property="saledate" depends="required,date">
<arg position="0" key="sale.orderdate"/>
<var><var-name>datePatternStrict</var-name><var-value>MM/dd/yyyy</var-
value></var>
</field>

range - validate number range.

Deprecated, use intRange, longRange, floatRange


or doubleRange.

intRange - validates that an integer field is within a specified range. Requires min and max variables to
specify the range. This validator depends on the integer validator which must also be in the field's
depends attribute.

<field property="age" depends="required,integer,intRange">


<arg position="0" key="employee.age"/>
<arg position="1" name="intRange" key="${var:min}" resource="false"/>
<arg position="2" name="intRange" key="${var:max}" resource="false"/>
<var><var-name>min</var-name><var-value>18</var-value></var>
<var><var-name>max</var-name><var-value>65</var-value></var>
</field>

longRange - validates that a long field is within a specified range. Requires min and max variables to
specify the range. This validator depends on the long validator which must also be in the field's
depends attribute.

<field property="age" depends="required,long,longRange">


<arg position="0" key="employee.age"/>
<arg position="1" name="longRange" key="${var:min}" resource="false"/>
<arg position="2" name="longRange" key="${var:max}" resource="false"/>
<var><var-name>min</var-name><var-value>18</var-value></var>
<var><var-name>max</var-name><var-value>65</var-value></var>
</field>

floatRange - validates that a float field is within a specified range Requires min and max variables to
specify the range. This validator depends on the float validator which must also be in the field's
depends attribute.

<field property="ordervalue" depends="required,float,floatRange">


<arg position="0" key="order.value"/>
<arg position="1" name="floatRange" key="${var:min}" resource="false"/>
<arg position="2" name="floatRange" key="${var:max}" resource="false"/>
<var><var-name>min</var-name><var-value>100</var-value></var>
<var><var-name>max</var-name><var-value>4.99</var-value></var>
</field>
doubleRange - validates that a double field is within a specified range Requires min and max variables to
specify the range. This validator depends on the double validator which must also be in the field's
depends attribute.

<field property="ordervalue" depends="required,double,doubleRange">


<arg position="0" key="employee.age"/>
<arg position="1" name="doubleRange" key="${var:min}" resource="false"/>
<arg position="2" name="doubleRange" key="${var:max}" resource="false"/>
<var><var-name>min</var-name><var-value>100</var-value></var>
<var><var-name>max</var-name><var-value>4.99</var-value></var>
</field>

creditCard - validate credit card number format

<field property="name" depends="required, creditCard">


<arg position="0" key="customer.cardnumber"/>
</field>

email - validate email address format

<field property="customeremail" depends="email">


<arg position="0" key="customer.email"/>
</field>

url - validates url format. Has four optional variables ( allowallschemes , allow2slashes ,
nofragments and schemes ) which can be used to configure this validator.

allowallschemes specifies whether all schemes are allowed. Valid values are true or false (default is
false ). If this is set to true then the schemes variable is ignored.

allow2slashes specifies whether double '/' characters are allowed. Valid values are true or false
(default is false ).

nofragments specifies whether fragements are allowed. Valid values are true or false (default is
false - i.e. fragments are allowed).

schemes - use to specify a comma separated list of valid schemes. If not specified then the defaults are
used which are http , https and ftp .

<field property="custUrl" depends="url">


<arg position="0" key="customer.url"/>
</field>

<field property="custUrl" depends="url">


<arg position="0" key="customer.url"/>
<var>
<var-name>nofragments</var-name>
<var-value>true</var-value>
</var>
<var>
<var-name>schemes</var-name>
<var-value>http,https,telnet,file</var-value>
</var>
</field>

Constants/Variables
Global constants can be inside the global tags and FormSet/Locale constants can be created
in the formset tags. Constants are currently only replaced in the Field's property attribute, the
Field's var element value attribute, the Field's msg element key attribute, and Field's arg
element's key attribute. A Field's variables can also be substituted in the arg elements (ex:
${var:min}). The order of replacement is FormSet/Locale constants are replaced first, Global
constants second, and for the arg elements variables are replaced last.

<global>
<constant>
<constant-name>zip</constant-name>
<constant-value>^\d{5}(-\d{4})?$</constant-value>
</constant>
</global>

The var element under a field can be used to store variables for use by a pluggable validator.
These variables are available through the Field's getVar(String key) method.

<field property="integer" depends="required,integer,intRange">


<arg position="0" key="typeForm.integer.displayname"/>
<arg position="1" name="intRange" key="${var:min}" resource="false"/>
<arg position="2" name="intRange" key="${var:max}" resource="false"/>
<var>
<var-name>min</var-name>
<var-value>10</var-value>
</var>
<var>
<var-name>max</var-name>
<var-value>20</var-value>
</var>
</field>

Designing Complex Validations with validwhen

[Since Struts 1.2.0] A frequent requirement in validation design is to validate one field against
another (for example, if you have asked the user to type in a password twice for confirmation, to
make sure that the values match.) In addition, there are fields in a form that may only be required
if other fields have certain values. The validwhen validator is designed to handle these cases.
The validwhen validator takes a single var field, called test . The value of this var is a boolean
expression which must be true in order for the validation to success. The values which are
allowed in the expression are:

The token *this* , which contains the value of the field currently being tested
Other fields in the form referenced by field name, such as customerAge
The token null which will match against either null or an empty string
Single or double-quoted string literals.
Integer literals in decimal, hex or octal format

Using our own validator.xml

Instead of using validator.xml file for validations we can use our own xml file as
validator.xml. But we need to configure it in Struts configuration file.

Instead of using predefined validator_rules.xml file, we can use our own xml file
and we need to configure it in struts configuration file. As shown below file we
change the configuration in struts-config.xml

Here validation_test.xml file is our own validation file. Generally


validator_rules.xml file is available in struts-core.jar. But here we placed it in
WEB-INF folder.
Procedure to work with Custom Validators:
1. Develop a class with static method by supplying the standard parameters to
a method.

Creating Pluggable Validators

The methodParams attribute takes a comma separated list of class names. The
method attribute needs to have a signature complying with the above list. The list
can be comprised of any combination of the following:

java.lang.Object - Bean validation is being performed on.


org.apache.commons.validator.ValidatorAction - The current
ValidatorAction being performed.
org.apache.commons.validator.Field - Field object being validated.
org.apache.struts.action.ActionMessages - The errors object to add an
ActionMessage to if the validation fails.
javax.servlet.http.HttpServletRequest - Current request object.
javax.servlet.ServletContext - The application's ServletContext.
org.apache.commons.validator.Validator - The current
org.apache.commons.validator.Validator instance.
java.util.Locale - The Locale of the current user.
2) Copy the .class file into classes folder. Configure CustomValidator class in
validator-rules.xml by specifying a validator key(short name for this class)

3) Configure this validator-rules.xml file in struts-config xml file as shown


below. Make sure that validator-rules .xml file is available in WEB-INF folder.

4) Configure our own validator class in validator_test.xml file


Q) When we develop CustomValidator classes?

Ans: If there is a filed which is used across all the screens of project and
predefined validator is not available then we will use validator class.

Q) When we will override validate () method in the FormBean class?

Ans: If there is a validation which has to take care of only one field that validation
is carried out in validate () method. Then only we will override validate () to carry
out the validation.

eg: we have fields like password and retype password and we want check
whether both values are same or not . If values are different then we have to
display an error message on jsp.

When we override validate() method we need to make sure that we calls super
class validate() method. This is because the super class validate() takes care of
reading the contents from validation.xml and perform validations which are
configured as part of validation.xml. If we are not call the validate () method then
predefined validation’s can’t be carried out.

Eg:
Generating JavaScript using DynaValidatorForm :

By using DynaValidatorForm we can generate client side validations also.

To generate javascript in jsp we use the <html:javascript />

the mandatory attribute is formName . For formName attribute we have to


supply form name as input to that.

Eg: <html:javascript formName=”UserRegistrationForm ” />

when the above tag is evaluated it will generate a javaScript function whose
name validate+formName attribute value. eg: Here it will generate
validateUserRegistrationForm(form) in userRegistration.jsp

By default the DynaValidatorForm will not call the


validateUserRegistrationForm(form) method. We have to call that method
explicitly. We are using onsubmit event to call the above JavaScript function. as
shown below.

The DynaValidatorForm plugin can generate JavaScript only for predefined


validations. If we want to carry out our own validations by using JavaScript we
have to write our own JavaScript functions.

Apache guys has developed their own validations using JavaScript and placed
inside validator plugin.jar file. The validator plugin take the JavaScript form this
jar file and place the JavaScript in jsp whenever we use <html:javascript />
Whenever we use our own JavaScript function to carry out client side validations
from that also we can call the generated JavaScript function as shown below.

eg:

There are n no. of ways are there to develop FormBean classes. Some of them are

1. ActionForm 2.DynaActionForm 3. DynaValidatorForm

4. DynaValidatorActionsForm 5.ValidatorForm 6.ValidatorActionForm


We can use other ways of using FormBean classes like BeanValidatorForm,
LazyValidatorForm and etc.

Form based application using ValidatorForm :


When we working with validatorForm we no need to take care of the validations.
We have to provide setter () and getter methods for identified properties.eg:
public class SignupFB extends ValidatorForm {
String firstName;
String lastName;
//provide setter and getters for above properties }
The remaining procedure is same as above DynaValidatorForm.
Form based application using ValidatorActionForm :
When we working with validatorActionForm we no need to take care of the
validations. We have to provide setter() and getter methods for identified
properties.
public class SignupFB extends ValidatorActionForm {
String firstName;
String lastName;
//provide setter and getters for above properties
}
To compile above program we have to set the classpath to struts-extras.jar.
When we develop an application based on ValidatorActionForm, we have to
configure the validation.xml as follows.

In <form> tag for name attribute we have to supply the <action> tag path
attribute specified value. Otherwise validations will not carry out.
In DynaValidatorActionForm also we should specify the path of the resource to
name attribute in validator.xml as shown as above example.
In Struts ActionServlet, Action classes, FormBean classes acts as Controllers. It’s
not recommended to write business logic in Action classes or FormBean classes.
So we should not transfer the FormBean class to Model class.
Develop a complete Form Based application by using MVC2 architecture:

We have to capture the data from the above form and save that details in
database server. The following is flow of the Project.

To implement the above requirement we have to perform the following steps:-


Step1:- Develop a javaBean to write the business logic . The business logic is get
the form details and store those in DataBase server and send an email to register
mail id.
eg:

Step2:- Develop a FormBean class and configure that in Struts Configuration file.

In this program we don’t require to override the reset() and validate() methods.
that’s why we are not writing any FormBean class but we are using predefined
class DyanValidatorForm. configure that in struts-config.xml file
Step3:- Configure the validation in validations.xml file as shown below
Step4:- Develop an action to capture the data and call the methods of javaBean
and forward the request to Welcome.jsp

Configure the above classes in Struts configuration file

In the above project the java bean program is clubbed with busiess logic and Data
Access Logic. It’s always recommended to separate out the business logic and
Data Access Logic. To separate out the business logic and Data AccessLogic we use
DAO designPattern.
DAO DesignPattern:

DAO strands for Data Access object. DAO design pattern make sure that we
clearly separate out business logic and Data Access Logic.

In the DAO classes we provide the code to interact with the data base server only.
In this we will use jdbc or hibernate or any persistent technologies. So if any
change in Persistent code we will modify only Dao classes. It will not affect on any
other layer.

Develop the following form based application using mvc2 and DAO,DTO design
pattern
To implement the above project we have to perform the following steps:

DTO DesignPattern:

It resolves the problems of transferring the data from one component to another
component .In the above example we transfer the data like signup form details in
the form method parameters to JavaBeans from Controller. This is not
recommended approach because when ever any change in the parameter we
have to modify our program because of this we may face maintenance related
problems. Instead of passing each value as method parameter to javabean we will
create a DTO which contains instance variable and setter and getter methods and
we will supply this DTO as parameter to javabean. And it will call the DAO method
which takes the DTO as parameter. DTO will pass from Controller to DAO

Develop a project which uses MVC2 designpattern DAO and DTO designpatterns.

step1:- Create a DTO class which can hold the FormBean data. This class has store
the data of which enter by the user in the above shown form
step2:- Develop a DAO program. In this we write the only the code which is
responsible to interact with the database server. This DAO class component takes
the DTO object as parameter as shown below. This method is called by the
Controller as it shown in controller program. eg:

In above example we have a registerUser() method which is responsible to store


the user details in db. This method is returning Boolean value. If the data is
successfully registered then this method returns true otherwise it returns false.
We used this value in controller to forward the appropriate jsp.eg. If user data is
successfully registered then forward to success.jsp otherwise forward to
inputform.jsp

step3:- Develop a JavaBean which is responsible to get the data from Controller,
create an object to DAO class and call the methods of Dao. Usually in the
JavaBean we will write the business logic code.
Here We are calling the registerUser() method which is returning a value. we
storing that in isRegistered variable . If user details are stored then send a mail to
that email.

step4:- Develop FormBean class and Configure in struts configuration file.

In this example we no need to display default values to the form. That’s why we
are not overriding the reset() method. And we no need to take care the user
defined validation that means predefine validations are enough to carry out the
validations. So in this scenario we no need to develop the our own FormBean
class for that we will use predefined FormBean class. In this example we are using
DynaValidatorForm.

The following is configurations of DynaValidatorForm in struts configuration file.


step5:- Develop Action class and capture the data and create object to Javabean
and call the methods of Javabean as follow

If user data is successfully registered then forward to success.jsp otherwise


forward to inputform.jsp . In Action class we can handle the errors. The errors in
the Action class should be based on the return type of DAO and javabean
methods.
step6:- Develop an input form and successform.

VO Design Pattern: (Value Object)

VO design pattern is used retrieve the data from the DAO layer and send the data
to view View Component. this design pattern is used to get the values from
database server and store those values in Vo object. and transfer these vo object
to View component by adding it to Arraylist.

eg :searchRecords:
Develop the following form based application to search for the records and
display output to the client.

eg: searchRecords
The business logic is if user is entered any data in the pid field then it has to
display the corresponding record of product table from the database.If records
arenot available then display “No records found” . If user doesn’t entered any
data, view has to display the all records of Product table.

we use the design patterns like MVC2, DAO,DTO,VO design patterens.

Step1: - Develop the DTO class. which is responsible to hold the pid field details.
And transfer this dto to javabean from Contrller.

ex:
Step2:- Develop the VO class. This class responsibility is hold the product table
data.It contains instance variables and setter and getter methods. These instance
members based on the no of columns values we want store in VO object.This
class is instantiated by DAO class and represent each record in the form of an VO
object.

eg:

In this example we dealing with product table which contains only three columns
that’s why we are taking three fields in our VO class.
Step3: - Develop a DAO class which is responsible to represent the records in the
form Objects and add these to ArrayList object.

In above program we forming the query dynamically. represent each record in the
form SearchProductVO object. and store these objects to Arraylist.
searchRecords() method is taking the DTO as parameter to it. and returning the
Arraylist object.
Step4:- Develop the javabean (Model ) class. It has to call the Dao methods .

Model class responsibility is create the object to javabean and call the
searchRecords(). return this arraylist object to controller. If we want to write any
other business logic we will write in this class only.

Step5:- Develop the formbean class and configure that in struts configuration
file. In this example we are not developing any formbean class just we are
configuring the predefined Formbean class as shown below

Step6:- Develop the Action class and configure that in struts configuration. The
action class responsibility is capture the data and stored it DTO object and call
the javabean methods and get the arraylist object and store it in request scope.
Step6:- Develop the Input form(search.jsp)

Step7:- Develop the success form (display.jsp) which is responsible to get the
arrayList object from that display the product details to user.

Hibernate integration in Struts:

The following are some of ways to integrate hibernate in struts:


1. write hibernate code in Action class (not recommended)
2. Based on Developing our own Hibernate plugin
3. By using SingleTon Designpattern and hibernate Template design
pattern

Procedure to use hibernate in struts:

1. copy all the hibernate related jar files into struts project lib folder.
2. coy hibernate configuration file and hbm (mapping) files into
classes folder.

write hibernate code in Action class:

When we are writing hibernate code in Action class , for every request
the action class execute() method will execute. so every time it is
executing the configure() and buildSessionFactiory() methods. But it is
not recommended to call these methods every time. In a project life
time we have to call these methods only once. Because these methods
will take more amount of time to execute.
But it is not recommended to write the business logic in Controller and
not recommended call hibernate configure() and buildSessionFactiory(
) methods. For that we have to call these methods only once. This thing
can be achieved by using plugins which will execute only once that is at
time of deploying the project.

Based on Developing our own Hibernate plugin:

Procedure to use hibernate in struts:

1. copy all the hibernate related jar files into struts project lib folder.
2. coy hibernate configuration file and hbm (mapping) files into
classes folder.
3. Develop a hibernate plugin class based on plugin interface
4. Configure the HibernatePlugin class in struts configuration file
<plug-in className=” HibernatePlugin” />
5. Develop an action class to get the SessionFactory object from the
application scope and execute the query.

Develop a hibernate plugin class based on plugin interface


Develop an action class to get the SessionFactory

we shouldn’t use these two approaches. This is because we are writing


business logic and DataAccessLogic in Action class execute() method.

note: we should write the hibernate code only in DAO layer


Develop the following form based application to search for the records and
display output to the client. we must use MVC2,DAO,DTO,VO,SingleTon
designpatterns and Hibernate Template designpatterns .

searchRecords

we have follow the following steps:

step1 and step2 are same as above searchRecords example


Step3: - Develop a DAO class which is responsible to represent the records in the
form Objects and add these to ArrayList object. and return arrayList to model.

The following is an example of writing hibernate code in DAO class

But here we are calling configure() and buildSessionFactiory() every time.


to overcome this problem we using SingleTon design pattern

SingleTon design pattern:

If we want carry out any work only once we can use SingleTon design
pattern. This design pattern will make sure that this work will happens
only once. for that we will use static variable and static blocks. This is
because for these members memory will be allocated only once at time
of jvm loading the class into jvm’s memory.

we declare the construtctor as private because no one is allowed to


create an object this class. we can call the methods of this call directly
by using the class name.
Template Design Pattern:

When we take any project we try to perform the operations like insert,
update, delete and retrieve records. Instead of writing the code
repeatedly we develop a template designpattern. This design pattern
will help us in removing the redundant code of hibernate. Because of
this reason we call it as HibernateTemplate designpattern.(eg: instead
of writing accno, name,date etc.. in our own style daily we will follow
one template. that is easy to write the form)

The following is example of HibernateTemplate design pattern


Step3: - Develop a DAO class which is responsible to represent the records in the
form Objects and add these to ArrayList object. and return arrayList to model.
Step4:- Develop the javabean (Model ) class. It has to call the Dao methods .

Model class responsibility is create the object to javabean and call the
searchRecords(). return this arraylist object to controller. If we want to write any
other business logic we will write in this class only.

Step5:- Develop the formbean class and configure that in struts configuration
file. In this example we are not developing any formbean class just we are
configuring the predefined Formbean class as shown below

Step6:- Develop the Action class and configure that in struts configuration. The
action class responsibility is capture the data and stored it DTO object and call
the javabean methods and get the arraylist object and store it in request scope.
Step6:- Develop the Input form(search.jsp)

Step7:- Develop the success form (display.jsp) which is responsible to get the
arrayList object from that display the product details to user.
Action Chaining:
Executing the multiple actions in a single request is called as Action Chaining. For
example we have developed two action classes, one class has to check whether
user is logged in or not then insert the record in database server. Another class
also has to check the user is logged in or not then delete the record.

In the above action classes we are trying to check whether user is logged in or
not. But this code is provided in multiple Action classes. when ever we want
change the we have to change it multiple classes.Because of this we may get
project maintainance problems. To resolve these problems we need to make sure
that one Action class has to carry out only ont task. By using this we can remove
the redundancy code in project.

 We can configure one action class with different path values.


eg: <action path=”insert” type=”InsertAction” />
<action path=”ins” type=”InsertAction” /
From the above code we have understand we can use either /insert.do or

/ins.do to execute the InsertAction


 An ActionForward can forward the request to a jsp or another action class.
If we want to forward the request to another action class we have to use
that action class path in path attribute as shown below

The above ActionForward is forwarding the request to a jsp as well as


another class also.

one Action class has to carry out only ont task. To get the above requirement we
are writing 3 action classes i.e UserCheckAction , InsertAction, DeleteAction

UsercheckAction has to check whether user logged in or not. InsertAction has to


insert the record and DeleteAction has to delete the records

eg:
To achieve Action chaining we have to configure action classes in struts
configuration file.

for example when client send the request to server with /insert.do first
UsercheckAction has to execute then InsertAction has to execute.

when client send the request the server with /delete.do First UserccheckAction
has to check whether user is there are not then ActionTwo has to execute to
delete the record.

for that we are configuring the action classes as shown below.


What is local forward?

A forward which is specific to an Action class is called as local forward.

This forward object can be access by only ActionOne class in struts configuration
file

What is global forward?

A forward object which can be accessible by all the actions are called as global
forwards.

This forward object can be access by any of Action class in struts configuration file

Global Exceptions:

An Exception is a runtime error which disturbs the flow of execution of the


program. Exceptions are two types: 1) Checked Exceptions 2) Unchecked
Exceptions

When a program throws checked exceptions we have to handle. We can do that


in two ways

1. Maintain try catch in the program itself.

2. Use throws keyword.


we have developed two action classes, ActionOne and ActionTwo . ActionOne
class is trying to load a class which is not available in that folder. ActionTwo class
is trying to load a file which is not available in that folder.

When the client sends the request to above two actions they are throwing an
exception to Actionservlet service() method. Actionservlet service() checks
exception is handled here or not. As exceptions are not handled in that it will
throw an exception to server. Server throws an Exception to user directly. But it is
not recommended to throw an exception to user instead of that we will display a
message to user.

when ever an FileNotFoundException is raised errors.jsp will be executed and the


output sent to client.
Predefine Actions: (Built-in Actions)

Struts guys has given some predefined Action classes. These Action classes are
available in org.apache.struts.actions. package. The following are some of the
predefined actions

1. BaseAction
2. ForwardAction
3. IncludeAction
4. DispatchAction
5. LookupDispatchAction
6. SwitchAction
7. MappingDispatchAction

To work with predefined actions we must use Struts-extras.jar file. When we


developing action classes based on these classes we must copied the struts-
extras.jar into project lib folder.

The problem in struts1.x is using servlet (ActionServlet) as a controller. This is


because the url pattern is configured as *.do . So which request ends with .do
that requests only handled by the ActionServlet.

When we using jsp’s in struts1.x directly jsp are getting executed. This is against
to the rules of MVC2 architecture . Jsp’s also must access through controller only.

ForwardAction :

By using ForwardAction we can forward the request to jsp through controller. If


we doesn’t use ForwardAction we have to develop so many empty action classes
which forwards the request to one -one jsp. Because of this reason Maintenance
of the project becomes difficult. To resolve this problem we use ForwardAction.
The following the configuration of Forwardaction in configuration file.

If want to execute the home.jsp we have to send the request to server as


/home.do. Then it ForwardAction execute() method will be executed. as part of
that they will get the parameter attribute value as like this

According the SunMicroSystems documentation it is not recommended to


develop a java program with more than 2000 lines of code as well as not
recommended to develop a program with very less amount of java code also.

DispatchAction :

DispatchAction make sure that it club multiple action classes into a single action
class. If we want to develop multiple formbased applications which does the
relevant work we can use DispatchAction. for eg:
If we want to develop the above four forms we can club four action classes into a
single Action by using DispatchAction.

Develop an action class with our own methods which takes only four parameters
as like execute() method. and these parameter order should be same as in
execute(). and return type must be ActionForward object only.
step 2:

Configure above action class into struts configuration file by specifying parameter
as attribute. The parameter attribute can be any thing. eg:

Step 3:

To execute the specific method of an Action class we use the following url
mname as query string.

http://localhost:8000/preactions/store.do?mname=storeProduct

To work with DispatchAction end user will not remember the url’s . In the jsp’s for
action attribute value we specify the query String.
IncludeAction is much like ForwardAction except that the resulting resource is
included in the HTTP response instead of being forwarded to. It is rarely used. Its
only significant use is to integrate legacy applications with Struts transparently.
Consider a web site that aggregates information from disparate sources – some of
which are non-Struts. The JSP for such a web site consists of <jsp:include>s to
include different resources. One of such <jsp:include> that might be as follows:

<jsp:include page=”/xoom/LegacyServletA” />

It is very clear from the value of the page attribute that it is a non-Struts resource.
Wouldn’t it be better to have a <jsp:include> that pretends as if the resource
exists in the current Struts application? It would be ideal if the page include
looked as follows:

<jsp:include page=”/App1/legacyA.do” />

The /legacyA.do cannot be a ForwardAction because it would perform a HTTP


Forward to the above resource instead of including the resource in the HTTP
response. Since the HTTP Response OutputStream closes (The J2EE jargon for this
is the response has been committed) after HTTP Forward, the servlet container
cannot process the rest of the JSP and include its response in the OutputStream.
Consequently it throws a IllegalStateException with a message that “Response is
already committed”. IncludeAction addresses this problem. Instead of forwarding
to the specified resource, it includes the resource in the current response.
Consequently the output of the LegacyServletA is displayed in the same HTML as
that of the Struts application. You have to add the following ActionMapping in the
Struts Config file:

<action path=”/legacyA”
parameter=”/xoom/LegacyServletA”
type=”org.apache.struts.actions.IncludeAction” />

The parameter attribute indicates the actual resource that has to be included in
the response. As mentioned earlier, the use of IncludeAction is limited to
including responses from existing Servlet in the current page. This requires the
use of <jsp:include> in the page. If you web application is aggregating response
from legacy servlet applications, portlets seems to be the way to go. Portlet API –
JSR 168 has been finalized and it is matter of time before you can develop
standardized portals aggregating contents from disparate web applications. Tiles
framework is the way to go if you are on a short-term project that wants to
aggregate information now (From different applications or may be from various
Actions in the same Struts application). Tiles provides a robust alternative to the
primitive <jsp:include>. Chapter 7 provides an in-depth coverage of Tiles in
conjunction with Struts.
We say that ActionServlet is the backbone of the struts application but actually it just receives the
request and invoke RequestProcessor process() method and this RequestProcessor processes all
aspects of the request.
If the above is true , then RequestProcessor should be the heart of struts application or do we
consider {ActionServlet + Requestprocessor} as a single unit when we say "ActionServlet is the
backbone of the struts application".

1. ActionServlet receives the request.


2. The doPost() or doGet() methods receive a request and invoke the process() method.

3. The process() method gets the current RequestProcessor and invokes the RequestProcessor.
process() method

4.The RequestProcessor.process() method is where the current request is actually serviced. This
method retrieves, from the struts-config.xml file, the <action> element that matches the path
submitted on the request. It does this by matching the path passed in the <html:form /> tag's action
element to the <action> element with the same path value

5. When the RequestProcessor.process() method has a matching <action>, it looks for a <form-
bean> entry that has a name attribute that matches the <action> element's name attribute.

6. When the RequestProcessor.process() method knows the fully qualified name of the FormBean, it
creates or retrieves a pooled instance of the ActionForm named by the <form-bean> element's type
attribute and populates its data members with the values submitted on the request

7. After the ActionForm's data members are populated, the RequestProcessor.process() method calls
the ActionForm.validate() method, which checks the validity of the submitted values.

8. At this point, the RequestProcessor.process() method knows all that it needs to know and it is time
to actually service the request. It does this by retrieving the fully qualified name of the Action class
from the <action> element's type attribute, creating or retrieving the named class, and calling the
Action.execute() method

9. When the Action class returns from its processing, its execute() method returns an ActionForward
object that is used to determine the target of this transaction. The RequestProcessor.process()
method resumes control, and the request is then forwarded to the determined target.

10. At this point, the ActionServlet instance has completed its processing for this request and is ready
to service future requests.

You might also like