Struts:-: Struts Framework Is A Piece of Software Which Contains The Solutions To
Struts:-: Struts Framework Is A Piece of Software Which Contains The Solutions To
Struts:-: Struts Framework Is A Piece of Software Which Contains The Solutions To
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 :
The following are the advantages of Frameworks like Struts and spring:-.
Every Company uses their own frameworks to develop the projects .all these
frameworks internally uses the other frameworks.
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.
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
1. Server will read the contents from web.xml file and store the information
in jvm’s memory.
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.
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.
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.
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.
name attribute is used as logical name to identity a particular action. This name
attributed used mainly in developing form based application.
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:
For the above code it returns ActionForward object for af1 and af2. For af3 it
returns a null value.
The following steps are carried out when client sends the request to Action class
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.
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.
In a properties file we supply the data in the form of key and value.
eg:
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 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:
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
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
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.
out.println(objLocale);
%>
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:
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.
</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
<struts-config>
<message-resources parameter="resone" />
<message-resources parameter="restwo" />
</struts-config>
eg:
application.setAttribute(Globals.MESSAGE_KEY, objPropertyMessageResources1);
application.setAttribute(Globals.MESSAGE_KEY, objPropertyMessageResources2);
The logic tab library contains set of tags which are used to check the logical
conditions. for example Present, notpresent, greaterthan and lessthan etc .
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.
Step3: Configure Action class into struts configuration file. As shown below
step3: execute() method create ActionErrors object and add the ActionMessage
object’s to that. ActionMessage is taking the error key as parameter.
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>
</html:messages>
1. *.do
2. /do/*
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.
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
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:
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.
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:
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
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
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
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
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.
String fileName;
this.fileName= fileName;
return fileName;
application.setAttribute("fileName", fileName);
fileName = null;
}
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.
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
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
<bean:message>
when we run above program it will display the message as “null can not be
greater than null characters.”
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.
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
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.
(or)
2) key :
This attribute is dependent on resource attribute. The key attribute value is
supply as input to parameter.
3) resource :
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.
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.
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
Different validators uses different variables we can find the all variables in
manual. We can configure the variables in validation.xml as shown below.
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
minlength - validate input data isn't less than a specified minimum length. Requires a minlength
variable.
maxlength - validate input data doesn't exceed a specified maximum length. Requires a maxlength
variable.
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).
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 ).
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.
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.
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.
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 .
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.
[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
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
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:
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.
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 :
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
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
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.
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
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:
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.
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.
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.
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.
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.
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.
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.
searchRecords
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.
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)
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.
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
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.
This forward object can be access by only ActionOne class in struts configuration
file
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:
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.
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
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 :
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:
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:
<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".
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.