Вы находитесь на странице: 1из 261

RoseIndia Struts 2 Tutorial and Online free training helps you learn new elegant Struts 2

Framework with examples. Struts 2 is very elegant and flexible front ontroller framework based
on many standard tehnologies like !ava Filters" !ava #eans" Resoure#undles" $%& et.
Struts 2 Training! Get Trained Now!!!
1. Struts 2 Features
It is very extensible as eah lass of the framework is based on an Interfae and all the
base lasses are given an extra appliation and even you an add your own.

2. Struts 2 History
'pahe Struts is an open(soure framework that is used for developing !ava web
appliation. Originally developed by the programmer and author )raig R. %)lanahan
this was later taken over by the 'pahe Software Foundation in 2**2.

3. Struts 2 Architecture
Struts and webwork has +oined together to develop the Struts 2 Framework. Struts 2
Framework is very extensible and elegant for the development of enterprise web
appliation of any si,e. In this setion we are going to explain you the arhiteture of
Struts 2 Framework.
4. Why Struts 2
The new version Struts 2.* is a ombination of the Sturts ation framework and
-ebwork. 'ording to the Struts 2.*.. release announement" some key features are/
5. Struts 1.x Vs Struts 2.x
In the following setion" we are going to ompare the various features between the two
frameworks. Struts 2.x is very simple in omparison to the struts ..x" few of its
exelling features are/

6. 0ownloading and Installing Struts 2
In this setion we will download and install the Struts 2.* on the latest version of Tomat
ontainer. -e will first download tomat and onfigure it as our development server.

Struts 2 Hello World Alication
7. !reating the de"elo#ent directory Structure
In this setion we will reate diretory struture of our Struts 2 1ello -orld appliation
based on Struts 2 framework. Our Struts 2 1ello -orld appliation is your first step
towards developing appliations based on Struts 2 framework.

8. Writing $s% $a"a and !on&iguration &iles
In this setion we will write !S2" !ava and re3uired onfiguration files for our Struts 2
1ello -orld appliation. 4ow in struts 2 struts.x#l is used to onfigure the appliations.
-e will also deploy and test the appliation.

9. Struts 2 x#l con&iguration &ile
In this setion we will introdue you with the struts.xml file. This setion explains you
how best you an use the struts.xml file for you big pro+ets.

Struts 2 Actions
10. Struts 2 'tions 5xample
-hen a lient re3uest mathes the ation6s name" the framework uses the mapping from
struts.x#l file to proess the re3uest.

11. Struts 2 Actions 'ntroduction
-hen a lient re3uest mathes the ation6s name" the framework uses the mapping from
struts.x#l file to proess the re3uest. The mapping to an ation is usually generated by a
Struts Tag.

12. Struts 2 (edirect Action
In this setion" you will get familiar with struts 2 Rediret ation and learn to use it in the
struts 2 appliation.

Struts 2 )ogin Alication
13. *e"eloing )ogin Alication in Struts 2
In this setion we are going to develop login appliation based on Struts 2 Framework.
Our urrent login appliation does not validate the user against the database.

14. Adding Validation to Struts 2 )ogin Alication
In this setion we will write the ode to validate the login appliation. 'fter ompleting
this setion you will be able to write validations for your Struts 2 pro+ets.

15. (unning and testing alication
In this setion we will run the example on Tomat 7.* server and hek how it works.

16. !lient Side Validation in Struts 2 )ogin Alication
In this setion we will see how to write ode that will generate !ava Sript ode for lient
side validation. In the last setion we developed &ogin(validator.xml onfiguration file
for defining the server side validation.

17. Validations using Struts 2 Annotations
In this setion we are going to validate our login appliation using 'nnotations in 'tion
lass. Our urrent login appliation does not validate the user against the database.

+ore Struts Validator ,xa#les
8ser input validations are an integral part of any web appliation. -ith the release of
Struts 2" validation are now muh easy and robust. Struts 2 support '+ax based and even
server side validations.

18. )ogin-)ogout With Session
In this setion" we are going to develop a login9logout appliation with session. This
appliation heks the user authentiation. -henever you run" it takes a user id and a
password :#oth the user id and password is ;ad#in;< it displays the welome page" when
both fields are orretly filled.
19. !onnecting to +yS.) *ata/ase in Struts 2 0Struts 2 +yS.)1
In this setion" =ou will learn to onnet the +yS.) database with the struts 2
appliation.
20. (ich ,ditor ,xa#le
In this setion" you will learn how to reate pagination in struts 2.
21. Validate TextArea
In this setion" you will learn how to validate your text area in struts 2. ' text area
ontains . to 2>* haraters. It ann6t support ;null; value.

Struts 2 Tags
22. Struts Tags
In this setion we will introdue you with the tags provided along with Struts 2
framework. It is neessary to understand all the tags provided along with Struts 2
framework.

Struts 2 Tags ,xa#les

23. Struts 2 Tags ,xa#les 0Generic Tags1
Struts 2 tags tutorials and examples.
24. !ontrol Tags2'& - ,lse '& - ,lse
In this setion we are going to disuss the various ontrol tags : The )ontrol Tags are
used for flow ontrol suh as if" else and iterate.<.
25. Aend Tag 0!ontrol Tags1 ,xa#le
In this setion" we are going to desribe the append tag. The append tag is a generi tag
that is used to merge multiple iterators into one iterator.
26. Generator Tag 0!ontrol Tags1 ,xa#le
In this setion" we are going to desribe the generator tag. The generator tag is a generi
tag that is used to generate iterators based on different attri/utes passed.
27. Generator Tag 0!ontrol Tags1 3sing !ount Attri/utes
In this setion" we are going to desribe the generator tag using the count attributes.
28. Generator Tag 0!ontrol Tags1 3sing an 'terator with 'd Attri/utes
In this setion" we are going to desribe the generator tag using the id attributes.
29. 'terator Tag 0!ontrol Tags1 ,xa#le
In this setion" we are going to desribe the Iterator tag. Iterator tag is used to iterate over
a value. 'n iterable value an be either of/ 4a"a.util.!ollection or 4a"a.util.'terator.
30. +erge Tag 0!ontrol Tags1 ,xa#le
In this setion" we are going to desribe the merge tag. The merge tag is a generi tag that
is used to merge iterators. The suessive all to the merge iterator auses eah merge
iterator to have a hane to expose its elements" subse3uently next all allows the next
iterator to expose its element.
31. Su/set Tag 0!ontrol Tags1 ,xa#le
In this setion" we are going to desribe the subset tag. The subset tag is a generi tag
that takes an iterator and outputs a subset of it. It delegates to
org.apahe.struts2.util.SubsetIteratorFilter internally to perform the subset funtionality.
32. Su/set Tag 0!ontrol Tags1 ,xa#le 3sing !ount
In this setion" we are going to desribe the subset tag using the count parameter. The
ount parameter indiates the number of entries to be set in the resulting subset iterator.
33. Su/set Tag 0!ontrol Tags1 ,xa#le 3sing Start
In this setion" we are going to desribe the subset tag using the start parameter. The
start parameter is of integer type. It indiates the starting index :eg. first entry is *< of
entries in the soure :needed to make available as the first entry in the resulting subset
iterator<.
34. Action Tag 0*ata Tag1 ,xa#le
In this setion" we are going to desribe the ation tag. The ation tag is a generi tag that
is used to all ations diretly from a !S2 page by speifying the ation name and an
optional namespae.
35. 5ean Tag 0*ata Tag1 ,xa#le
In this setion" we are going to desribe the #ean Tag. The #ean tag is a generi tag that
is used to instantiates a lass that onfirms to the !ava#eans speifiation.
36. *ate Tag 0*ata Tag1 ,xa#le
In this setion" we are going to desribe the 0ate tag. The date tag allows to format a
0ate in a 3uik and easy way. 8ser an speify a custo# &or#at :eg. ;dd9%%9yyyy
hh/mm;<" an generate easy reada/le notations :like ;in 2 hours" .? minutes;<" or an
+ust fall bak on a rede&ined &or#at with key 6struts.date.format6 in the properties file.
37. 'nclude Tag 0*ata Tag1 ,xa#le
In this setion" we are going to desribe the inlude tag. The inlude tag is a generi tag
that is used to inlude a servlet6s output :result of servlet or a !S2 page< to the urrent
page.
38. 6ara# Tag 0*ata Tag1 ,xa#le
In this setion" we are going to desribe the param tag. The param tag is a generi tag that
is used to parameteri,e other tags. For example the inlude tag and bean tag. The
parameters an be added with or without a name as a key.
39. Set Tag 0*ata Tag1 ,xa#le
In this setion" we are going to desribe the Set tag. The set tag is a generi tag that is
used to assign a value to a variable in a speified sope.
40. Text Tag 0*ata Tag1 ,xa#le
In this setion" we are going to desribe the text tag. The text tag is a generi tag that is
used to render a I.@n text message.
41. 6roerty Tag 0*ata Tag1 ,xa#le
In this setion" we are going to desribe the property tag. The property tag is a generi tag
that is used to get the property of a value" whih will default to the top of the stak if
none is speified.
42. Struts 2 Tags 03' Tags1 ,xa#les

For# Tags ,xa#les
43. Auto !o#leter ,xa#le
In this setion" we are going to desribe the autoompleter tag. The autoompleter tag
always displays a dropdown list with the options that have at least a partial math with
entered text in the textbox. If the user liks on the dropdown button then all options
shown in the dropdown list.
44. !hec7/ox Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the hekbox tag. The hekbox tag is a 8I tag
that is used to render an 1T%& input element of type hekbox" populated by the
speified property from the AalueStak.
45. !hec7/oxlist Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the hekboxlist tag. The hekboxlist tag is a 8I
tag that reates a series of hekboxes from a list. Setup is like Bs/selet 9C or Bs/radio 9C"
but reates hekbox tags.
46. !o#/o/ox Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the ombobox tag. The ombo box is basially an
1T%& I428T of type text and 1T%& S5&5)T grouped together to give you a ombo
box funtionality.
47. *ateti#eic7er Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the datetimepiker tag. The datetimepiker tag is
a 8I tag that is used to render a date9time piker in a dropdown ontainer.
48. *ou/leselect Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the doubleselet tag. The doubleselet tag is a 8I
tag that renders two 1T%& selet elements with seond one hanging displayed values
depending on seleted entry of first one.
49. File Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the file tag. The file tag is a 8I tag that renders
an 1T%& file input element ahieved through browsing.
50. For# Tag ,xa#le
In this setion" we are going to desribe the form tag. The form tag is a 8I tag that
renders 1T%& an input form.
51. )a/el Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the label tag. The label tag is a 8I tag that is used
to render an 1T%& &'#5& that allows to output la/el8na#e type of ombinations that
has the same format treatment as the rest of 8I ontrols.
52. 9tiontrans&erselect Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the Optiontransferselet tag. The
Optiontransferselet tag is a 8I tag that reates an option transfer selet omponent.
53. 9tgrou Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the optgroup tag. The optgroup tag is a 8I tag
that reates an optgroup omponent whih needs to reside within a selet tag
<s:select>.
54. 6assword Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the password tag. The password tag is a 8I tag
that renders an 1T%& input tag of type password.
55. (adio Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the radio tag. The radio tag is a 8I tag that
renders a radio button input field.
56. (eset Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the reset tag. The reset tag is a 8I tag that is
used with the form tag to provide form resetting.
57. Select Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the selet tag. The selet tag is a 8I tag that is
used to render an 1T%& input tag of type selet.
58. Su/#it Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the submit tag. The submit tag is a 8I tag that is
used to render a submit button. The submit tag is used with the form tag to provide
asynhronous form submissions.
59. Textarea Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the textarea tag. The textarea tag is a 8I tag that
is used to render an 1T%& textarea.
60. Text&ield Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the textfield tag. The textfield tag is a 8I tag that
is used to render an 1T%& input field of type text.
61. 3downselect Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the updownselet tag. The updownselet tag is a
8I tag that reates a selet omponent with buttons to move up and down the elements in
the selet omponent.
Non2For# 3' Tags
62. Actionerror and Action#essage Tags 0Non2For# 3' Tags1 ,xa#le
In this setion" we are going to desribe the actionerror and action#essage tags. The
ationerror tag is a 8I tag that renders ation errors :in the +sp pages.< if they exists while
the ationmessage tag renders ation messages if they exists.
63. Fielderror Tag 0Non2For# 3' Tags1 ,xa#le
In this setion" we are going to desribe the fielderror tags. The fielderror tag is a 8I tag
that renders field errors if they exists.
64. Ta//ed6anel 0A4ax Tag1 ,xa#le
In this setion" you will learn about the tabbed2anel tag. This is an '+ax omponent"
where eah tab is either a loal ontent or a remote ontent :refreshed eah time when
user selets that tab<.
65. tree and treenode 0A4ax Tag1 tags ,xa#le
In this setion" you will learn about the tree and treenode tags. These both work with the
'+ax support.

66. *i" 0A4ax Tag1 tag ,xa#le
In this setion" you will learn about the di" tag. The di" tag is an '+ax omponent that is
used with '+ax that refreshes the ontents of a partiular setion without refreshing the
entire page.


Struts 2 ,xa#les
67. Struts 2 *ate
In this setion we will disuss the date proessing funtionalities available in the Struts 2
Framework.

68. *ate For#at ,xa#les
In this tutorials you will learn about 0ate Format funtion in Struts 2. -e have provided
fully tested example ode to illustrate the onepts.

69. Struts 2 datepiker 5xample
In this setion we will show you how to develop datetimepiker in struts 2. Struts 2 uses
the do+o toolkit for reating date piker.

70. Struts 2 For#at ,xa#les
In this setion you will learn how to format 0ate and numbers in Struts 2 Framework.
Our Struts 2 Format 5xamples are very easy to grasp and you will learn these onepts in
very small time.

71. Struts 2 File 3load
In this setion you will learn how to write program in Struts 2 to upload the file on the
server. In this example we are also providing the ode to save the uploaded file in any
diretory on the server mahine.

Struts 2 (esources ,xa#les
72. Struts 2 (esources ,xa#les
The struts 2 resoures examples

73. Static 6ara#eter
In this section, we will develop a simple application to access the static parameters. We will use a
JavaBean to set and get the static parameters. Each static parameter has a value.

74. Accessing Session 9/4ect
In this setion" we will develop a simple appliation to aess the framework resoures
like the session ob+et" session ontext and the last aessed session time.
75. Access (e:uest and (esonse
In this setion" you will learn to develop an appliation that aesses the re3uest and
response ob+et in struts 2 appliation.
Struts 2 Tools
76. Struts 2 ,clise 6lugin
This page ontains the examples and the list of plugins that are available for Struts 2
0evelopment using 5lipse I05.

77. Struts 2 '*,
This page ontains the list of I05s available to ease the development of Struts 2
Framework based appliations. The I05 for Struts 2 will atually make the development
yle muh easier.

78. Struts 2 Alication
0eveloping user registration appliation based on Struts 2 Framework. This Struts 2
'ppliation is a simple user registration appliation that will help you to learn how to
develop real world appliations using Struts 2 Framework.

79. Struts 2 A4ax
In this setion we explain you '+ax based development in Struts 2. Struts 2 provides
built(in support for '+ax using 0o+o toolkit.
Struts 2 Features
The strut-2 framework is designed for the comi!ation of the entire
de"e!oment c#c!e inc!uding of $ui!ding% de"e!oing and maintaining the
who!e a!ication. &t is "er# e'tensi$!e as each c!ass of the framework is
$ased on an &nterface and a!! the $ase c!asses are gi"en an e'tra a!ication
and e"en #ou can add #our own. The $asic !atform re(uirements are )er"!et
*+& 2.4% ,)+ *+& 2.0 and ,a"a 5.
)ome of the genera! features of the current *ache )trut 2 framework are
gi"en $e!ow.
Architecture - .irst the we$ $rowser re(uest a resource for which the .i!ter
/isatcher decides the suita$!e action. Then the &ntercetors use the
re(uired functions and after that the *ction method e'ecutes a!! the functions
!ike storing and retrie"ing data from a data$ase. Then the resu!t can $e seen
on the outut of the $rowser in 0T12% +/.% images or an# other.
Tags - Tags in )trut 2 a!!ow creating d#namic we$ a!ications with !ess
num$er of coding. 3ot on!# these tags contain outut data $ut a!so ro"ide
st#!e sheet dri"en marku that in turn he!s in creating ages with !ess code.
0ere the tags a!so suort "a!idation and !oca!i4ation of coding that in turn
offer more uti!i4ation. The !ess num$er of codes a!so makes it eas# to read
and maintain.
+V! D The +odel View !ontroller in Strut 2 framework ats as a oordinator between
appliationEs model and web view. Its )ontroller and Aiew omponents an ome together with
other tehnology to develop the model. The framework has its library and markup tags to present
the data dynamially.
!on&iguration D 2rovides a deployment desriptor to initiali,e resoures in $%& format. The
initiali,ation takes plae simply by sanning all the lasses using !ava pakages or you an use
an appliation onfiguration file to ontrol the entire onfiguration. Its general(purpose defaults
allow using struts diretly Out of the box.
)onfiguration files are re(loadable that allows hanges without restarting a web ontainer.
9ther Features8
'll framework lasses are based on interfaes and ore interfaes are independent from
1TT2.
)hek boxes do not re3uire any kind of speial appliation for false values.
'ny lass an be used as an ation lass and one an input properties by using any
!ava#ean diretly to the ation lass.
Strut 2 ations are Spring friendly and so easy to Spring integration.
'!'$ theme enables to make the appliation more dynami.
2ortal and servlet deployment are easy due to automati portlet support without altering
ode.
The re3uest handling in every ation makes it easy to ustomi,e" when re3uired.
Struts 2 - History of Struts 2
*ache )truts is an oen-source framework that is used for de"e!oing ,a"a
we$ a!ication. 5rigina!!# de"e!oed $# the rogrammer and author 6raig 7.
1c6!anahan% this was !ater taken o"er $# the *ache )oftware .oundation in
2002. )truts ha"e ro"ided an e'ce!!ent framework for de"e!oing a!ication
easi!# $# organi4ing ,)+ and )er"!et $ased on 0T12 formats and ,a"a code.
)trut1 with a!! standard ,a"a techno!ogies and ackages of ,akarta assists to
create an e'tensi$!e de"e!oment en"ironment. 0owe"er% with the growing
demand of we$ a!ication% Strut 1 does not stand firm and needs to $e
changed with demand. This !eads to the creation of )trut2% which is more
de"e!oer friend!# with features !ike *8a'% raid de"e!oment and
e'tensi$i!it#.
)truts is a we!!-organi4ed framework $ased on MVC architecture. &n Model-
View-Controller Architecture% 1ode! stands for the $usiness or data$ase
code% 9iew reresents the age design code and the 6ontro!!er for
na"igationa! code. *!! these together makes )truts an essentia! framework for
$ui!ding ,a"a a!ications. :ut with the de"e!oment of new and !ightweight
196 $ased framworks !ike )ring% )tries and Taestr#% it $ecomes
necessar# to modif# the )truts framework. )o% the team of *ache )truts and
another ,2;; framework% WebWork of OpenSymphony 8oined hand together
to de"e!o an ad"anced framework with a!! ossi$!e de"e!oing features that
wi!! make it de"e!oer and user friend!#.
Strut2 contains the com$ined features of )truts Ti and <e$<ork 2 ro8ects
that ad"ocates higher !e"e! a!ication $# using the architecture of
<e$<ork2 with features inc!uding a !ugin framework% a new *+&% *8a' tags
etc. )o the )truts communities and the <e$<ork team $rought together
se"era! secia! features in <e$<ork2 to make it more ad"ance in the 5en
)ource wor!d. 2ater the name of <e$<ork2 has changed to )truts2. 0ence%
*ache )trut 2 is a d#namic% e'tensi$!e framework for a com!ete a!ication
de"e!oment from $ui!ding% de!o#ing and maintaining.
-eb-ork is a framework for web(appliation development that has been inluded in Struts
framework 2.* release. It has some uni3ue onepts and onstruts like its ompatibility of
working within existing -eb '2Is in !ava rather than trying to replae them ompletely. It has
been built speifially taking into aount the developerEs produtivity and ode simpliity.
Furthermore it is ompletely ontext dependent that provides a wrapper around $-ork. -hen
working on web appliations the web work provides a ontext that helps web developer in
speifi implementations.
-hile" $-ork provides a mehanism that is used for onfiguration and fatory implementation
management. This mehanism is dependenies in+et mehanism.
Struts 2 Architecture - Detail information on Struts 2 Architecture
Struts and webwork has +oined together to develop the Struts 2 Framework. Struts 2 Framework
is very extensible and elegant for the development of enterprise web appliation of any si,e. In
this setion we are going to explain you the arhiteture of Struts 2 Framework.
(e:uest )i&ecycle in Struts 2 alications
1. 3ser Sends re:uest8 8ser sends a re3uest to the server for some resoure.

2. Filter*isatcher deter#ines the aroriate action8 The Filter0ispather looks at the
re3uest and then determines the appropriate 'tion.

3. 'ntercetors are alied8 Intereptors onfigured for applying the ommon
funtionalities suh as workflow" validation" file upload et. are automatially applied to
the re3uest.

4. ,xecution o& Action8 Then the ation method is exeuted to perform the database related
operations like storing or retrieving data from the database.

5. 9utut rendering8 Then the Result renders the output.

6. (eturn o& (e:uest8 Then the re3uest returns through the intereptors in the reverse
order. The returning re3uest allows us to perform the lean(up or additional proessing.

7. *islay the result to user8 Finally the ontrol is returned to the servlet ontainer" whih
sends the output to the user browser.
'#age8 Struts 2 high le"el o"er"iew o& re:uest rocessing8
Struts 2 Architecture
Struts 2 is a very elegant and flexible front ontroller framework based on many standard
tehnologies like !ava Filters" !ava #eans" Resoure#undles" $%& et.
For the +odel" the framework an use any data aess tehnologies like !0#)" 5!#" 1ibernate
et and for the View" the framework an be integrated with !S2" !T&" !SF" !akarta Aeloity
5ngine" Templates" 20F" $S&T et.
,xcetion Handling8
The Struts 2 Framework allows us to define exeption handlers and ineptors.
,xcetion Handlers8
5xeption handlers allows us to define the exeption handling proedure on global and
loal basis. Framework athes the exeption and then displays the page of our hoie
with appropriate message and exeption details.

'ntercetors8
The Intereptors are used to speify the ;re3uest(proessing lifeyle; for an ation.
Intereptors are onfigured to apply the ommon funtionalities like workflow" validation
et.. to the re3uest.
Struts 2 Architecture
The following diagram depits the arhiteture of Struts 2 Framework and also shows the the
initial re3uest goes to the servlet ontainer suh as tomat" whih is then passed through standard
filer hain.
'#age8 Struts 2 Architecture
The filter hain inludes/
Action !ontext!lean3 &ilter/
The 'tion)ontext)lean8p filter is optional and it is useful when integration has to be
done with other tehnologies like Site%ash 2lugin.

Filter*isatcher8
4ext the Filter0ispath is alled" whih in turn uses the 'tion%apper to determine
whether to invoke an 'tion or not. If the ation is re3uired to be invoked" the
Filter0ispather delegates the ontrol to the Action6roxy.

Action6roxy8
The 'tion2roxy takes help from )onfiguration Files manager" whih is initiali,ed from
the struts.xml. Then the 'tion2roxy reates an Action'n"ocation% whih implements
the ommand pattern. The 'tionInvoation proess invokes the Intereptors :if
onfigured< and then invokes the ation. The the 'tionInvoation looks for proper
result. Then the result is exeuted" whih involves the rendering of !S2 or templates.
Then the Intereptors are exeuted again in reverse order. Finally the response returns
through the filters onfigured in web.xml file. If the 'tion)ontext)lean8p filter is
onfigured" the Filter0ispather does not lean the Thread&oal 'tion)ontext. If the
'tion)ontext)lean8p filter is not present then the Filter0ispather will leanup all the
Thread&oals present.
In this setion we have learnt about the 'rhiteture of Struts 2 Framework.
Why Struts 2
The new "ersion Struts 2.; is a co#/ination o& the Sturts action &ra#ewor7 and We/wor7.
According to the Struts 2.;.1 release announce#ent% so#e 7ey &eatures are8
Si#li&ied *esign ( 2rogramming the abstrat lasses instead of interfaes is one of
design problem of struts. framework that has been resolved in the struts 2 framework.
%ost of the Struts 2 lasses are based on interfaes and most of its ore interfaes are
1TT2 independent. Struts 2 'tion lasses are framework independent and are simplified
to look as simple 2O!Os. Framework omponents are tried to keep loosely oupled.
Si#li&ied Actions ( 'tions are simple 2O!Os. 'ny +ava lass with exeute:< method
an be used as an 'tion lass. 5ven we don6t need to implement interfaes always.
Inversion of )ontrol is introdued while developing the ation lasses. This make the
ations to be neutral to the underlying framework .
No #ore ActionFor#s ( 'tionForms feature is no more known to the struts2
framework. Simple !ava#ean flavored ations are used to put properties diretly. 4o need
to use all String properties.
Si#li&ied testa/ility ( Struts 2 'tions are 1TT2 independent and framework neutral.
This enables to test struts appliations very easily without resorting to mok ob+ets.
'ntelligent *e&aults ( %ost onfiguration elements have a default value whih an be set
aording to the need. 5ven there are xml(based default onfiguration files that an be
overridden aording to the need.
'#ro"ed results ( 8nlike 'tionForwards" Struts 2 Results provide flexibility to reate
multiple type of outputs and in atual it helps to prepare the response.
5etter Tag &eatures ( Struts 2 tags enables to add style sheet(driven markup apabilities"
so that we an reate onsistent pages with less ode. Struts 2 tags are more apable and
result oriented. Struts 2 tag markup an be altered by hanging an underlying stylesheet.
Individual tag markup an be hanged by editing a Free%arker template. #oth !S2 and
Free%arker tags are fully supported.
Annotations introduced / 'ppliations in struts 2 an use !ava > annotations as an
alternative to $%& and !ava properties onfiguration. 'nnotations minimi,e the use of
xml.
State&ul !hec7/oxes ( Struts 2 hekboxes do not re3uire speial handling for false
values.
.uic7Start ( %any hanges an be made on the fly without restarting a web ontainer.
custo#i<ing controller ( Struts . lets to ustomi,e the re3uest proessor per module"
Struts 2 lets to ustomi,e the re3uest handling per ation" if desired.
,asy Sring integration ( Struts 2 'tions are Spring(aware. !ust need to add Spring
beansF
,asy lugins ( Struts 2 extensions an be added by dropping in a !'R. 4o manual
onfiguration is re3uiredF
A$A= suort ( The '!'$ theme gives interative appliations a signifiant boost.
The framework provides a set of tags to help you a+axify your appliations" even on 0o+o.
The '!'$ features inlude/

1. '!'$ )lient Side Aalidation


2. Remote form submission support :works with the submit tag as well<
3. 'n advaned div template that provides dynami reloading of partial 1T%&
4. 'n advaned template that provides the ability to load and evaluate !avaSript
remotely
5. 'n '!'$(only tabbed 2anel implementation
6. ' rih pub(sub event model
G. Interative auto omplete tag
Struts 1.x Vs Struts 2.x
In the following setion" we are going to ompare the various features between the two
frameworks. Struts 2.x is very simple as ompared to struts ..x" few of its exelent features are/
1. Ser"let *eendency8
'tions in Struts. have dependenies on the servlet '2I sine the HttSer"let(e:uest and
HttSer"let(esonse ob+ets are passed to the execute method when an 'tion is invoked but
in ase of Struts 2" 'tions are not ontainer dependent beause they are made simple 2O!Os. In
struts 2" the servlet ontexts are represented as simple %aps whih allows ations to be tested in
isolation. Struts 2 'tions an aess the original re3uest and response" if re3uired. 1owever"
other arhitetural elements redue or eliminate the need to aess the 1ttpServetRe3uest or
1ttpServletResponse diretly.
2. Action classes
2rogramming the abstrat lasses instead of interfaes is one of design issues of struts.
framework that has been resolved in the struts 2 framework.
Struts. 'tion lasses needs to extend framework dependent abstrat base lass. #ut in ase of
Struts 2 'tion lass may or may not implement interfaes to enable optional and ustom
servies. In ase of Struts 2 " 'tions are not ontainer dependent beause they are made simple
2O!Os. Struts 2 provides a base 'tionSupport lass to implement ommonly used interfaes.
'lbeit" the 'tion interfae is not re3uired. 'ny 2O!O ob+et with an execute signature an be
used as an Struts 2 'tion ob+et.
>. Validation
Struts. and Struts 2 both supports the manual validation via a validate method.
Struts. uses validate method on the 'tionForm" or validates through an extension to the
)ommons Aalidator. 1owever" Struts 2 supports manual validation via the validate method
and the $-ork Aalidation framework. The $work Aalidation Framework supports haining
validation into sub(properties using the validations defined for the properties lass type and the
validation ontext.
?. Threading +odel
In Struts." 'tion resoures must be thread(safe or synhroni,ed. So 'tions are singletons and
thread(safe" there should only be one instane of a lass to handle all re3uests for that 'tion.
The singleton strategy plaes restritions on what an be done with Struts. 'tions and re3uires
extra are to develop. 1owever in ase of Struts 2" 'tion ob+ets are instantiated for eah
re3uest" so there are no thread(safety issues. :In pratie" servlet ontainers generate many throw(
away ob+ets per re3uest" and one more ob+et does not impose a performane penalty or impat
garbage olletion.<
@. Testa/ility
Testing Struts. appliations are a bit omplex. ' ma+or hurdle to test Struts. 'tions is that the
execute method beause it exposes the Servlet '2I. ' third(party extension" Struts Test)ase"
offers a set of mok ob+et for Struts.. #ut the Struts 2 'tions an be tested by instantiating the
'tion" setting properties and invoking methods. 0ependeny In+etion support also makes
testing simpler. 'tions in struts2 are simple 2O!Os and are framework independent" hene
testability is 3uite easy in struts2.
A. Har"esting 'nut
Struts. uses an 'tionForm ob+et to apture input. 'nd all 'tionForms needs to extend a
framework dependent base lass. !ava#eans annot be used as 'tionForms" so the developers
have to reate redundant lasses to apture input.
1owever Struts 2 uses 'tion properties :as input properties independent of underlying
framework< that eliminates the need for a seond input ob+et" hene redues redundany.
'dditionally in struts2" 'tion properties an be aessed from the web page via the taglibs.
Struts 2 also supports the 'tionForm pattern" as well as 2O!O form ob+ets and 2O!O 'tions.
5ven rih ob+et types" inluding business or domain ob+ets" an be used as input9output ob+ets.
B. ,xression )anguage
Struts. integrates with !ST&" so it uses the !ST&(5&. The struts. 5& has basi ob+et graph
traversal" but relatively weak olletion and indexed property support. Struts 2 an also use
!ST&" however it supports a more powerful and flexible expression language alled ;Ob+et
Hraph 4otation &anguage; :OH4&<.
C. 5inding "alues into "iews
In the view setion" Struts. uses the standard !S2 mehanism to bind ob+ets :proessed from the
model setion< into the page ontext to aess. 1owever Struts 2 uses a ;AalueStak; tehnology
so that the taglibs an aess values without oupling your view to the ob+et type it is rendering.
The AalueStak strategy allows the reuse of views aross a range of types whih may have the
same property name but different property types.
D. Tye !on"ersion
8sually" Struts. 'tionForm properties are all Strings. Struts. uses )ommons(#eanutils for type
onversion. These type onverters are per(lass and not onfigurable per instane. 1owever
Struts 2 uses OH4& for type onversion. The framework inludes onverters for basi and
ommon ob+et types and primitives.
1;. !ontrol 9& Action ,xecution
Struts. supports separate Re3uest 2roessor :lifeyles< for eah module" but all the 'tions in a
module must share the same lifeyle. 1owever Struts 2 supports reating different lifeyles on
a per 'tion basis via Intereptor Staks. )ustom staks an be reated and used with different
'tions as needed.
Download and Installin Struts 2
In this setion we will download and install the Struts 2.* on the latest version of Tomat
ontainer. -e will first download tomat and onfigure it as our development server. Then we
will download Struts 2.* and install the struts(blank appliation on the tomat server to hek the
examples that ome with the struts(blank appliation.
*ownloading Struts 2.;
Aisit the Struts download site http/99struts.apahe.org9download.gi and download the Struts 2.*
for this tutorial.
-e have downloaded the Struts 2.*.7 :struts(2.*.7(all.,ip< for this tutorial.
*ownload the To#cat
0ownload the latest version of tomat from http/99tomat.apahe.org9download(>>.gi. -e have
downloaded aache2to#cat2@.@.2;.<i for this tutorial.
I am assuming that latest version of !ava is installed on your system. 5xtrat downloaded file and
run the )/Iapahe(tomat(>.>.2*IbinIstartup.bat to start the tomat. Type http/99loalhost/@*@*9 in
your browser" it should show the welome page in the browser window as shown below.
)ongratulations you have now suessfully installed latest version of tomat for learning Struts
2.*. 4ow we will install the struts(blank appliation on the tomat ontainer and test the
appliation.
,xtracting Struts 2.; distri/ution and installing on to#cat
5xtrat the downloaded struts distribution struts(2.*.7(all.,ip into your favorite diretory. To
install the struts blank appliation opy ;struts2(blank(2.*.7; from ;Eextracted
directoryFGstruts22.;.A2allGstruts22.;.AGas; into the webapps diretory of tomat. Tomat
will automatially deploy the appliation.
Feb 2>" 2**G ../?2/2J 2% org.apahe.oyote.http...1ttp..#ase2rotool
start
I4FO/ Starting )oyote 1TT29... on http(@*@*
Feb 2>" 2**G ../?2/2? 2% org.apahe.+k.ommon.)hannelSoket init
I4FO/ !K/ a+p.J listening on 9*.*.*.*/@**L
Feb 2>" 2**G ../?2/2? 2% org.apahe.+k.server.!k%ain start
I4FO/ !k running I0M* timeM*9.?. onfigMnull
Feb 2>" 2**G ../?2/2? 2% org.apahe.atalina.storeonfig.Store&oader load
I4FO/ Find registry server(registry.xml at lasspath resoure
Feb 2>" 2**G ../?2/2? 2% org.apahe.atalina.startup.)atalina start
I4FO/ Server startup in 77G2 ms
Feb 2>" 2**G ../>2/>> 2% org.apahe.atalina.startup.1ost)onfig
deploy-'R
I4FO/ 0eploying web appliation arhive struts2(blank(2.*.7.war
To test the struts(blank appliation type http/99loalhost/@*@*9struts2(blank(2.*.7 in the browser
and the struts(blank appliation get displayed in your browser window.
)lik the 5nglish link and familiari,e yourself with Struts #lank sample appliation.
Struts 2.* distribution also ontains the following sample appliations that you an try/
struts2(mailreader(2.*.7.war
struts2(portlet(2.*.7.war
struts2(showase(2.*.7.war
=ou an simply opy these files to the webapps diretory of your tomat server. Tomat will
automatially deploy these appliations and then you an test these appliations.
Struts 2 Hello World A!!lication "xam!le# $earn how to de%elo! Hello World a!!lication
in struts 2
In this setion we will develop Hello World appliation based on Struts 2 Fra#ewor7. Our
Struts 2 Hello World appliation is your first step towards developing appliations based on
Struts 2 Fra#ewor7. -e are here providing step by step guide for developing Hello World
appliation in Struts 2 framework.
Tutorial overs basi steps like reating diretory struture" developing build.xml file to build the
appliation using ant build tool. Then we explained !ava" !S2 and onfiguration files that are
re3uired in this appliation.
!reating directory structure &or the ro4ect
Ste18 5xtrat struts 2 download and opy struts22/lan722.;.A.war:If you are using latest
version of struts 2 then version may be different for you< to your tomats we/as diretory.
Rename struts22/lan722.;.A.war to struts2tutorial and un,ip it in the tomats webapps
diretory. 4ow start the tomat and type http/99loalhost/@*@*9struts2tutorial9 into your browser.
=ou browser should show look like/
)ongratulations you have suessfully installed struts 2 blank appliation to start with.
Ste 28 4ow delete the ontent of struts2tutorialGW,52'NFGsrc and struts2tutorialGW,52
'NFGclasses diretories" as we don6t need these files that omes with struts 2 blank appliation.
Ste >8 )reate /uild.x#l file in the struts2tutorialGW,52'NFGsrc and paste the following
ontent in the /uild.x#l file.
<project name="Struts 2 Tutorial" basedir="../" default="all">
<! !roject settin"s >
<propert# name="project.title" value="$ose%ndia Struts 2 Tutorials"/>
<propert# name="project.jar.file" value="struts2tutorial.jar"/>
<pat& id="class.pat&">
<fileset dir="lib">
<include name="''/'.jar"/>
</fileset>
<fileset dir="libext">
<include name="''/'.jar"/>
</fileset>
</pat&>
<! (lasspat& for !roject >
<pat& id="compile.classpat&">
<pat&element pat& ="lib/commonsbeanutils.jar"/>
<pat&element pat& ="lib/commonsdi"ester.jar"/>
<pat&element pat& ="lib/struts.jar"/>
<pat&element pat& ="libext/servletapi.jar"/>
<pat&element pat& ="libext/catalinaant.jar"/>
<pat&element pat& ="classes"/>
<pat&element pat& =")*classpat&+"/>
</pat&>
<! (&ec, timestamp on files >
<tar"et name="prepare">
<tstamp/>
<cop#
file="src/struts.xml"
todir="src/classes"/>
</tar"et>
<! (op# an# resource or confi"uration files >
<tar"et name="resources">
<cop# todir="src/classes" include-mpt#.irs="no">
<fileset dir="src/java">
<patternset>
<include name="''/'.conf"/>
<include name="''/'.properties"/>
<include name="''/'.xml"/>
</patternset>
</fileset>
</cop#>
</tar"et>
<! /ormal build of application >
<tar"et name="compile" depends="prepare0resources">
<javac srcdir="src" destdir="src/classes"
debu"="true" debu"level="lines0vars0source">
<classpat& refid="class.pat&"/>
</javac>
<jar
jarfile="lib/)*project.jar.file+"
basedir="src/classes"/>
</tar"et>
<! $emove classes director# for clean build >
<tar"et name="clean"
description="!repare for clean build">
<delete dir="classes"/>
<m,dir dir="classes"/>
</tar"et>
<! 1uild 2avadoc documentation >
<tar"et name="javadoc"
description="3enerate 2ava.oc 4!% docs">
<delete dir="./doc/api"/>
<m,dir dir="./doc/api"/>
<javadoc sourcepat&="./src/java"
destdir="./doc/api"
classpat&=")*servlet.jar+:)*jdbc25ext.jar+"
pac,a"enames="'"
aut&or="true"
private="true"
version="true"
6indo6title=")*project.title+ 4!%
.ocumentation"
doctitle="7lt8&97"t8)*project.title+
.ocumentation :;ersion )
*project.version+<7lt8/&97"t8"
bottom="(op#ri"&t 7=9>?8 2552">
<classpat& refid="compile.classpat&"/>
</javadoc>
</tar"et>
<! 1uild entire project >
<tar"et name="project" depends="clean0prepare0compile"/>
<! (reate binar# distribution >
<tar"et name="dist"
description="(reate binar# distribution">
<m,dir
dir=")*distpat&.project+"/>
<jar
jarfile=")*distpat&.project+/)
*project.distname+.jar"
basedir="./classes"/>
<cop#
file=")*distpat&.project+/)*project.distname+.jar"
todir=")*distpat&.project+"/>

<6ar
basedir="../"
6arfile=")*distpat&.project+/)
*project.distname+.6ar"
6ebxml="6eb.xml">
<exclude name=")*distpat&.project+/)
*project.distname+.6ar"/>
</6ar>
</tar"et>
<! 1uild project and create distribution>
<tar"et name="all" depends="project"/>
</project>
Ste ?8 )reate diretory li/ext under the struts2tutorialGW,52'NFG then you opy latest
Servlets api +ar :in our ase servlet(api.+ar< file over there. This library file will be used to
ompile Servlets in our appliation.
Ste @8 4ow reate diretories 4a"a and classes under struts2tutorialGW,52'NFGsrc. The
diretory struts2tutorialGW,52'NFGsrcG4a"a will be used to put all the +ava soures file and
diretory struts2tutorialGW,52'NFGsrcGclasses will be used by ant build utility to store
ompiled +ava files.
4ow we have suessfully reated the diretory struture and ant build file for our Struts 2 1ello
-orld 'ppliation. In the next setion we will reate !S2" !ava file and the onfiguration file and
then test our Struts 2 1ello -orld appliation.
De%elo!in &S'# &a%a and (onfiuration for Hello World A!!lication
In this setion we will write !S2" !ava and re3uired onfiguration files for our Struts 2 1ello
-orld appliation. 4ow in struts 2 struts.x#l is used to onfigure the appliations.
3nderstanding the alication
Our appliation is very simple appliation that displays 1ello -orld message along with urrent
date and time of the server. -hen user liks on the ;(un Struts 2 Hello World Alication;
link on the tutorial home page" a re3uest is sent to the struts framework. Then struts framework
sends the input to the ation lass :in our ase Struts21ello-orld.+ava<. 'fter ation is fired the
Result selets the resoure ;9pages91ello-orld.+sp; to render the response.
In this example we have to develop three parts view" 'tion lass and mapping :struts.xml< to
ouple ation and page. #y reating these three omponents we are separating the appliation in
three parts Aiew" %odel and )ontroller.
*e"eloing View8
This page is used to display the result on the browser. The 1ello-orld.+sp is view part of our
appliation. )reate ;1ello-orld.+sp; in the struts2tutorialIpages diretory and add the following
ontent/
EHI tagli/ re&ixJKsK uriJK-struts2tagsK HF
BhtmlC
BheadC
BtitleCStruts 2 1ello -orld 'ppliationFB9titleC
B9headC
BbodyC
Bh2CEs8roerty "alueJK#essageK -FB9h2C
BpC)urrent date and time is/ BbCEs8roerty "alueJKcurrentTi#eK -FB9bC
B9bodyC
B9htmlC
The line EHI tagli/ re&ixJKsK uriJK-struts2tagsK HF delares data tag library of struts. The
struts data tag is used to display the dynami data. The tag Es8roerty "alueJK#essageK -F
and Es8roerty "alueJKcurrentTi#eK -F alls the methods get%essage:< and
get)urrentTime:< respetively of the Struts21ello-orld ation lass and merges the values with
response.
*e"eloing Action 0to interact with +odel18
4ow reate Struts2HelloWorld.4a"a and saves it to the ;struts2tutorialGW,52
'NFGsrcG4a"aGnetGroseindia; diretory. This ation lass reates the message to be displayed on
the sreen. 1ere is the ode of Struts2HelloWorld.4a"a8
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util..ate8
public class Struts2@elloAorld extends 4ctionSupport *
public static final Strin" B-SS43- = "Struts 2 @ello Aorld Tutorial!"8
public Strin" execute:< throws -xception *
setBessa"e:B-SS43-<8
return SC((-SS8
+
private Strin" messa"e8
public void setBessa"e:Strin" messa"e<*
this.messa"e = messa"e8
+
public Strin" "etBessa"e:< *
return messa"e8
+
public Strin" "et(urrentTime:<*
return new .ate:<.toStrin":<8
+
+
*e"eloing !ontroller !on&iguration File8
Struts 2 uses the struts.x#l file for onfiguring the appliation. )reate struts.x#l file and save it
in the ;struts2tutorialGW,52'NFGsrc; diretory with the following ontent.
BNxml versionM;..*; enodingM;8TF(@; NC
BF0O)T=25 struts 28#&I)
;(99'pahe Software Foundation990T0 Struts )onfiguration 2.*9954;
;http/99struts.apahe.org9dtds9struts(2.*.dtd;C
BstrutsC
Bonstant nameM;struts.enable.0ynami%ethodInvoation; valueM;false; 9C
Bonstant nameM;struts.dev%ode; valueM;true; 9C
Bpakage nameM;roseindia; namespaeM;9roseindia; extendsM;struts(default;C
Bation nameM;1ello-orld; lassM;net.roseindia.Struts21ello-orld;C
BresultC9pages91ello-orld.+spB9resultC
B9ationC
BF(( 'dd ations here ((C
B9pakageC
BF(( 'dd pakages here ((C
B9strutsC
The struts.xml file should be present in the lass path of the appliation" you an either inlude it
in the +ar and plae in the lib diretory of the appliation or plae it in the lasses diretory of the
web appliation. In our appliation we are using ant build tool whih is inluding it in the +ar file.
5uilding the alication
I am assuming that you have already installed ant build tool on your mahine. Sine we are using
the ant built tool" building appliation by using is very easy. To build the appliation open
ommand prompt and go to ;struts2tutorialI-5#(I4FIsr; diretory of the web appliation and
issue the ;ant; ommand. The ant build tool will ompile the +ava file and reate +ar file
;struts2tutorial.4ar; into the lib diretory of your web appliation. 1ere is the output of ant
build tool/
)/Iapahe(tomat(7.*..*Iapahe(tomat(7.*..*IwebappsIstruts2tutorialI-5#(I4FIsr
Cant
#uildfile/ build.xml
lean/
OdeleteP 0eleting diretory )/Iapahe(tomat(7.*..*Iapahe(tomat(
7.*..*IwebappsIstruts2tutorialI-5#(I4FIlasses
OmkdirP )reated dir/ )/Iapahe(tomat(7.*..*Iapahe(tomat(7.*..*IwebappsIstruts2tutorialI-5#(
I4FIlasses
prepare/
resoures/
ompile/
O+avaP )ompiling . soure file to )/Iapahe(tomat(7.*..*Iapahe(tomat(
7.*..*IwebappsIstruts2tutorialI-5#(I4FIsrIlasses
O+arP #uilding +ar/ )/Iapahe(tomat(7.*..*Iapahe(tomat(7.*..*IwebappsIstruts2tutorialI-5#(
I4FIlibIstruts2tutorial.+ar
pro+et/
all/
#8I&0 S8))5SSF8&
Total time/ G seonds
)/Iapahe(tomat(7.*..*Iapahe(tomat(7.*..*IwebappsIstruts2tutorialI-5#(I4FIsr
C
Testing Struts 2 Hello World Alication
In the above setion we have ompiled our appliation and now finally we will test our
appliation. To test the appliation start the tomat server and type
http/99loalhost/@*@*9struts2tutorial9 and then selet ;(un Struts 2 Hello World Alication;
from the list.
1ere is the sreen shot of our struts 2 tutorial home page/
Selet ;(un Struts 2 Hello World Alication; link. Our first appliation ;Struts 2 Hello
World; will look like the following/
The appliation will display message ;Struts 2 1ello -orld TutorialF; along with urrent date
and time of the server.
How alication wor7sL
1ere is the brief desription on how Struts 2 1ello -orld 'ppliation works/
=our browser sends a re3uest to the web server for the 8R&
http/99loalhost/@*@*9tutorial91ello-orld.ation.
1. -hen you lik on the ;(un Struts 2 Hello World Alication; link" the browser sends
a re3uest for the url http/99loalhost/@*@*9struts2tutorial9roseindia91ello-orld.ation. The
ontainer re3uests for the resoure ;1ello-orld.ation;. #y default web.xml file of struts
blank appliation is onfigured to route all the re3uest for Q.ation through
org.apahe.struts2.dispather.Filter0ispather. 1ere is the onfiguration from web.xml
file/
BfilterC
Bfilter(nameCstruts2B9filter(nameC
Bfilter(lassCorg.aache.struts2.disatcher.Filter*isatcherB9filter(lassC
B9filterC
Bfilter(mappingC
Bfilter(nameCstruts2B9filter(nameC
Burl(patternC-MB9url(patternC
B9filter(mappingC

2. Then the framework looks for the mapping for the ation ;1ello-orld; and then
framework instantiates the appropriate lass and alls the exeute method. In this ase
ation lass is Struts21ello-orld. 1ere is the onfiguration file from struts.xml whih
defines the ation mapping/
Bation nameM;HelloWorld; lassM;net.roseindia.Struts2HelloWorld;C
BresultC-ages-HelloWorld.4sB9resultC
B9ationC

3. Then the exeute method sets the message and returns S8))5SS.
publi String exeute:< throws 5xeption R
set%essage:%5SS'H5<S
return S8))5SSS
T
Then framework determines whih page is to be loaded if S8))5SS is returned. In our
ase framework tells the ontainer to load 1ello-orld.+sp and render the output.
In the struts 2 framework 'tions are used to proess the form and user re3uest. The
exeute method of the ation returns S8))5SS" 5RROR" or I428T value. Then based
on these values framework tells the ontainer to load and render the appropriate result.

4. )ontainer proess the 1ello-orld.+sp and generates the output.

>. Then the output in the 1T%& format is sent to the browser.
*ownload the alication and source code8
=ou an download the appliation and soure ode of the tutorial and to save your time and
efforts spent on onfiguring the appliation. )lik here to download the ode.
Our goal is to provide the working skeleton of the appliation based on ant tool. So you an
download the appliation and then use ant tool to ompile the +ava lasses. 'ppliation is in the
exploded diretory struture and an be deployed as it is on tomat server. If any of our visitor
finds and problem please disuss it. -e re3uest you to share your experienes with us.
Struts (onfiuration file - struts.xml
In this setion we will introdue you to the struts.xml file. This setion explains you how best
you an use the struts.xml file for you big pro+ets.
The struts.x#l File
The Struts 2 Framework uses a onfiguration file :struts.xml< to initiali,e its own resoures.
These resoures inlude/
Intereptors that an preproess and postproess a re3uest
'tion lasses that an all business logi and data aess ode
Results that an prepare views using !avaServer 2ages" Aeloity and Free%arker
templates
't runtime" there is a single onfiguration for an appliation. 2rior to runtime" the onfiguration
is defined through one or more $%& douments" inluding the default struts.xml doument.
There are several elements that an be onfigured" inluding pakages" namespaes" inludes"
ations" results" intereptors" and exeptions.
The struts.xml file is the ore onfiguration file for the framework and it should be present in the
lass path of your web appliation. Features of struts 2 onfiguration file/
The struts.xml file allows to break big struts.xml file into small files and onfiguration
files to be inluded as needed. 1ere is the example/

BstrutsC
.....
......
Binlude
fileM;file..xml;9C
Binlude
fileM;file2.xml;9C
.....
.....
B9strutsC

=ou an even plae struts(plugin.xml file in the !'R" and it will be automatially plugged
into the appliation. This helps the programmers to develop self(onfigured omponents.

If you want to use the frameworks suh as Freemaker and Aeloity modules" then the
templates an also be loaded from lasspath. This enables the developer to pakage entire
module +ust in single !'R file.
Structure o& the struts.x#l &ile
In the last setion we developed and tested the 1ello -orld appliation. 1ere is the sample
struts.xml file from the last example.
BNxml versionM;..*; enodingM;8TF(@; NC
BF0O)T=25 struts 28#&I)
;(99'pahe Software Foundation990T0 Struts )onfiguration 2.*9954;
;http/99struts.apahe.org9dtds9struts(2.*.dtd;C
BstrutsC
Bonstant nameM;struts.enable.0ynami%ethodInvoation;
valueM;false; 9C
Bonstant nameM;struts.dev%ode; valueM;true; 9C
Bpakage nameM;roseindia; namespaeM;9roseindia; extendsM;struts(
default;C
Bation nameM;1ello-orld; lassM;net.roseindia.Struts21ello-orld;C
BresultC9pages91ello-orld.+spB9resultC
B9ationC
BF(( 'dd ations here ((C
B9pakageC
BF(( 'dd pakages here ((C
B9strutsC
The struts.x#l &ile #ust con&ir# to the Struts 2 *ocu#ent Tye *e&inition 0*T*1
The /T/ ro"ides information a$out the structure and the e!ements that the
struts.xml file shou!d ha"e.
1ere is the Struts 2.* 0T0 /
<!
Struts confi"uration .T..
Cse t&e follo6in" .D(TE!-

<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts
(onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
>
<!-F-B-/T struts :pac,a"eHincludeHbeanHconstant<'>
<!-F-B-/T pac,a"e :resultt#pesI0 interceptorsI0
defaultinterceptorrefI0 defaultactionrefI0 "lobal
resultsI0
"lobalexceptionmappin"sI0 action'<>
<!4TTF%ST pac,a"e
name (.4T4 =$-JC%$-.
extends (.4T4 =%B!F%-.
namespace (.4T4 =%B!F%-.
abstract (.4T4 =%B!F%-.
external$eference$esolver /BTDK-/ =%B!F%-.
>
<!-F-B-/T resultt#pes :resultt#peL<>
<!-F-B-/T resultt#pe :param'<>
<!4TTF%ST resultt#pe
name (.4T4 =$-JC%$-.
class (.4T4 =$-JC%$-.
default :trueHfalse< "false"
>
<!-F-B-/T interceptors :interceptorHinterceptorstac,<L>
<!-F-B-/T interceptor :param'<>
<!4TTF%ST interceptor
name (.4T4 =$-JC%$-.
class (.4T4 =$-JC%$-.
>
<!-F-B-/T interceptorstac, :interceptorrefL<>
<!4TTF%ST interceptorstac,
name (.4T4 =$-JC%$-.
>
<!-F-B-/T interceptorref :param'<>
<!4TTF%ST interceptorref
name (.4T4 =$-JC%$-.
>
<!-F-B-/T defaultinterceptorref :param'<>
<!4TTF%ST defaultinterceptorref
name (.4T4 =$-JC%$-.
>
<!-F-B-/T defaultactionref :param'<>
<!4TTF%ST defaultactionref
name (.4T4 =$-JC%$-.
>
<!-F-B-/T "lobalresults :resultL<>
<!-F-B-/T "lobalexceptionmappin"s :exceptionmappin"L<>
<!-F-B-/T action :paramHresultHinterceptorrefHexception
mappin"<'>
<!4TTF%ST action
name (.4T4 =$-JC%$-.
class (.4T4 =%B!F%-.
met&od (.4T4 =%B!F%-.
converter (.4T4 =%B!F%-.
>
<!-F-B-/T param :=!(.4T4<>
<!4TTF%ST param
name (.4T4 =$-JC%$-.
>
<!-F-B-/T result :=!(.4T4Hparam<'>
<!4TTF%ST result
name (.4T4 =%B!F%-.
t#pe (.4T4 =%B!F%-.
>
<!-F-B-/T exceptionmappin" :=!(.4T4Hparam<'>
<!4TTF%ST exceptionmappin"
name (.4T4 =%B!F%-.
exception (.4T4 =$-JC%$-.
result (.4T4 =$-JC%$-.
>
<!-F-B-/T include :=!(.4T4<>
<!4TTF%ST include
file (.4T4 =$-JC%$-.
>
<!-F-B-/T bean :=!(.4T4<>
<!4TTF%ST bean
t#pe (.4T4 =%B!F%-.
name (.4T4 =%B!F%-.
class (.4T4 =$-JC%$-.
scope (.4T4 =%B!F%-.
static (.4T4 =%B!F%-.
optional (.4T4 =%B!F%-.
>
<!-F-B-/T constant :=!(.4T4<>
<!4TTF%ST constant
name (.4T4 =$-JC%$-.
value (.4T4 =$-JC%$-.
>
It is possible to remove the Ustruts.xmlV file from your appliation ompletely if the funtionality
of your appliation does not depends on it. There are few onfigurations that an be handled
alternatively suh as annotations% Nwe/.x#lO startu ara#eters% and alternate 3()
#aing sche#es. Still" there are few onfigurations that always need the Ustruts.xmlV file like
the glo/al results% excetion handling% and the custo# intercetor stac7s.
,xloring struts.x#l
The EstrutsF tag is the root tag for the struts.x#l. It may ontain the following tags / pakage"
inlude" bean and onstant.
1. The 6ac7age Tag 8
2akages are a way to group ations" results" result types" intereptors" and intereptor(staks
into a logial onfiguration unit. )oneptually" pakages are similar to ob+ets in that they an be
extended and have individual parts that an be overridden by ;sub; pakages.
The Bpakage 9C tag is used to group together onfigurations that share ommon attributes suh
as intereptor staks or 8R& namespaes. It may also be useful to organi,ationally separate
funtions" whih may be further separated into different onfiguration files.
The pakage element has one re3uired attribute" name" whih ats as the key for later referene to
the pakage. The extends attribute is optional and allows one pakage to inherit the
onfiguration of one or more previous pakages ( inluding all intereptor" intereptor(stak" and
ation onfigurations.
4ote that the onfiguration file is proessed se3uentially down the doument" so the pakage
referened by an ;extends; should be defined above the pakage whih extends it.
The optional abstract attribute reates a base pakage that an omit the ation onfiguration.
Attri/ute (e:uired *escrition
name yes key for other pakages to referene
extends no inherits pakage behavior of the pakage it extends
namespae no provides a mapping from the 8R& to the pakage.
abstrat no
delares pakage to be abstrat :no ation
onfigurations re3uired in pakage<
1. na#e D uni3ue name is given for a pakage.
2. extends D the name of a pakage that this pakage will extendS all onfiguration information
:inluding ation onfigurations< from the extended pakage will be available in the new
pakage" under the new namespae.
J. na#esace D the namespae provides a mapping from the 8R& to the pakage. i.e. for two
different pakages" with namespae attributes defined as Upak.V and Upak2V" the 8R&s would
be something like U9web'pp9pak.9my.ationV and U9web'pp9pak29my.ationV
?. a/stract D if this attribute value is UtrueV the pakage is truly a onfiguration grouping and
ations onfigured will not be aessible via the pakage name. It is important to make sure you
are extending the orret parent pakage so that the neessary pre(onfigured features will be
available to you.
2. The 'nclude Tag8
The Binlude 9C tag is used to modulari,e a Struts2 appliation that needs to inlude other
onfiguration files. It ontains only one attribute UfileV that provides the name of the xml file to
be inluded. This file has exatly the same struture as the Ustruts.xmlV onfiguration file. For
example" to break a onfiguration file of a finane appliation" you might hoose to group
together the invoies" admin" report onfigurations et into separate files/
BstrutsC
Binlude fileM;invoies(
onfig.xml; 9C
Binlude fileM;admin(
onfig.xml; 9C
Binlude fileM;reports(
onfig.xml; 9C
B9strutsC

-hile inluding files" order is important. The information from the inluded file will be available
from the point that the inlude tag is plaed in the file.
There are some files that are inluded impliitly. These are the Ustrutsde&ault.x#lV and the
Ustruts2lugin.x#lV files. #oth ontains default onfigurations for result types" intereptors"
intereptor staks" pakages as well as onfiguration information for the web appliation
exeution environment :whih an also onfigured in the Ustruts.propertiesV file<. The differene
is that Ustruts(default.xmlV provides the ore onfiguration for Struts2" where Ustruts(plugin.xmlV
provides onfigurations for a partiular plug(in. 5ah plug(in !'R file should ontain a Ustruts(
plugin.xmlV file" all of whih are loaded during startup.
>. The 5ean Tag
%ost appliations won6t need to extend the #ean )onfiguration. The bean element re3uires the
class attribute whih speifies the !ava lass to be reated or manipulated. ' bean an either
1. be reated by the framework6s ontainer and in+eted into internal framework ob+ets" or
2. have values in+eted to its stati methods
The first use" ob+et in+etion" is generally aompanied by the t#pe attribute" whih tells the
ontainer that whih interfae this ob+et implements.
The seond use" value in+etion" is good for allowing ob+ets not reated by the ontainer to
reeive framework onstants. Ob+ets using value in+et must define the the static attribute.
Attri/ute (e:uired *escrition
lass yes the name of the bean lass
type no the primary !ava interfae this lass implements
name no
the uni3ue name of this beanS must be uni3ue among other
beans that speify the same t#pe
sope no
the sope of the beanS must be either default" sin"leton"
reMuest" session" t&read
stati no
whether to in+et stati methods or notS shouldn6t be true
when the t#pe is speified
optional no whether the bean is optional or not
5ean ,xa#le 0struts.x#l1

BstrutsC
Bbean
typeM;roseindi
a.net.Ob+etFa
tory;
nameM;fatory
;
lassM;roseindi
a.net.%yOb+et
Fatory; 9C

...
B9strutsC
?. The !onstant Tag
There are two key roles for onstants.
.. They are used to override settings like the maximum file upload si,e or whether the Struts
framework should be in dev%ode:M development mode< or not.
2. They speify whih #ean should be hosen" among multiple implementations of a given type.
)onstants an be delared in multiple files. #y default" onstants are searhed for in the
following order" allowing for subse3uent files to override by the previous ones/
struts(default.xml
struts(plugin.xml
struts.xml
struts.properties
web.xml
The struts.properties file is provided for bakward(ompatiblity with -eb-ork. In the
struts.properties file" eah entry is treated as a onstant. In the web.xml file" any Filter0ispather
initiali,ation parameters are loaded as onstants.
In the various $%& variants" the onstant element has two re3uired attributes / name and value.
Attri/ute (e:uired *escrition
name yes the name of the onstant
value yes the value of the onstant
!onstant ,xa#le 0struts.x#l1

BstrutsC
Bonstant
nameM;struts.dev%ode;
valueM;true; 9C
...
B9strutsC

!onstant ,xa#le 0struts.roerties1
struts.de"+ode J true
Struts2 Actions
Struts2 Actions
-hen a lient6s re3uest mathes the ation6s name" the framework uses the mapping from
struts.x#l file to proess the re3uest. The mapping to an ation is usually generated by a Struts
Tag.

Struts 2 Rediret 'tion
In this setion" you will get familiar with struts 2 Rediret ation and learn to use it in the struts 2
appliation
. -hen a lient6s re3uest mathes the ation6s name" the framework uses the mapping from
struts.x#l file to proess the re3uest. The mapping to an ation is usually generated by a Struts
Tag. The ation tag :within the struts root node of struts.xml file< speifies the ation by name
and the framework renders the default extension and other re3uired stuff.
The default entry method to the handler lass is defined by the 'tion interfae.
Struts2 Action inter&ace
'll ations may implement this interfae" whih exposes the execute01 method. =ou are free to
reate 69$9s that maintains the same ontrat defined by this interfae without atually
implementing the interfae.
pac,a"e com.opens#mp&on#.x6or,28
public interface 4ction *
//T&e action execution 6as a failure.
public final static Strin" -$$D$8
//T&e action execution reMuire more input
in order to succeed
public final static Strin" %/!CT8
//T&e action could not execute0 since t&e
user most 6as not lo""ed in
public final static Strin" FD3%/8
// T&e action execution 6as successful
but do not s&o6 a vie6.
public final static Strin" /D/-8
//T&e action execution 6as successful.
public final static Strin" SC((-SS8
//t&e lo"ic of t&e action is implemented
public Strin" execute:< t&ro6s -xception8
+

Implementing the 'tion interfae is optional. If 'tion is not implemented" the framework will
use refletion to look for an execute method. If there is no execute method and no other
method is speified in the onfiguration" the framework will throw an exeption.
The Struts2 'tion have introdued a simpler implementation approah of the ation lasses as
2O!O: 2lain Old !ava Ob+ets<. The most basi usage of an ation" is to perform work
with a sing!e resu!t a!wa#s $eing returned. It looks like/
public class /e64ction *
public Strin" execute:< t&ro6s -xception *
// do t&e 6or,
return "success"8
+
+
4ote that here the ation lass doesn6t extend any other lass or interfae. The method invoked in
the proessing of an ation is the ;exeute; method. The ;exeute; method has no parameter and
it returns a String ob+et. 1owever with struts 2 ations you an get different return types other
than the string ob+ets" by using helper interfaes available : 1elper interfae provides the
ommon results as onstants like ;success;" ;none;" ;error;" ;inut; and ;login;<.
The Action Class usually ats as a Model and exeutes a partiular business logi depending on
the Re3uest ob+et and the Input 2arameters. In earlier versions of Struts :before Struts 2.*<" an
'tion lass is supposed to extend the org.apache.struts.Action lass and has to override
the Action.execute() method whih takes four parameters.
#asially" ations are meant to proess various ob+ets like HttSer"let(e:uest"
HttSer"let(esonse. #ut here" our ation lass is not proessing any ob+et parameter. 1ere
one important issue arises ( how do you get aess to the ob+ets that you need to work withN
The answer lies in the ;inversion of ontrol; or ;dependeny in+etion; pattern.
To ro"ide a !oose!# cou!ed s#stem% )truts2 uses a techni(ue ca!!ed
deendenc# in8ection% or in"ersion of contro!. 0ependeny in+etion an be
implemented by onstrutor in+etion" interfae in+etion and setter in+etion. Struts2 uses setter
in+etion. This means that to have ob+ets available to the action% we need on!# to ro"ide
a setter method. There are a!so o$8ects such as the HttpServletRequest
that an be obtained by asking the Action!ontext or implementing ServletRe3uest'ware.
Implementing ServletRe3uest'ware is preferred. .or each of the non-$usiness o$8ects
there is a corresonding interface =known as an >aware? interface@
that the action is re(uired to im!ement.
To understand the inversion of ontrol better" let6s look at an example where the proessing of
the ation re3uires aess to the urrent re3uests 1ttpServletRe3uest ob+et.
The dependeny in+etion mehanism used in this example is inter&ace in4ection. 's the
name implies" with interfae in+etion there is an interfae that needs to be implemented. This
interfae ontains setter methods" whih in turn are used to provide data to the ation. In our
example we are using the ServletRequestAware interfae" here it is/
publi interfae ServletRe3uest'ware R
publi void
setServletRe3uest:1ttpServletRe3uest re3uest<S
T
-hen we implement this interfae" our simple ation gets modified a bit but now we have a
HttSer"er(e:uest ob+et to use.
public class /e64ction implements add.ependenc# *
private @ttpServlet$eMuest reMuest8
public void setServlet$eMuest:@ttpServlet$eMuest reMuest< *
t&is.reMuest = reMuest8
+
public Strin" execute:< t&ro6s -xception *
// do t&e 6or, usin" t&e reMuest
return "SC((-SS"8
+
+
In Struts2" an ation instane is reated for eah re3uest. It6s not shared and it6s disarded after
the re3uest has been ompleted.
Action +aings
The ation mapping an speify a set of result types" a set of exeption handlers" and an
intereptor stak. #ut" only the name attribute is re3uired. The other attributes an also be
provided at pakage sope. Speified through Struts.xml file.
The configuration for this action !ooks !ike thisA
<action name="ne6"
class="/e64ction" >
<result>vie6.jsp</result>
</action>

The UnameV attri$ute ro"ides the B72 information to e'ecute the action as
>Cnew.action?. The e'tension >.action? is configured in the >struts.roerties?
configuration fi!e.
The >c!ass? attri$ute ro"ides the fu!! ackage and c!ass name of the action
to $e e'ecuted.
)truts 2 rocesses an action c!ass as a +5,5 and ena$!es to return different
resu!ts deending on the outcome of the !ogic. To get different resu!ts% the
c!ass needs to get modified asA
class /e64ction *
public void Strin" execute:< t&ro6s -xception *
if : itso,:< < *
return "lo"in"8
+
else *
return "none"8
+++
0ere the c!ass ro"ides two different resu!ts% we ha"e to configure the
action tags of struts.'m! fi!e for each case. %odify the onfiguration as /
<action name="ne6"
class="/e64ction" >
<result>lo"in.jsp</result>
<result
name="none">none.jsp</result>
</action>
Struts 2 )edirect Action
In this setion" you will get familiar with struts 2 Rediret ation and learn to use it in the struts 2
appliation.
(edirect A&ter 6ost/ This post pattern is supported by Struts 2. This is a ommon pattern in web
appliation. In whih an ation is redireted to another ation. This is a ommon use to rediret
ation to display a page.
(edirect Action (esult/ This rediret pattern is supported by Struts 2. The Action+aer
provided by the Action+aerFactory is used to rediret the browser to a 8R& that invokes the
speified ation. =ou an see a simple implementation of this in the following struts 2
appliation.
(edirects *yna#ic 6ara#eters8 The ation(rediret result takes following parameters/
ation4ame
namespae
method
enode
parse
loation
prependServlet)ontext
Follow the stes to de"elo a (edirect Action exa#le8
Ste 1/ )reate the struts.xml file and add the following xml snippet in the struts.x#l file.
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<include file="strutsdefault.xml"/>
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">

<! $edirect 4ction >
<action name="s&o64jaxFo"in(ancelGorm">
<result>/pa"es/ajaxlo"in(ancel.jsp</result>
</action>
<action name="ajaxlo"in(ancel" class="net.roseindia.Fo"in">
<result name="input">/pa"es/ajaxlo"in(ancel.jsp</result>
<result name="error">/pa"es/ajaxlo"in(ancel.jsp</result>
<result name="cancel" t#pe="redirect">/pa"es/ajaxlo"in(ancel.jsp</resul
t>
<result>/pa"es/ajaxlo"insuccess.jsp</result>
</action>

<! 4dd actions &ere >
</package>
<! 4dd pac,a"es &ere >
</struts>
Ste 2 / )reate an input form.
a4axlogin!ancel.4s
<OP ta"lib prefix="s" uri="/strutsta"s"O>
<&tml>
<&ead>
<s:&ead t&eme="ajax" debu"="true"/>
</&ead>
<bod#>
<s:div id="lo"in.iv" t&eme="ajax">
<div st#le="6idt&: Q55px8borderst#le: solid">
<s:form action="ajaxlo"in(ancel" validate="true">
<tr>
<td colspan="2">
Fo"in
</td>
</tr>
<tr>
<td colspan="2">
<s:actionerror />
<s:fielderror />
</td>
<s:textfield name="username" label="Fo"in name"/>
<s:pass6ord name="pass6ord" label="!ass6ord"/>
<s:submit value="Submit" t&eme="ajax" tar"ets="lo"in.iv" notif#Topi
cs="/ajaxlo"in(ancel"/>
<s:submit action="s&o64jaxFo"in(ancelGorm" value="(ancel" onclic,="
form.onsubmit=null"/>

</s:form>
</div>
</s:div>
</bod#>
</&tml>
Ste > / )reate an 'tion lass.
)ogin.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util..ate8
/''
' <p> ;alidate a user lo"in. </p>
'/
public class Fo"in extends 4ctionSupport *
public Strin" execute:< throws -xception *
if:!"etCsername:<.eMuals:"4dmin"< HH !"et!ass6ord:<.eMuals:"4dmin"<<*
add4ction-rror:"%nvalid user name or pass6ord! !lease tr# a"ain!"
<8
return -$$D$8
+
if:"etCsername:<.eMuals:"4dmin"< HH "et!ass6ord:<.eMuals:"4dmin"<<*
return SC((-SS8
+else*
return /D/-8
+
+
// Csername propert#
/''
' <p>Gield to store Cser username.</p>
' <p/>
'/
private Strin" username = null8
/''
' <p>!rovide Cser username.</p>
'
' Preturn $eturns t&e Cser username.
'/
public Strin" "etCsername:< *
return username8
+
/''
' <p>Store ne6 Cser username</p>
'
' Pparam value T&e username to set.
'/
public void setCsername:Strin" value< *
username = value8
+
// Csername propert#
/''
' <p>Gield to store Cser pass6ord.</p>
' <p/>
'/
private Strin" pass6ord = null8
/''
' <p>!rovide Cser pass6ord.</p>
'
' Preturn $eturns t&e Cser pass6ord.
'/
public Strin" "et!ass6ord:< *
return pass6ord8
+
/''
' <p>Store ne6 Cser pass6ord</p>
'
' Pparam value T&e pass6ord to set.
'/
public void set!ass6ord:Strin" value< *
pass6ord = value8
+
+
Ste ? / )reate the appropriate validator as shown/
The validation.xml format is either <ActionClassName>validation.xml or
<ActionClassName><ActionAliasName>validation.xml.
)ogin2"alidation.x#l
<Ixml version="9.5" encodin"="CTGN"I>
<!.D(TE!- validators !C1F%(
"//DpenS#mp&on# 3roup//RAor, ;alidator 9.5.2//-/"
"&ttp://666.opens#mp&on#.com/x6or,/x6or,validator9.5.2.dtd">

<validators>
<field name="username">
<fieldvalidator t#pe="reMuiredstrin"">
<param name="trim">true</param>
<messa"e>Fo"in name is reMuired</messa"e>
</fieldvalidator>
</field>
<field name="pass6ord">
<fieldvalidator t#pe="reMuiredstrin"">
<param name="trim">true</param>
<messa"e>!ass6ord is reMuired</messa"e>
</fieldvalidator>
</field>
</validators>
-hen entered the orret user name and password then the user gets the a4axloginsuccess.4s
page displaying the entered text
a4axloginsuccess.4s
<&tml>
<&ead>
<title>Fo"in Success</title>
</&ead>
<bod#>
<p ali"n="center"><font color="=5555N5" siSe="T">Fo"in Successful !
</font></p>
<&9> Aelcome to <O=reMuest."et!arameter:"username"<O> </&9>
</bod#>
</&tml>
9utut8
-hen this appliation exeutes you get the following/
-hen you don6t fill any field and lik ;Submit; button" you get/
If you lik the ;)anel; button then rediret ation exeutes and provides/
Struts 2 $oin A!!lication
*e"eloing Struts 2 )ogin Alication
In this setion we are going to develop login appliation based on Struts 2 Framework. Our
urrent login appliation does not validate the user against the database. Instead login name and
password are validated against the hardode values :8ser/ 'dmin and 2assword/ 'dmin< in the
ations lass.
Wor7ing o& the alication
.. &ogin page is displayed to take the input.
2. 8ser enters user name and password and then liks on the ;&ogin; button.
J. 8ser validation is done in ation lass and if user enters 'dmin9'dmin in the user
name9password fields" then suess pages is displayed. Otherwise the error message is
displayed on the sreen.
Stes to de"eloe the alication
1ere are simple and easy steps to develop &ogin page in the using Struts 2 framework.
1. *e"elo )ogin For#
The H8I of the appliation onsists of login form :login.4s< and suess message page
:loginsuccess.4s<.
The login.4s is used to display the login page to the user. In our appliation it is saved in
;webappsIstruts2tutorialIpagesI; folder. 1ere is the ode of login.4s file/
EHI tagli/ re&ixJKsK uriJK-struts2tagsK HF
BhtmlC
BheadC
BtitleCStruts 2 &ogin 'ppliationFB9titleC
Blink hrefM;Bs/url valueM;-css-#ain.css;9C; relM;stylesheet; typeM;text9ss;9C
B9headC
BbodyC
Es8&or# actionJKdo)oginK #ethodJK69STKF
BtrC
Btd olspanM;2;C
&ogin
B9tdC
B9trC
BtrC
Btd olspanM;2;C
Es8actionerror -F
Es8&ielderror -F
B9tdC
B9trC
Es8text&ield na#eJKuserna#eK la/elJK)ogin na#eK-F
Es8assword na#eJKasswordK la/elJK6asswordK-F
Es8su/#it "alueJK)oginK alignJKcenterK-F
E-s8&or#F
B9bodyC
B9htmlC
2. The ode /
Es8actionerror -F
Es8&ielderror -F
displays ation errors and field validation errors.
3. The ode Es8&or# actionJKdo)oginK #ethodJK69STKF generates the html form for
the appliation.
The ode /
Es8text&ield na#eJKuserna#eK la/elJK)ogin na#eK-F
Es8assword na#eJKasswordK la/elJK6asswordK-F
generates &ogin 4ame and 2assword fields.
4. The submit button is generated through Es8su/#it "alueJK)oginK alignJKcenterK-F
ode.
-hen appliation is exeuted it generates the following html ode/
<&tml>
<&ead>
<title>Struts 2 Fo"in 4pplication!</title>
<lin, &ref="/struts2tutorial/css/main.css" rel="st#les&eet"
t#pe="text/css"/>

</&ead>
<bod#>
<form id="doFo"in" name="doFo"in" onsubmit="return true8"
action="/struts2tutorial/roseindia/doFo"in.action" met&od="!DST">
<table class="66GormTable">
<tr>
<td colspan="2">
Fo"in
</td>
</tr>
<tr>
<td class!"td#abel"><label for!"do#ogin$username" class!"label">
#ogin name%<&label>
<&td>
<td><input t'pe!"text" name!"username" value!"" id!"do#ogin$username"&>
<&td>
<&tr>
<tr>
<td class="tdFabel"><label for="doFo"inUpass6ord" class="label">
!ass6ord:</label></td>
<td><input t#pe="pass6ord" name="pass6ord" id="doFo"inUpass6ord"/>
</td>
</tr>
<tr>
<td colspan="2"><div ali"n="center"><input t#pe="submit"
id="doFo"inU5" value="Fo"in"/>
</div></td>
</tr>
</table></form>
</bod#>
</&tml>
5.
On viewing the above generated html ode you will find that Struts 2 automatially
generates form" html table" label for the html elements. This is the another great feature of
Struts as ompared to Struts ..x.
The loginsuccess.4s page displays the &ogin Suess message when user is
authentiated suessfully. 1ere is the ode of loginsuccess.4s file/
BhtmlC
BheadC
BtitleC&ogin SuessB9titleC
B9headC
BbodyC
Bp alignM;enter;CBfont olorM;W****@*; si,eM;>;C&ogin
SuessfulB9fontCB9pC
B9bodyC
B9htmlC

6.
7. *e"eloing Action !lass
4ow let6s develop the ation lass to handle the login re3uest. In Struts 2 it is not
neessary to implement the 'tion interfae" any 2O!O ob+et with exeute signature an
be used in Struts 2. The Struts 2 framework provides a base 'tionSupport lass to
implement ommonly used interfaes. In our ation lass :&ogin.+ava< we have
implemented 'tionSupport interfae. Our ;&ogin.+ava; is saved in the
;webappsIstruts2tutorialI-5#(I4FIsrI+avaInetIroseindia; diretoy. 1ere is the ode of
&ogin.+ava ation lass/

package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util..ate8
/''
' <p> ;alidate a user lo"in. </p>
'/
public class Fo"in extends 4ctionSupport *
public Strin" execute:< throws -xception *
S#stem.out.println:";alidatin" lo"in"<8
if:!"etCsername:<.eMuals:"4dmin"< HH !"et!ass6ord:<.eMuals:"4dmin"<<
*
add4ction-rror:"%nvalid user name or pass6ord! !lease tr# a"
ain!"<8
return -$$D$8
+else*
return SC((-SS8
+
+
// Csername propert#
/''
' <p>Gield to store Cser username.</p>
' <p/>
'/
private Strin" username = null8
/''
' <p>!rovide Cser username.</p>
'
' Preturn $eturns t&e Cser username.
'/
public Strin" "etCsername:< *
return username8
+
/''
' <p>Store ne6 Cser username</p>
'
' Pparam value T&e username to set.
'/
public void setCsername:Strin" value< *
username = value8
+
// Csername propert#
/''
' <p>Gield to store Cser pass6ord.</p>
' <p/>
'/
private Strin" pass6ord = null8
/''
' <p>!rovide Cser pass6ord.</p>
'
' Preturn $eturns t&e Cser pass6ord.
'/
public Strin" "et!ass6ord:< *
return pass6ord8
+
/''
' <p>Store ne6 Cser pass6ord</p>
'
' Pparam value T&e pass6ord to set.
'/
public void set!ass6ord:Strin" value< *
pass6ord = value8
+
+
@.
9. !on&iguring action #aing 0in struts.x#l1
4ow we will reate ation mapping in the struts.xml file. 1ere is the ode to be added in
the struts.xml/
Bation nameM;show)ogin;C
BresultC9pages9login.+spB9resultC
B9ationC
Bation nameM;do)ogin; lassM;net.roseindia.)ogin;C
Bresult nameM;input;C9pages9login.+spB9resultC
Bresult nameM;error;C9pages9login.+spB9resultC
BresultC9pages9loginsuess.+spB9resultC
B9ationC
.*. In the above mapping the ation ;show&ogin; is used to display the login page and
;do&ogin; validates the user using ation lass :&ogin.+ava<.
11.!SS &ile 0#ain.css1
This ss file is used to enhane the presentation of the login form. The #ain.css is saved
into ;IwebappsIstruts2tutorialIss; diretory.
1ere is the ode of #ain.css/
X)1'RS5T ;8TF(@;S
body R
font/ .2px verdana" arial" helvetia" sans(serifS
bakground(olor/WFFFFFFS
T
table.wwFormTable R
font/ .2px verdana" arial" helvetia" sans(serifS
border(width/ .pxS
border(olor/ W*J*S
border(style/ solidS
olor/ W2?2S
bakground(olor/ WadaS
width/ J*YS
margin(left/J>YS
margin(right/J>YS
margin(top/.>YS
T
table.wwFormTable th R
T
table.wwFormTable tr td R
bakground(olor/ WdfdS
margin/ >pxS
padding/ >pxS
T
.td&abel R
9Q
border(width/ .pxS
border(olor/ WafaS
border(style/ solidS
Q9
font(weight/ boldS
align/ topS
T
.label R
T
.error%essage R
olor/ redS
font(si,e/ *.@emS
T
Wheader0iv R
border(style/ solidS
border(width/ .px .px *pxS
border(olor/ blakS
padding/ >pxS
bakground(olor/ WGaGS
9Q height/ 22pxS Q9
height/ ..@emS
9Q margin(bottom/ .2pxS Q9
T
Wbutton#ar R
border(width/ *px .px .pxS
border(style/ solidS
border(olor/ blakS
olor/ whiteS
margin(bottom/ .2pxS
bakground(olor/ WGaGS
height/ ..7emS
padding/ >pxS
T
Wapp4ame R
olor/ whiteS
font(si,e/ ..@emS
T
WpageTitle R
font(si,e/ ..?emS
olor/ WdfdS
lear/ noneS
T
Wapp4ame" WpageTitle R
float/ rightS
T
Wmenu)ontainer R
float/ leftS
T
Wbranding)ontainer R
float/ right/
text(align/ rightS
T
In the next setion we will learn how to add validation to the login appliation.
Struts 2 Validation "xam!le
Validation )ogin alication
In this setion we will write the ode to validate the login appliation. 'fter ompleting this
setion you will be able to write validations for your Struts 2 pro+ets. The onepts defined in
this setion are so illustrative that a learner 3uikly develops his9her skills in Struts 2 framework.
Struts 2 is very elegant framework that provides a lot of funtionality to develop web based
appliations 3uikly. 1ere you will learn to write the form validation ode in Struts 2 very easily.
-e will add the form validation ode in our login appliation.
For validation the login appliation +ava sript an be added to the +sp page or in ation lass" but
Struts 2 provides another very easy method to validate your fields automatially. =ou an even
use the same onfiguration file to generate lient side sript : in next setion we will see how to
generate lient side validation ode<.
The Struts 2 validation framework uses xml based onfiguration file. The file name should be
EPour action classF 2"alidation.x#l. In our ase our ation lass name is &ogin.+ava" so our
validation onfiguration file will be )ogin2"alidation.x#l. The )ogin2"alidation.x#l will be
saved into ;we/asGstruts2tutorialGW,52'NFGsrcG4a"aGnetGroseindia; diretory. 1ere is the
ontent of )ogin2"alidation.x#l file/
<Ixml version="9.5" encodin"="CTGN"I>
<!.D(TE!- validators !C1F%(
"//DpenS#mp&on# 3roup//RAor, ;alidator 9.5.2//-/"
"&ttp://666.opens#mp&on#.com/x6or,/x6or,validator9.5.2.dtd">

<validators>
<field name!"username">
<fieldvalidator t'pe!"re(uiredstring">
<param name!"trim">true<&param>
<message>#ogin name is re(uired<&message>
<&fieldvalidator>
<&field>
<field name!"password">
<fieldvalidator t'pe!"re(uiredstring">
<param name!"trim">true<&param>
<message>)assword is re(uired<&message>
<&fieldvalidator>
<&field>
</validators>

In the above onfiguration file the field name orresponds to the 'tionForm properties. For the
userna#e and assword elements the re:uiredstring validation is applied and the message in
the E#essageF....E-#essageF tag is used to display the message if validation fails.
!o#iling the alication
To ompile the appliation go to ;IwebappsIstruts2tutorialI-5#(I4FIsr; diretory and type ant
ommand. The ant tool will ompile the appliation for you.
Adding the lin7 into index.ht#l
Finally we add the link in the index.html to aess the login form.
BulC
BliCBa hrefM;roseindia9show&ogin.ation;C&ogin 'ppliationB9aCB9liC
B9ulC
In the next setion we will run and test the appliation.
)unnin and *estin Struts 2 $oin a!!lication
(unning Struts 2 )ogin ,xa#le
In this setion we will run the example on Tomat 7.* server and hek how it works.
(unning To#cat
To run the Tomat" go to its bin diretory and then double lik on startup.bat. The startup.bat
will start the tomat.
Testing alication
To test the appliation type http/99loalhost/@*@*9struts2tutorial9. =our browser should show the
following sreen/

4ow lik on ;&ogin 'ppliation; link. Then your browser will display the &ogin page as shown
below/

4ow lik on the ;&ogin; button. 'ppliation will show the following error sreen/
4ow you enter the &ogin name ;'dmin; and lik on the ;&ogin; button" appliation will show
the following error/

4ow enter any password exept ;'dmin;" appliation will again show the error. This error is
atually generated in the 'tion lass.

4ow enter the valid password ;'dmin; and lik on ;&ogin; button. 4ow the appliation will
show you the welome message as shown below.

)ongratulationF 4ow you have suessfully developed and tested your Struts 2 &ogin
appliation. In the next setion we will show you how to add lient side !ava Sript validation
using Struts 2 Aalidation framework.
(lient Side %alidation in Struts 2 a!!lication
In this setion we will see how to write ode that will generate !ava Sript ode for lient side
validation. In the last setion we developed &ogin(validator.xml onfiguration file for defining
the server side validation. In this setion we will use the same &ogin(validator.xml file for
generating the lient side +ava sript.

*e"eloing $S6 ages
1ere is the ode of login +sp page :login)lientSideAalidation.+sp<
BYX taglib prefixM;s; uriM;9struts(tags; YC
BhtmlC
BheadC
BtitleCStruts 2 &ogin 'ppliationFB9titleC
Blink hrefM;Bs/url valueM;9ss9main.ss;9C; relM;stylesheet;
typeM;text9ss;9C
B9headC
BbodyC
Bs/form ationM;do&ogin)lientSideAalidation; methodM;2OST; "alidateJKtrueKC
BtrC
Btd olspanM;2;C
&ogin
B9tdC
B9trC
Bs/ationerror 9C
Bs/fielderror 9C
Bs/textfield nameM;username; labelM;&ogin name;9C
Bs/password nameM;password; labelM;2assword;9C
Bs/submit valueM;&ogin; alignM;enter;9C
B9s/formC
B9bodyC
B9htmlC
4ote that in the above ode we have +ust added "alidateJKtrueK in the Bs/form tag...C. This is
the only work we have to do and rest work is done by Struts 2 validator framework. The
validator framework generates !avaSript for validating the form at lient side.
!hanges in the struts.x#l
'dd the following ode into struts.xml file/
Bation nameM;show&ogin)lientSideAalidation;C
BresultC9pages9login)lientSideAalidation.+spB9resultC
B9ationC
Bation nameM;do&ogin)lientSideAalidation; lassM;net.roseindia.&ogin;C
Bresult nameM;input;C9pages9login)lientSideAalidation.+spB9resultC
Bresult nameM;error;C9pages9login)lientSideAalidation.+spB9resultC
BresultC9pages9loginsuess.+spB9resultC
B9ationC
The ation show)ogin!lientSideValidation displays login form while
do&ogin)lientSideAalidation handles the validation re3uest.
Adding the lin7 into index.ht#l
Finally we add the link in the index.html to aess the login form for testing lient side
validation.
BulC
BliCBa hrefM;roseindia9show&ogin)lientSideAalidation.ation;C&ogin 'ppliation :)lient Side
Aalidation<B9aCB9liC
B9ulC
Testing the !lient side "alidation
Start tomat and type http/99loalhost/@*@*9struts2tutorial9. =our browser should show the
following sreen/

4ow lik on ;&ogin 'ppliation :)lient Side Aalidation<; link. Then your browser will display
the &ogin page as shown below/

)lik on the ;&ogin; button without entering anything. !ava Sript will show the error message
as shown below/

4ow enter the ;&ogin 4ame; and lik on the ;&ogin; button" appliation will show error as
shown below/

,xa#ining the $a"a Scrit code generated
The following html ode is generated by the framework/
BhtmlC
BheadC
BtitleCStruts 2 &ogin 'ppliationFB9titleC
Blink hrefM;9struts2tutorial9ss9main.ss; relM;stylesheet;
typeM;text9ss;9C
B9headC
BbodyC
Bsript srM;9struts2tutorial9struts9xhtml9validation.+s;CB9sriptC
Bform namespaeM;9roseindia; idM;do&ogin)lientSideAalidation; nameM;do&ogin)lientSideAalidation;
onsu/#itJKreturn "alidateFor#Qdo)ogin!lientSideValidation01RK
ationM;9struts2tutorial9roseindia9do&ogin)lientSideAalidation.ation; methodM;2OST;C
Btable lassM;wwFormTable;C
BtrC
Btd olspanM;2;C
&ogin
B9tdC
B9trC
BtrC
Btd lassM;td&abel;CBlabel forM;do&ogin)lientSideAalidationZusername; lassM;label;C&ogin
name/B9labelCB9tdC
Btd
CBinput typeM;text; nameM;username; valueM;; idM;do&ogin)lientSideAalidationZusername;9C
B9tdC
B9trC
BtrC
Btd lassM;td&abel;CBlabel forM;do&ogin)lientSideAalidationZpassword;
lassM;label;C2assword/B9labelCB9tdC
Btd
CBinput typeM;password; nameM;password; idM;do&ogin)lientSideAalidationZpassword;9C
B9tdC
B9trC
BtrC
Btd olspanM;2;CBdiv alignM;enter;CBinput typeM;submit; idM;do&ogin)lientSideAalidationZ*;
valueM;&ogin;9C
B9divCB9tdC
B9trC

B9tableCB9formC


Bsript typeM;text9+avasript;C
funtion validateFormZdo&ogin)lientSideAalidation:< R
form M doument.get5lement#yId:;do&ogin)lientSideAalidation;<S
lear5rror%essages:form<S
lear5rror&abels:form<S
var errors M falseS
99 field name/ username
99 validator name/ re3uiredstring
if :form.elementsO6username6P< R
field M form.elementsO6username6PS
var error M ;&ogin name is re3uired;S
if :field.value FM null [[ :field.value MM ;; \\ field.value.replae:9]Is^\Is^_9g";;<.length MM *<< R
add5rror:field" error<S
errors M trueS
T
T
99 field name/ password
99 validator name/ re3uiredstring
if :form.elementsO6password6P< R
field M form.elementsO6password6PS
var error M ;2assword is re3uired;S
if :field.value FM null [[ :field.value MM ;; \\ field.value.replae:9]Is^\Is^_9g";;<.length MM *<< R
add5rror:field" error<S
errors M trueS
T
T
return FerrorsS
T
B9sriptC
B9bodyC
B9htmlC
In the above ode you an see the !avaSript ode and funtion
validateFormZdo&ogin)lientSideAalidation:< whih is generated for lient side validation
Validating Struts 2 )ogin Alication using Annotations
In this setion we are going to validate our login appliation using 'nnotations in 'tion lass.
Our urrent login appliation does not validate the user against the database. Instead login name
and passwords are validated against the hardode values :8ser/ Admin and 2assword/ Admin< in
the ations lass.
Wor7ing o& the alication
1. &ogin page is displayed to take the inputs.
2. 8ser enters user name and password and then liks on the ;&ogin; button.
J. 8ser validation is done in ation lass and if user enters 'dmin9'dmin in the user
name9password fields" then suess pages is displayed. Otherwise the error message is
displayed on the sreen.
Stes to de"elo the alication
1ere are simple and easy steps to develop &ogin page in the using Struts 2 framework.
1. *e"elo )ogin For#
The H8I of the appliation onsists of login form :log2in.4s< and suess message page
:loginsuccess.4s< .
The log2in.4s is used to display the login page to the user. In our appliation it is saved
in ;webappsIstruts2tutorialIpagesI; folder. 1ere is the ode of log2in.4s file/

EHI tagli/ re&ixJKsK uriJK-struts2tagsK HF
BhtmlC
BheadC
BtitleCStruts 2 &ogin 'ppliationFB9titleC
Blink hrefM;Bs/url valueM;-css-#ain.css;9C; relM;stylesheet; typeM;text9ss;9C
B9headC
BbodyC
Es8&or# actionJKAnnotationActionK #ethodJK69STK "alidateJKtrueKF
BtrC
Btd olspanM;2;C
&ogin
B9tdC
B9trC
BtrC
Btd olspanM;2;C
Es8actionerror -F
Es8&ielderror -F
B9tdC
B9trC
Es8text&ield na#eJKuserna#eK la/elJK)ogin na#eK-F
Es8assword na#eJKasswordK la/elJK6asswordK-F
Es8su/#it "alueJK)oginK alignJKcenterK-F
E-s8&or#F
B9bodyC
B9htmlC
.. The ode /
Es8actionerror -F
Es8&ielderror -F
displays ation errors and field validation errors.
The ode Es8&or# actionJKAnnotationActionK #ethodJK69STK "alidateJKtrueKF
generates the html form for the appliation.
The ode /
Es8text&ield na#eJKuserna#eK la/elJK)ogin na#eK-F
Es8assword na#eJKasswordK la/elJK6asswordK-F
generates &ogin 4ame and 2assword fields.
The submit button is generated through Es8su/#it "alueJK)oginK alignJKcenterK-F
ode.
The loginsuccess.4s page displays the &ogin Suess message when user is
authentiated suessfully. 1ere is the ode of loginsuccess.4s file/
BhtmlC
BheadC
BtitleC&ogin SuessB9titleC
B9headC
BbodyC
Bp alignM;enter;CBfont olorM;W****@*; si,eM;>;C&ogin
SuessfulB9fontCB9pC
B9bodyC
B9htmlC


2. *e"eloing Action class 0using Annotations to "alidate )ogin &or#s1
4ow let6s develop the ation lass to handle the login re3uest. The Struts 2 framework
provides a base 'tionSupport lass to implement ommonly used interfaes. In our
ation lass :AnnotationAction.4a"a< we have extended ActionSuort lass and
imported the com.opens#mp&on#.x6or,2.validator.annotations pac,a"e .
For validating the login appliation +ava sript an be added to the +sp page or in ation
lass" but Struts 2 provides another very easy method to validate your form fields using
annotations in the ation lass.
Two annotations are needed"
.. The IValidation annotation tells to Struts that ation in this lass might need to be
validated.
2. The I(e:uiredStringValidator annotation is used for the text input to hold a
singular value.
Rest of the are is taken by the framework.
Our ;4nnotation4ction; lass is saved in the ;webappsIstruts2tutorialI-5#(
I4FIsrI+avaInetIroseindia; diretoy. 1ere is the ode of 4nnotation4ction.+ava ation
lass/
In this lass we will write the ode to validate the login page.
AnnotationAction.*ava
package net.roseindia8

import com.opens#mp&on#.x6or,2.4ctionSupport8
import com.opens#mp&on#.x6or,2.validator.annotations.'8

P;alidation

public class 4nnotation4ction extends 4ctionSupport *

private Strin" username = null8

private Strin" pass6ord = null8

P$eMuiredStrin";alidator:messa"e="Suppl# name"<

public Strin" "etCsername:< *
return username8
+


public void setCsername:Strin" value< *
username = value8
+


P$eMuiredStrin";alidator:messa"e="Suppl# pass6ord"<

public Strin" "et!ass6ord:< *

return pass6ord8
+


public void set!ass6ord:Strin" value< *

pass6ord = value8
+



public Strin" execute:< throws -xception *

S#stem.out.println:";alidatin" lo"in"<8
if:!"etCsername:<.eMuals:"4dmin"< HH !"et!ass6ord:<.eMuals:"4dmin"<<*
add4ction-rror:"%nvalid user name or pass6ord! !lease tr# a"ain!"<8

return -$$D$8

+
else*

return SC((-SS8
+

+
+

1. !on&iguring action #aing 0in struts.x#l1
4ow we will reate ation mapping in the struts.xml file. 1ere is the ode to be added in
the struts.xml/
Bation nameM;&ogin'nnotation;C
BresultC9pages9log(in.+spB9resultC
B9ationC
Bation nameM;'nnotation'tion;
lassM;net.roseindia.'nnotation'tion;C
Bresult nameM;input;C9pages9log(in.+spB9resultC
Bresult nameM;error;C9pages9log(in.+spB9resultC
BresultC9pages9loginsuess.+spB9resultC
B9ationC
2. In the above mapping the ation ;&ogin'nnotation; is used to display the login page and
;'nnotation'tion; validates the user using ation lass :4nnotation4ction.+ava<.
3. !SS &ile 0#ain.css1
This ss file is used to enhane the presentation of the login form. The #ain.css is saved
into ;IwebappsIstruts2tutorialIss; diretory.
1ere is the ode of #ain.css/
X)1'RS5T ;8TF(@;S
body R
font/ .2px verdana" arial" helvetia" sans(serifS
bakground(olor/WFFFFFFS
T
table.wwFormTable R
font/ .2px verdana" arial" helvetia" sans(serifS
border(width/ .pxS
border(olor/ W*J*S
border(style/ solidS
olor/ W2?2S
bakground(olor/ WadaS
width/ J*YS
margin(left/J>YS
margin(right/J>YS
margin(top/.>YS
T
table.wwFormTable th R
T
table.wwFormTable tr td R
bakground(olor/ WdfdS
margin/ >pxS
padding/ >pxS
T
.td&abel R
9Q
border(width/ .pxS
border(olor/ WafaS
border(style/ solidS
Q9
font(weight/ boldS
align/ topS
T
.label R
T
.error%essage R
olor/ redS
font(si,e/ *.@emS
T
Wheader0iv R
border(style/ solidS
border(width/ .px .px *pxS
border(olor/ blakS
padding/ >pxS
bakground(olor/ WGaGS
9Q height/ 22pxS Q9
height/ ..@emS
9Q margin(bottom/ .2pxS Q9
T
Wbutton#ar R
border(width/ *px .px .pxS
border(style/ solidS
border(olor/ blakS
olor/ whiteS
margin(bottom/ .2pxS
bakground(olor/ WGaGS
height/ ..7emS
padding/ >pxS
T
Wapp4ame R
olor/ whiteS
font(si,e/ ..@emS
T
WpageTitle R
font(si,e/ ..?emS
olor/ WdfdS
lear/ noneS
T
Wapp4ame" WpageTitle R
float/ rightS
T
Wmenu)ontainer R
float/ leftS
T
Wbranding)ontainer R
float/ right/
text(align/ rightS
T
!o#iling the alication
To ompile the appliation go to ;IwebappsIstruts2tutorialI-5#(I4FIsr; diretory and type ant
ommand. The ant tool will ompile the appliation for you.
Adding the lin7 into index.ht#l
Finally we add the link in the index.html to aess the login form.
BulC
BliCBa hrefM;roseindia9&ogin'nnotation.ation;C'tion 'nnotation 5xampleB9aCB9liC
B9ulC
9utut8
'& you clic7 )ogin /utton without &illing the &ields% you will get the outut ages as 8
'& you &ill only the K)ogin na#eK &ield and clic7 )ogin /utton without &illing the next &ields%
you will get the outut ages as 8
'& you &ill the wrong in&or#ation and clic7 the )ogin /utton% you will get the outut
ages as 8
'& you &ill the correct in&or#ation and clic7 the )ogin /utton% you will get the outut
ages as 8
Struts 2 Validation
8ser input validations are integral part of any web appliation. -ith the release of Struts 2"
validation are now muh easier and robust. Struts 2 support '+ax based and even server side
validations. Struts 2.* ation relies on the $-ork validation framework. The $-ork framework
runs the validation rules before exeuting the ation. Struts 2 also provides the faility to define
validation rules in your ation lass using !ava > annotations.
1. Struts 2 Validation 0'nt Validator 1
Struts 2 Framework provides in(built validation funtions to validate user inputs. These
validation funtions are suffiient for any normal web appliation.
2. Struts 2 (e:uiredString "alidator
This setion disusses Re3uiredString validator of Struts 2 framework.
Re3uiredStringAalidator heks the String field is non(null and its length is C *. :i.e. it
isn6t ;;<.

3. Struts 2 dou/le "alidator
The 0ouble validator of Struts 2 Framework heks if the given input is double or not. If
the input is not double" it generates the error message. 0ouble validator an also be used
to hek the input range.

4. Struts 2 *ate Validator
The 0ate validator in the Struts 2 Framework heks whether the supplied date lies
within a speifi range or not. If the value supplied does not lie in the speified range" it
generates an error message.

5. Struts 2 ,2#ail Validator
The email validator in Struts 2 Framework heks whether a given String field is empty
or not and ontains a valid email address or not. If the entered value does not math with
the email type" then the e(mail validator generates an error message.

6. Struts 2 3rl Validator
The 8R&Aalidator of Struts 2 Framework heks whether the String ontained within the
given field is a valid 8R& or not. If the entered value is not a valid 8R&" it generates an
error message.

7. Validations using Struts 2 Annotations
In this setion we are going to validate our login appliation using 'nnotations in 'tion
lass. Our urrent login appliation does not validate the user against the database.
Instead login name and passwords are validated against the hardode values :8ser/
Admin and 2assword/ Admin< in the ation
Struts 2 Validation +Int Validator,
Struts 2 Framework provides in(built validation funtions to validate user inputs. These
validation funtions are suffiient for any normal web appliation. In some ases these standard
set of validation funtions are not suffiient to validate omplex business logi. To validate
omplex business logi" Struts 2 validation framework an be extended to develop ustom
validation funtions.
This setion disusses all the validation funtions available with Struts 2 framework. Subse3uent
setions of the tutorials disuss these validation funtions with examples.
Validation (ules
Aalidation rules are an integral part of Struts 2 appliations" where rules to validating partiular
user inputs are stored. Struts 2 validation framework validates user input against the defined
rules.
The validation rules an be speified/
.. 2er 'tion lass/ 'tion4ame(validation.xml
2. 2er 'tion alias/ 'tion4ame(alias(validation.xml
J. Inheritane hierarhy and interfaes are implemented by 'tion lass. The $-ork
searhes up the inheritane tree of the ation to find default validations for parent lasses
of the ation and interfaes implemented.
?. 8sing !ava > annotations.
Struts 2 de&ault "alidation &unctions
Following field validators are part of Struts 2 framework/
.. )onversion Aalidator
2. 0ate Aalidator
J. 0ouble Aalidator
?. 5mail Aalidator
>. 5xpression Aalidator
7. Feldexpression Aalidator
G. Int Aalidator
@. Regex Aalidator
L. Re3uired Aalidator
.*. Re3uiredstring Aalidator
... Stringlength Aalidator
.2. 8R& Aalidator
.J. Aisitor Aalidator
3sing Struts 2 'nt Validator
Following example disusses the use of Int Aalidator to validate integer input by user. 1ere are
the steps to develop Int validator example/
Ste 1/ )reate the xml file and adds the following xml snippet in the struts.x#l file.
struts.x#l
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">

<! 4dd actions &ere >
<! int validation >
<action name="int;alidation" class="net.roseindia./um4ction">
<result name="input">/pa"es/int%nputGorm.jsp</result>
<result name="error">/pa"es/int%nputGorm.jsp</result>
<result>/pa"es/intSuccess.jsp</result>
</action>
<! 4dd actions &ere >
</package>
<! 4dd pac,a"es &ere >
</struts>
Ste 2 / )reate the input form.
int'nutFor#.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>%nput form</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
<s:&ead/>
</&ead>
<bod#>

<s:form met&od="!DST" action="int;alidation">
</td>
</tr>
<s:textfield label="-nter /umber" name="userinput" />
<s:submit />
</s:form>
</bod#>
</&tml>
Ste > / )reate the 'tion lass.
Nu#Action.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class /um4ction extends 4ctionSupport*

private int userinput=58

public Strin" execute:< throws -xception*
/' if :"etCserinput:< >= 95 77 "etCserinput:< <= N5<*
return SC((-SS8
+
else*
return -$$D$8
+
'/
return SC((-SS8
+
public void setCserinput:int userinput<*
this.userinput = userinput8
+
public int "etCserinput:<*
return userinput8
+
+
Ste ? / )reate the validations.
The validation.xml format is either <ActionClassName>validation.xml or
<ActionClassName><ActionAliasName>validation.xml.
Write "alidation rule
The following validation rule file defines the rules to hek the input range. The int Field
Aalidator heks whether the given integer is within a ertain range or not. If an integer is within
a ertain range then you +umped into the intSuess.+sp page. Otherwise it displays the given
message in the xml file :Nu#/er needs in /etween 1; and C;<. The int validator takes the
following parameters/
field4ame ( The field name whih is to be validated. Re3uired if using 2lain(Aalidator
Syntax otherwise not re3uired
min ( This is the minimum value :if none is speified" it will not be heked<.
max ( This is the maximum value :if none is speified" it will not be heked<.
4um'tion(validation.xml
<Ixml version="9.5" encodin"="CTGN"I>
<!.D(TE!- validators !C1F%(
"//DpenS#mp&on# 3roup//RAor, ;alidator 9.5.2//-/"
"&ttp://666.opens#mp&on#.com/x6or,/x6or,validator9.5.2.dtd">

<validators>
<field name="userinput">
<fieldvalidator t#pe="int">
<param name="min">95</param>
<param name="max">N5</param>
<messa"e>/umber needs to bet6een )*min+ and )*max+ </messa"e>
</fieldvalidator>
</field>
</validators>
-hen the given number is within .* and @* then the intSuccess.4s page displays the inputted
number with ;)orret Input 4umber; message.
intSuccess.4s
<OPpa"e lan"ua"e="java" O>
<&tml>
<&ead>
<title>(orrect entr#</title>
</&ead>
<bod#>
<b>(orrect %nput /umber :</b><O=reMuest."et!arameter:"userinput"< O>
</bod#>
</&tml>
9utut8
-hen this appliation exeutes you get the following/
If you enter the wrong data or text then you get/
-hen you fill a number 6>*6
Then you get/
Struts 2 )e-uiredStrin %alidator
This setion disusses Re3uiredString validator of Struts 2 framework. Re3uiredStringAalidator
heks the String field is not(null and its length is C *. :i.e. it isn6t ;;<. The ;trim; parameter
determines the String before performing the length hek. If unspeified" the String will be
trimmed.
If user does not enter anything in the input filed and submits the forms" re3uired String validator
will generate error message. Then the error message is displayed to user.
This example demonstrates how to use Struts 2 Re3uiredString validation with a simple data
entry form where user is prompted to enter his9her user number. Follow the following steps to
develop the example appliation/
Ste 1/ )reate the xml file and add the following xml snippet in the struts.x#l file.
struts.x#l
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">

<! 4dd actions &ere >
<! strin" validation >
<action name="strin";alidation" class="net.roseindia.Strin";aFidation4cti
on">
<result name="input">/pa"es/strin"%nputGorm.jsp</result>
<result name="error">/pa"es/strin"%nputGorm.jsp</result>
<result>/pa"es/strin"Success.jsp</result>
</action>
<! 4dd actions &ere >
</package>
<! 4dd pac,a"es &ere >
</struts>
Ste 2 / )reate the input form.
string'nutFor#.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>%nput form</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
<s:&ead/>
</&ead>
<bod#>

<s:form met&od="!DST" action="strin";alidation">
</td>
</tr>
<s:textfield label="-nter Cser /umber" name="username" maxlen"t&="95" />
<s:submit />
</s:form>
</bod#>
</&tml>
Ste > / )reate the 'tion lass.
StringVa)idationAction.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class Strin";aFidation4ction extends 4ctionSupport*
private Strin" username8
public Strin" execute:< throws -xception*
if :"etCsername:< != null<*
return SC((-SS8
+
else*
return -$$D$8
+
+
public void setCsername:Strin" username<*
this.username = username8
+
public Strin" "etCsername:<*
return username8
+
+
Ste ? / )reate the validators.
The validation.xml format is either <ActionClassName>validation.xml or
<ActionClassName><ActionAliasName>validation.xml.
(e:uiredString "alidator8 Re3uiredStringAalidator heks the String field is not(null and it has
a length C *. :i.e. it isn6t ;;<. The ;trim; parameter determines the String before performing the
length hek. If unspeified" the String will be trimmed. If any string inputted in the text field
then you +umped into the stringSuccess.4s page. Otherwise" it displays the given message in the
xml file :3ser Na#e is re:uired<. The Re3uiredString validator takes the following parameters/
field4ame ( This is the field name that has to validate. Re3uired if using 2lain(Aalidator
Syntax otherwise not re3uired.
trim ( This is the field name of value before validating :default is true<.
StringVa)idationAction2"alidation.x#l
<Ixml version="9.5" encodin"="CTGN"I>
<!.D(TE!- validators !C1F%(
"//DpenS#mp&on# 3roup//RAor, ;alidator 9.5.2//-/"
"&ttp://666.opens#mp&on#.com/x6or,/x6or,validator9.5.2.dtd">

<validators>
<field name="username">
<fieldvalidator t#pe="reMuiredstrin"">
<param name="trim">true</param>
<messa"e>Cser /ame is reMuired</messa"e>
</fieldvalidator>
</field>
</validators>
-hen any string that have to be inputted by you in the text field then you must have to +ump into
stringSuccess.4s page and displays your inputted string with ;-elome to Ainod ;message.
stringSuccess.4s
<OPpa"e lan"ua"e="java" O>
<&tml>
<&ead>
<title>(orrect entr#</title>
</&ead>
<bod#>
<b>Aelcome to </b><O=reMuest."et!arameter:"username"< O>!
</bod#>
</&tml>
9utut8
-hen this appliation exeutes" you get the following/
-hen you fill the following string as 6Ainod Kumar6
Then you get/
Struts 2 dou.le %alidator
The 0ouble validator of Struts 2 Framework heks if the given input is double or not. If the
input is not double" it generates the error message. 0ouble validator an also be used to hek the
input range. This example is a demonstration to use double validator hek the input range.
Follow the steps to develop double range validator example/
Ste 1/ )reate the struts.xml file and add the following xml snippet in the struts.x#l file.
struts.x#l
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">

<! 4dd actions &ere >
<! double validation >
<action name="double;alidation" class="net.roseindia..ouble;aFidation4cti
on">
<result name="input">/pa"es/double%nputGorm.jsp</result>
<result name="error">/pa"es/double%nputGorm.jsp</result>
<result>/pa"es/doubleSuccess.jsp</result>
</action>
<! 4dd actions &ere >
</package>
<! 4dd pac,a"es &ere >
</struts>
Ste 2 / )reate the input form.
dou/le'nutFor#.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>%nput form</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
<s:&ead/>
</&ead>
<bod#>

<s:form met&od="!DST" action="double;alidation">
</td>
</tr>
<s:textfield label="-nter Total !ercenta"e Bar,s" name="percenta"emar,s"
maxlen"t&="95" />
<s:submit />
</s:form>
</bod#>
</&tml>
Ste > / )reate the 'tion lass.
*ou/leVa)idationAction.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class .ouble;aFidation4ction extends 4ctionSupport*
private double percenta"emar,s8
public Strin" execute:< throws -xception*

return SC((-SS8
/'/'if :"et!ercenta"emar,s:< > 25.9 77 "et!ercenta"emar,s:< < T5.9<*
return SC((-SS8
+
else*
return -$$D$8
+
'/
+
public void set!ercenta"emar,s:double percenta"emar,s<*
this.percenta"emar,s = percenta"emar,s8
+
public double "et!ercenta"emar,s:<*
return percenta"emar,s8
+
+
Ste ? / )reate the validators.
The validation.xml format is either <ActionClassName>validation.xml or
<ActionClassName><ActionAliasName>validation.xml.
*ou/le "alidator8 This Field Aalidator heks" if the given number is double and speified
within the speified range. If your inputted text is valid or within speified range then you +ump
into the dou/leSuccess.4s page. Otherwise" it displays the given message in the xml file
:6ercentage #ar7s need to /etween 2;.1 and @;.1<. The double validator takes the following
parameters/
field4ame ( This is the field name of validator that have to validate. Re3uired if using
int(Aalidator Syntax otherwise not re3uired
minInlusive ( This is the minimum inlusive value as FloatAalue format speified by
!ava language :if none is speified" it will be heked<
maxInlusive ( This is the maximum inlusive value as FloatAalue format speified by
!ava language :if none is speified" it will be heked<
min5xlusive ( This is the minimum exlusive value as FloatAalue format speified by
!ava language :if none is speified" it will be heked<
max5xlusive ( This is the maximum exlusive value as FloatAalue format speified by
!ava language :if none is speified" it will be heked<
*ou/leVa)idationAction2"alidation.x#l
<Ixml version="9.5" encodin"="CTGN"I>
<!.D(TE!- validators !C1F%(
"//DpenS#mp&on# 3roup//RAor, ;alidator 9.5.2//-/"
"&ttp://666.opens#mp&on#.com/x6or,/x6or,validator9.5.2.dtd">

<validators>
<field name="percenta"emar,s">
<fieldvalidator t#pe="double">
<param name="min%nclusive">25.9</param>
<param name="max%nclusive">T5.9</param>
<messa"e>!ercenta"e mar,s need to bet6een
)*min%nclusive+ and )*max%nclusive+</messa"e>
</fieldvalidator>
</field>
</validators>
-hen any double value is within speified range then you must +ump into dou/leSuccess.4s
page and it displays your inputted double value with ;'ggregate Total %arks/ ;message.
stringSuccess.4s
<OPpa"e lan"ua"e="java" O>
<&tml>
<&ead>
<title>(orrect entr#</title>
</&ead>
<bod#>
<b>4""re"ate Total Bar,s: </b><O=reMuest."et!arameter:"percenta"emar,s"< O>O
</bod#>
</&tml>
9utut8
-hen this appliation exeutes" you get the following/
If you enter the wrong data or text then you get/
-hen you fill a number 627..*>6
Then you get/
Struts 2 Date Validator
The 0ate validator in the Struts 2 Framework heks whether the supplied date lies within a
speifi range or not. If the value supplied does not lie in the speified range" it generates an
error message.
The error message is supplied between the BmessageC B9messageC tag. The following example
demonstrates how to use the date validator to hek the input range.
S N9T,8 If date onverter is not speified then =Wor75asic!on"erter will kik in to do the
date onversion" whih by default uses the .ate.S@D$T format :using a programmatially
speified loale else falling bak to the system default loale<.T
Follow the steps to develop the date range validator /
Ste 1/ )reate the struts.xml file and add the following xml snippet in the struts.x#l file.
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">

<! 4dd actions &ere >
<! date validation >
<action name="date;alidation">
<result>/pa"es/date%nputGorm.jsp</result>
</action>
<action name="date;alidation9" class="net.roseindia..ate;aFidation4ction">
<result name="input">/pa"es/date%nputGorm.jsp</result>
<result name="error">/pa"es/date%nputGorm.jsp</result>
<result>/pa"es/dateSuccess.jsp</result>
</action>
<! 4dd actions &ere >
</package>
<! 4dd pac,a"es &ere >
</struts>
Ste 2 / )reate the input +sp form i.e.
date'nutFor#.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>%nput form</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
<s:&ead/>
</&ead>
<bod#>

<s:form met&od="!DST" action="date;alidation9">
</td>
</tr>
<s:textfield label="-nter 2oinin" .ate of -mplo#ee" name="joinin"date"/>
<s:submit />
</s:form>
</bod#>
</&tml>
Ste > / )reate an 'tion lass.
*ateVa)idationAction.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import com.opens#mp&on#.x6or,2.'8
import java.util.'8
import java.text.'8
public class .ate;aFidation4ction extends 4ctionSupport implements ;alidateab
le *
private .ate joinin"date=null8

public void set2oinin"date:.ate joinin"date<*
this.joinin"date = joinin"date8
+
public .ate "et2oinin"date:<*
return joinin"date8
+
+
Ste ? / )reate a 0ate validator with in an xml file/
The validation.xml format is either <ActionClassName>validation.xml or
<ActionClassName><ActionAliasName>validation.xml.
*ate "alidator8 This Field Aalidator heks if the date supplied is within a speifi range. If it
is valid and lies within the speified range then you are sent to the dateSuccess.4s page.
Otherwise" it displays the message given in the xml file :e.g. $oining date #ust /e sulied
/etween ;1-;1-1DD; and ;1-;1-2;;;.<. The date validator takes the following parameters/
field4ame ( This is the field name of the validator.
( Re3uired if working with 2lain Aalidator Syntax.
min ( This is the min date range. If not speified" it will not be heked.
max ( This is the max date range. If not speified" it will not be heked.
*ateVa)idationAction2"alidation.x#l
<Ixml version="9.5" encodin"="CTGN"I>
<!.D(TE!- validators !C1F%(
"//DpenS#mp&on# 3roup//RAor, ;alidator 9.5.2//-/"
"&ttp://666.opens#mp&on#.com/x6or,/x6or,validator9.5.2.dtd">

<validators>
<field name="joinin"date">
<fieldvalidator t#pe="date">
<param name="min">59/59/9??5</param>
<param name="max">59/59/2555</param>
<messa"e>2oinin" date must be supplied bet6een )*min+ and )
*max+</messa"e>
</fieldvalidator>
</field>
</validators>
-hen any date that has to be passed in the text field by the user is orret then dateSuccess.4s
page is displayed as shown below/
;,#loyee $oining *ate/ .29..9.LL@ ; message.
dateSuccess.4s
<OPpa"e lan"ua"e="java" O>
<&tml>
<&ead>
<title>(orrect entr#</title>
</&ead>
<bod#>
<b>-mplo#ee 2oinin" .ate: </b><O=reMuest."et!arameter:"joinin"date"< O>
</bod#>
</&tml>
9utut8
-hen this appliation exeutes" the following page is reieved/
If you enter the wrong data or text then you get/
If you enter the date below the range/
If you enter the date out of the range" then you get the output as/
If you enter the date lying between the speified range/
Then you get the output message as shown/
Struts 2 "-mail Validator
The email validator in Struts 2 Framework heks whether a given String field is empty or not
and ontains a valid email address or not. If the entered value does not math with the email type
then the e(mail validator generates an error message.
The error message is supplied between the BmessageC B9messageC tag. The following example
demonstrates how to use an email validator to hek the entered value.
Follow the steps to develop the email validator example/
Ste 1/ )reate the struts.xml file and add the following xml snippet in the struts.x#l file.
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">

<! 4dd actions &ere >
<! -mail validation >
<action name="email;alidation">
<result>/pa"es/email%nputGorm.jsp</result>
</action>
<action name="email;alidation9" class="net.roseindia.-mail;aFidation4ctio
n">
<result name="input">/pa"es/email%nputGorm.jsp</result>
<result name="error">/pa"es/email%nputGorm.jsp</result>
<result>/pa"es/emailSuccess.jsp</result>
</action>
<! 4dd actions &ere >
</package>
<! 4dd pac,a"es &ere >
</struts>

Ste 2 / )reate an input +sp form. as shown below/
e#ail'nutFor#.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>-mail input form</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
<s:&ead/>
</&ead>
<bod#>

<s:form met&od="!DST" action="email;alidation9">
</td>
</tr>
<s:textfield label="-nter -mail 4ddress" name="m#-mail" />
<s:submit />
</s:form>
</bod#>
</&tml>
Ste > / )reate an 'tion lass.
,#ailVa)idationAction.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class -mail;aFidation4ction extends 4ctionSupport *
private Strin" m#-mail8
public void setB#-mail:Strin" m#-mail<*
this.m#-mail = m#-mail8
+
public Strin" "etB#-mail:<*
return m#-mail8
+
+
Ste ? / )reate an e(mail validator as/.
The validation.xml format is either <ActionClassName>validation.xml or
<ActionClassName><ActionAliasName>validation.xml.
e#ail "alidator 8
This Field Aalidator heks whether a given String field is empty or not and ontains a valid
email address or not. If it has valid email type then the user is sent to the e#ailSuccess.4s page.
Otherwise" it displays the message given in the xml file :e.g. 6lease enter a "alid e#ail.<.
The email validator takes the following parameters/
field4ame ( This is the field name of validator that validates. It is re3uired only if the
user is using 2lain(Aalidator Syntax .
,#ailVa)idationAction2"alidation.x#l
<Ixml version="9.5" encodin"="CTGN"I>
<!.D(TE!- validators !C1F%(
"//DpenS#mp&on# 3roup//RAor, ;alidator 9.5.2//-/"
"&ttp://666.opens#mp&on#.com/x6or,/x6or,validator9.5.2.dtd">

<validators>
<field name="m#-mail">
<fieldvalidator t#pe="email">
<messa"e>!lease enter a valid email</messa"e>
</fieldvalidator>
</field>
</validators>
-hen the orret email address is entered then the user gets the e#ailSuccess.4s page
e#ailSuccess.4s
<OPpa"e lan"ua"e="java" O>
<&tml>
<&ead>
<title>(orrect entr#</title>
</&ead>
<bod#>
<b>Aelcome to </b><O=reMuest."et!arameter:"m#-mail"< O>!
</bod#>
</&tml>
9utut8
-hen this appliation exeutes the user gets the following output /
If you enter the wrong email address then you get a message as shown/
'gain" If you enter the wrong email address then you get/
'gain" If you enter the wrong email address then you get/
If you enter the orret email address/
Then you get/
Struts 2 /rl Validator
The 8R&Aalidator of Struts 2 Framework heks whether the String ontained within the given
field is a valid 8R& or not. If the entered value is not a valid 8R&" it generates an error
message.
The error message is supplied between the BmessageC B9messageC tag. The following example
demonstrates how to use the 8R& validator.
Follow the steps to develop the 8R& validator example/
Ste 1/ )reate the struts.xml file and add the following xml snippet in the struts.x#l file.
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">

<! 4dd actions &ere >
<! Crl validation >
<action name="url;alidation">
<result>/pa"es/url%nputGorm.jsp</result>
</action>
<action name="url;alidation9" class="net.roseindia.url;aFidation4ction">
<result name="input">/pa"es/url%nputGorm.jsp</result>
<result name="error">/pa"es/url%nputGorm.jsp</result>
<result>/pa"es/urlSuccess.jsp</result>
</action>
<! 4dd actions &ere >
</package>
<! 4dd pac,a"es &ere >
</struts>
Ste 2 / )reate an input +sp form.
url'nutFor#.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Crl input form</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
<s:&ead/>
</&ead>
<bod#>

<s:form met&od="!DST" action="url;alidation9">
</td>
</tr>
<s:textfield label="-nter Crl" name="url" />
<s:submit />
</s:form>
</bod#>
</&tml>
Ste > / )reate an 'tion lass.
urlVa)idationAction.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class url;aFidation4ction extends 4ctionSupport *
private Strin" url8
public void setCrl:Strin" url<*
this.url = url8
+
public Strin" "etCrl:<*
return url8
+
+
Ste ? / )reate an 8R& validator as shown/
The validation.xml format is either <ActionClassName>validation.xml or
<ActionClassName><ActionAliasName>validation.xml.
3() "alidator8 This Field Aalidator heks whether a given field ontains a valid 8R& String
or not. If the entered text is valid then you get the urlSuccess.4s page. Otherwise" it displays the
message given in the xml file :like ;6lease enter a "alid 3().K<.
The 8R& validator takes the following parameters/
field4ame ( It refers to the field name" the 8R& validator is validating.
It is re3uired if using 2lain(Aalidator Syntax
urlVa)idationAction2"alidation.x#l
<Ixml version="9.5" encodin"="CTGN"I>
<!.D(TE!- validators !C1F%(
"//DpenS#mp&on# 3roup//RAor, ;alidator 9.5.2//-/"
"&ttp://666.opens#mp&on#.com/x6or,/x6or,validator9.5.2.dtd">

<validators>
<field name="url">
<fieldvalidator t#pe="url">
<messa"e>!lease enter a valid url</messa"e>
</fieldvalidator>
</field>
</validators>
-hen the orret 8R& is entered the user gets the urlSuccess.4s page displaying the entered
8R&.
urlSuccess.4s
<OPpa"e lan"ua"e="java" O>
<&tml>
<&ead>
<title>(orrect entr#</title>
</&ead>
<bod#>
<b>C$F = </b><O=reMuest."et!arameter:"url"< O>!
</bod#>
</&tml>
9utut8
-hen this appliation exeutes initially the user gets the following/
If the user enters the wrong 8R& then he gets/
'gain" the user enters the wrong 8R& then he gets/
If the user enters the orret 8R& as
then he gets a suess message as an output/
Validations usin Struts 2 Annotations
Validating Struts 2 )ogin Alication using Annotations
In this setion we are going to validate our login appliation using 'nnotations in 'tion lass.
Our urrent login appliation does not validate the user against the database. Instead login name
and passwords are validated against the hardode values :8ser/ Admin and 2assword/ Admin< in
the ations lass.
Wor7ing o& the alication
1. &ogin page is displayed to take the input.
2. 8ser enters user name and password and then liks on the ;&ogin; button.
3. 8ser validation is done in ation lass and if user enters 'dmin9'dmin in the user
name9password fields" then suess page is displayed" Otherwise the error message is
displayed on the sreen.
Stes to de"elo the alication
1ere are simple and easy steps to develop &ogin page in the using Struts 2 framework.
1. *e"elo )ogin For#
The H8I of the appliation onsists of login form :log2in.4s< and suess message page
:loginsuccess.4s<.
The log2in.4s is used to display the login page to the user. In our appliation it is saved
in ;webappsIstruts2tutorialIpagesI; folder. 1ere is the ode of log2in.4s file/

EHI tagli/ re&ixJKsK uriJK-struts2tagsK HF
BhtmlC
BheadC
BtitleCStruts 2 &ogin 'ppliationFB9titleC
Blink hrefM;Bs/url valueM;-css-#ain.css;9C; relM;stylesheet; typeM;text9ss;9C
B9headC
BbodyC
Es8&or# actionJKAnnotationActionK #ethodJK69STK "alidateJKtrueKF
BtrC
Btd olspanM;2;C
&ogin
B9tdC
B9trC
BtrC
Btd olspanM;2;C
Es8actionerror -F
Es8&ielderror -F
B9tdC
B9trC
Es8text&ield na#eJKuserna#eK la/elJK)ogin na#eK-F
Es8assword na#eJKasswordK la/elJK6asswordK-F
Es8su/#it "alueJK)oginK alignJKcenterK-F
E-s8&or#F
B9bodyC
B9htmlC
1. The ode /
Es8actionerror -F
Es8&ielderror -F
displays ation errors and field validation errors.
The ode Es8&or# actionJKAnnotationActionK #ethodJK69STK "alidateJKtrueKF
generates the html form for the appliation.
The ode /
Es8text&ield na#eJKuserna#eK la/elJK)ogin na#eK-F
Es8assword na#eJKasswordK la/elJK6asswordK-F
generates &ogin 4ame and 2assword fields.
The submit button is generated through Es8su/#it "alueJK)oginK alignJKcenterK-F
ode.
The loginsuccess.4s page displays the &ogin Suess message when user is
authentiated suessfully. 1ere is the ode of loginsuccess.4s file/
BhtmlC
BheadC
BtitleC&ogin SuessB9titleC
B9headC
BbodyC
Bp alignM;enter;CBfont olorM;W****@*; si,eM;>;C&ogin
SuessfulB9fontCB9pC
B9bodyC
B9htmlC


2. *e"eloing Action class 0using Annotations to "alidate )ogin &or#s1
4ow let6s develop the ation lass to handle the login re3uest. The Struts 2 framework
provides a base 'tionSupport lass to implement ommonly used interfaes. In our
ation lass :AnnotationAction.4a"a< we have extended ActionSuort lass and
imported the com.opens#mp&on#.x6or,2.validator.annotations pac,a"e .
For validating the login appliation +ava sript an be added to the +sp page or in ation
lass" but Struts 2 provides another very easy method to validate your form fields using
annotations in the ation lass.
Two annotations are needed"
.. The IValidation annotation tells Struts that ation in this lass might need to be
validated.
2. The I(e:uiredStringValidator annotation is used for the text input to hold a
singular value.
Rest of the are is taken by the framework.
Our ;4nnotation4ction; lass is saved in the ;webappsIstruts2tutorialI-5#(
I4FIsrI+avaInetIroseindia; diretoy. 1ere is the ode of 4nnotation4ction.+ava ation
lass/
In this lass we will write the ode to validate the login page.
AnnotationAction.*ava
package net.roseindia8

import com.opens#mp&on#.x6or,2.4ctionSupport8
import com.opens#mp&on#.x6or,2.validator.annotations.'8

P;alidation

public class 4nnotation4ction extends 4ctionSupport *

private Strin" username = null8

private Strin" pass6ord = null8

P$eMuiredStrin";alidator:messa"e="Suppl# name"<

public Strin" "etCsername:< *
return username8
+


public void setCsername:Strin" value< *
username = value8
+


P$eMuiredStrin";alidator:messa"e="Suppl# pass6ord"<

public Strin" "et!ass6ord:< *

return pass6ord8
+


public void set!ass6ord:Strin" value< *

pass6ord = value8
+



public Strin" execute:< throws -xception *

S#stem.out.println:";alidatin" lo"in"<8
if:!"etCsername:<.eMuals:"4dmin"< HH !"et!ass6ord:<.eMuals:"4dmin"<<*
add4ction-rror:"%nvalid user name or pass6ord! !lease tr# a"ain!"<8

return -$$D$8

+
else*

return SC((-SS8
+

+
+

1. !on&iguring action #aing 0in struts.x#l1
4ow we will reate ation mapping in the struts.xml file. 1ere is the ode to be added in
the struts.xml/
Bation nameM;&ogin'nnotation;C
BresultC9pages9log(in.+spB9resultC
B9ationC
Bation nameM;'nnotation'tion;
lassM;net.roseindia.'nnotation'tion;C
Bresult nameM;input;C9pages9log(in.+spB9resultC
Bresult nameM;error;C9pages9log(in.+spB9resultC
BresultC9pages9loginsuess.+spB9resultC
B9ationC
2. In the above mapping the ation ;&ogin'nnotation; is used to display the login page and
;'nnotation'tion; validates the user using ation lass :4nnotation4ction.+ava<.
3. !SS &ile 0#ain.css1
This ss file is used to enhane the presentation of the login form. The #ain.css is saved
into ;IwebappsIstruts2tutorialIss; diretory.
1ere is the ode of #ain.css/
X)1'RS5T ;8TF(@;S
body R
font/ .2px verdana" arial" helvetia" sans(serifS
bakground(olor/WFFFFFFS
T
table.wwFormTable R
font/ .2px verdana" arial" helvetia" sans(serifS
border(width/ .pxS
border(olor/ W*J*S
border(style/ solidS
olor/ W2?2S
bakground(olor/ WadaS
width/ J*YS
margin(left/J>YS
margin(right/J>YS
margin(top/.>YS
T
table.wwFormTable th R
T
table.wwFormTable tr td R
bakground(olor/ WdfdS
margin/ >pxS
padding/ >pxS
T
.td&abel R
9Q
border(width/ .pxS
border(olor/ WafaS
border(style/ solidS
Q9
font(weight/ boldS
align/ topS
T
.label R
T
.error%essage R
olor/ redS
font(si,e/ *.@emS
T
Wheader0iv R
border(style/ solidS
border(width/ .px .px *pxS
border(olor/ blakS
padding/ >pxS
bakground(olor/ WGaGS
9Q height/ 22pxS Q9
height/ ..@emS
9Q margin(bottom/ .2pxS Q9
T
Wbutton#ar R
border(width/ *px .px .pxS
border(style/ solidS
border(olor/ blakS
olor/ whiteS
margin(bottom/ .2pxS
bakground(olor/ WGaGS
height/ ..7emS
padding/ >pxS
T
Wapp4ame R
olor/ whiteS
font(si,e/ ..@emS
T
WpageTitle R
font(si,e/ ..?emS
olor/ WdfdS
lear/ noneS
T
Wapp4ame" WpageTitle R
float/ rightS
T
Wmenu)ontainer R
float/ leftS
T
Wbranding)ontainer R
float/ right/
text(align/ rightS
T
!o#iling the alication
To ompile the appliation go to ;IwebappsIstruts2tutorialI-5#(I4FIsr; diretory and type ant
ommand. The ant tool will ompile the appliation for you.
Adding the lin7 into index.ht#l
Finally we have to add the link in the index.html to aess the login form.
BulC
BliCBa hrefM;roseindia9&ogin'nnotation.ation;C'tion 'nnotation 5xampleB9aCB9liC
B9ulC
9utut8
'& you clic7 )ogin /utton without &illing the &ields % you will get the outut age as 8
'& you &ill only the K)ogin na#eK &ield and clic7 )ogin /utton without &illing the next
&ields% you will get the outut age as 8
'& you &ill the wrong in&or#ation and clic7 the )ogin /utton% you will get the outut age
as 8
'& you &ill the correct in&or#ation and clic7 the )ogin /utton% you will get the outut
age as 8
$oin0$oout With Session
In this setion" we are going to develop a login9logout appliation with session. This appliation
heks the user authentiation. -henever you run" it takes a user id and a password :#oth the
user id and password is ;ad#in;< it displays the welome page" when both fields are orretly
filled.

)reate an ation mapping in the struts.xml file. 1ere is the ode to be added in the struts.x#l/

Bation nameM;login; lassM;net.roseindia.login'tion;
C
Bresult nameM;suess;
typeM;dispather;C9pages9uiTags9Suess.+spB9resultC
Bresult nameM;error;
typeM;rediret;C9pages9uiTags9&ogin.+spB9resultC
B9ationC
Bation nameM;logout;
lassM;net.roseindia.logout'tion; C
Bresult nameM;suess;
typeM;rediret;C9pages9uiTags9hek&ogin.+spB9resultC
B9ationC
0evelop an ation lass that handles the login re3uest. The Struts 2 framework provides a base
ActionSuort lass that implements ommonly used framework interfaes. In our ation
lass :loginAction.4a"a< we have extended ActionSuort lass.
1ere is the ode of ;loginActionK ation lass/
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import com.opens#mp&on#.x6or,2.4ction(ontext8
import java.util.'8
public class lo"in4ction extends 4ctionSupport *
private Strin" user%d8
private Strin" pass6ord8
public Strin" execute:< throws -xception*
if :"admin".eMuals:user%d< 77 "admin".eMuals:pass6ord<< *
Bap session = 4ction(ontext."et(ontext:<."etSession:<8
session.put:"lo""edin"0"true"<8
return SC((-SS8
+
else*
return -$$D$8
+
+
public Strin" lo"out:< throws -xception *
Bap session = 4ction(ontext."et(ontext:<."etSession:<8
session.remove:"lo""edin"<8
return SC((-SS8
+
public Strin" "et!ass6ord:< *
return pass6ord8
+
public void set!ass6ord:Strin" pass6ord< *
this.pass6ord = pass6ord8
+
public Strin" "etCser%d:< *
return user%d8
+
public void setCser%d:Strin" user%d< *
this.user%d = user%d8
+
+
0ownload this ode.
'gain" develop an ation lass to handle the logout operation. 'n ation lass :logoutAction< we
have extended ActionSuort lass.
1ere is the ode of logoutAction ation lass/
package net.roseindia8
import javax.servlet.&ttp.@ttpSession8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import com.opens#mp&on#.x6or,2.4ction(ontext8
import java.util.'8
public class lo"out4ction extends 4ctionSupport *
public Strin" execute:< throws -xception *
Bap session = 4ction(ontext."et(ontext:<."etSession:<8
session.remove:"lo""edin"<8
return SC((-SS8
+
+
*ownload this code.
*e"elo )ogin For#8 The H8I of the appliation onsists of login form :)ogin.4s<. The
;)ogin.4s; displays the login page to the user.
1ere is the ode of )ogin.4s file/
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<OP pa"e lan"ua"e="java" contentT#pe="text/&tml"O>
<&tml>
<&ead>
<title>%nsert .ata &ere!</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
</&ead>
<bod#>
<s:form action="/roseindia/lo"in.action" met&od="!DST">
<s:textfield name="user%d" label="Fo"in %d"/><br>
<s:pass6ord name="pass6ord" label="!ass6ord"/><br>
<s:submit value="Fo"in" ali"n="center"/>
</s:form>
</bod#>
</&tml>
The ;Success.4s; page displays the &ogin Suess message :Welcome, you have logged-in.< and
session :Session Ti#e8 -ed 'ug *. ../27/J@ H%T^*>/J* 2**G and &ogout < when user gets
suessful authentiation. If you lik the ;)ogout; then again login page is displayed on the
sreen.
1ere is the ode of Success.4s file/
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<OP pa"e lan"ua"e="java" contentT#pe="text/&tml" import="java.util.'"O>
<jsp:include pa"e="/struts2ta"s/pa"es/uiTa"s/lo"in(&ec,.jsp" />
<&tml>
<&ead>
<title>Aelcome0 #ou &ave lo"ined!</title>
</&ead>
<bod#>
Aelcome0 #ou &ave lo"ined. <br />
<b>Session Time: </b><O=new .ate:session."etFast4ccessedTime:<<O>
<br /><br />
<a &ref="<O= reMuest."et(ontext!at&:< O>/roseindia/lo"out.action
">Fo"out</a>
<br />
</bod#>
</&tml>
This page logs out the valid user.
check#ogin.*sp
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<OP pa"e lan"ua"e="java" contentT#pe="text/&tml" import="java.util.'"O>
<&tml>
<&ead>
<title>(&ec, validate!</title>
</&ead>
<bod#>
<s:if test="=session.lo"in != VadminV">
<jsp:for6ard pa"e="/pa"es/uiTa"s/Fo"in.jsp" />
</s:if>
</bod#>
</&tml>
+utput%
Run this appliation by getting the login page/
5nter the wrong user id and password in the login page
=ou get the following output/
5nter the orret user id and password in the login page/
=ou get the following output/
'fter liking the ;)ogout;. =ou get the following output/
Struts 2 1yS2$
In this setion" =ou will learn to onnet the +yS.) database with the struts 2 appliation.
Follow the following steps to onnet with %yS`& database/
Ste 1/ )reate the struts.xml file and add the following xml snippet in the struts.x#l file.
<Ixml version="9.5" encodin"="CTGN" I
>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T
. Struts
(onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/str
uts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials
>
<constant name="struts.enable..#na
micBet&od%nvocation"
value="false" />
<constant name="struts.devBode" va
lue="true" />
<include file="strutsdefault.xml"/>

<! 4dd pac,a"es &ere >
<package name="roseindia" namespace=
"/roseindia"
extends="strutsdefault">
<! insertin" data into data base t&r
ou"& 2.1( >
<action name="insert">
<result>/pa"es/insert.ata.jsp</r
esult>
</action>
<action name="insert.ata" class="n
et.roseindia.insert">
<result name="error">/pa"es/ins
ert.ata.jsp</result>
<result>/pa"es/insertSuccess.jsp
</result>
</action>

</package>
</struts>
Ste 2 / )reate an input +sp form.
insert*ata.4s
<OP ta"lib prefix="s" uri="/struts
ta"s" O>
<&tml>
<&ead>
<title>Struts 2 %nsert .ata 4pplicatio
n!</title>
<lin, &ref="<s:url value="/css/main.css
"/>" rel="st#les&eet"
t#pe="text/css"/>
</&ead>
<bod#>
<s:form action="insert.ata" met&od="!D
ST" validate="true">
<tr>
<td colspan="2">
!lease enter
</td>
</tr>
<s:actionerror />
<s:fielderror />
<s:textfield name="username" label="Cs
er /ame"/>
<s:pass6ord name="pass6ord" label="!as
s6ord"/>
<s:submit value="Save" ali"n="center"/>
</s:form>
</bod#>
</&tml>
Ste > / )reate an 'tion lass.
First" 5stablish a onnetion with the %yS`& 0atabase with the help of +yS.) driver
:;org.g4t.##.#ys:l.*ri"er;<.
4ow" %ake an aount in the %yS`& database to get onneted with the database.
'fter establishing a onnetion" you an retrieve" insert and update data to the %yS`& database
table.
The following ation lass establishes a onnetion with +yS.) database with the help of
appropriate type of methods and A6' interfaes. If onnetion is established then the entered
data is added to the %yS`& database table otherwise it displays an error message.
insert.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionS
upport8
import java.util..ate8
import java.sMl.'8
/''
' <p> ;alidate a user lo"in. </p>
'/
public class insert extends 4ctionSu
pport *

public Strin" execute:< throws -xcep
tion *
Strin" url = "jdbc:m#sMl://local&o
st:QQ5>/"8
Strin" db/ame = "tas,project"8
Strin" driver/ame = "or"."jt.mm.m#
sMl..river"8
Strin" user/ame = "root"8
Strin" pass6ord = "root"8
(onnection con=null8
Statement stmt=null8
tr'*
(lass.for/ame:driver/ame<.ne6%ns
tance:<8
con=.riverBana"er."et(onnection:
urlLdb/ame0 user/ame0
pass6ord<8
stmt=con.createStatement:<8
+
catch:-xception e<*
S#stem.out.println:e."etBessa"e:
<<8
+
Strin" uname="etCsername:<8
Strin" p6s="et!ass6ord:<8
stmt = con.createStatement:<8
int val = stmt.executeCpdate:"
%/S-$T emplo#ee ;4FC-S

:V"LunameL"V0V"Lp6sL"V<"<8
if:val == 5<*
return -$$D$8
+
else*
return SC((-SS8
+
+
// Csername propert#
/''
' <p>Gield to store Cser username
.</p>
' <p/>
'/
private Strin" username = null8
/''
' <p>!rovide Cser username.</p>
'
' Preturn $eturns t&e Cser userna
me.
'/
public Strin" "etCsername:< *
return username8
+
/''
' <p>Store ne6 Cser username</p>
'
' Pparam value T&e username to se
t.
'/
public void setCsername:Strin" val
ue< *
username = value8
+
// Csername propert#
/''
' <p>Gield to store Cser pass6ord
.</p>
' <p/>
'/
private Strin" pass6ord = null8
/''
' <p>!rovide Cser pass6ord.</p>
'
' Preturn $eturns t&e Cser pass6o
rd.
'/
public Strin" "et!ass6ord:< *
return pass6ord8
+
/''
' <p>Store ne6 Cser pass6ord</p>
'
' Pparam value T&e pass6ord to se
t.
'/
public void set!ass6ord:Strin" val
ue< *
pass6ord = value8
+
+
*escrition o& the code8
!onnection8
This is an interfae in 4a"a.s:l pakage that speifies establishing onnetion with the speifi
database like/ +yS.)" +s2Access" 9racle et and +ava files. The S.) statements are exeuted
within the ontext of the )onnetion interfae.
!lass.&orNa#e0String dri"er18
This method is stati. It attempts to load the lass dynamially and returns lass instane and
takes string type value :driver< when it mathes with the lass with given string.
*ri"er+anager8
It is a lass of 4a"a.s:l pakage that ontrols a set of $*5! drivers. 5ah driver has to be
registered with this lass.
get!onnection0String url% String userNa#e% String assword18
This method establishes a onnetion to speified database url. It takes three string types of
arguments like/
url8 ( 0atabase url to link with
userNa#e8 ( 8ser name of database
assword8 (2assword of database
con.close018
This method is used for disonneting the onnetion. It frees all the resoures oupied by the
database.
Ste ? / )reate the validator
The validation.xml format is either <ActionClassName>validation.xml or
<ActionClassName><ActionAliasName>validation.xml.
insert2"alidation.x#l
<Ixml version="9.5" encodin"="CTGN"I>
<!.D(TE!- validators !C1F%(
"//DpenS#mp&on# 3roup//RAor, ;a
lidator 9.5.2//-/"
"&ttp://666.opens#mp&on#.com/x6o
r,/x6or,validator9.5.2.dtd">

<validators>
<field name="username">
<fieldvalidator t#pe
="reMuiredstrin"">
<param name="trim">true</param>
<messa"e>Cser name is reMuired</
messa"e>
</fieldvalidator>
</field>
<field name="pass6ord">
<fieldvalidator t#pe
="reMuiredstrin"">
<param name="trim">true</param>
<messa"e>!ass6ord is reMuired</m
essa"e>
</fieldvalidator>
</field>
</validators>
-hen entered the orret data in the text field the user gets the insertSuccess.4s page
displaying the entered data.
insertSuccess.4s
<&tml>
<&ead>
<title>%nserted .ata Fist</title>
</&ead>
<bod#>
<b> %nserted .ata: </b>
<b>Cser name = </b><
O=reMuest."et!arameter:"username"< O>!
<b>!ass6ord = </b><
O=reMuest."et!arameter:"pass6ord"< O>!
</bod#>
</&tml>
9utut8
-hen this appliation exeutes the user gets the following/
-ithout filling fields and lik ;Save; button" you will get the output page as /
If you fill only the ;2assword; field and lik ;Save; button without filling the next fields" you
will get the output page as /
If you fill only the ;8ser 4ame; field and lik ;Save; button without filling the next fields" you
will get the output page as /
If you fill both field/
Then you get/
)ich "ditor "xam!le
In this setion" you will learn how to reate pagination in struts 2. For reating pagination in your
appliation follows the ertain steps/
*ownload this code
Step ./ )reate index.4s page
1ere is the ode to be added in the index.4s/
DE/56TF+; 0T12 +B:2&6 G-CC<36CC/T/ 0T12 4.0 Transitiona!CC;3GH
Dhtm!H
DheadH
Dtit!eH7ose&ndia.3et )truts 2 Tutoria!DCtit!eH
DCheadH
D$od#H
Ddi" a!ignIGcenterGH
DcenterH
Dta$!e $orderIG0G ce!!addingIG0G ce!!sacingIG0G widthIG400GH
DtrH
DtdHDfont co!orIGJ000080G si4eIG5GHD$H7ose&ndia.net )truts 2
Tutoria!sDC$HD$rH
Kn$sLKn$sLKn$sLDCfontHDCtdH
DCtrH
DtrH
DtdHDfont co!orIGJ000080GHD$H)e!ect the fo!!owing !inks to test the
e'am!esDC$HDCfontHDCtdH
DCtrH
DtrH
DtdH
Du!H
D!iHDa hrefIGroseindiaCagination.actionGH+agination ;'am!eDCaHDC!iH
DCu!H
DCtdH
DCtrH
DtrH
DtdHDfont co!orIGJ000080GHKn$sLD$rH
Kn$sLD$rH
Kn$sLD$rH
9isit Da hrefIGhttACCwww.roseindia.netGHhttACCwww.roseindia.netDCaH
for !atest tutoria!sDCfontHDCtdH
DCtrH
DCta$!eH
DCcenterH
DCdi"H
D a!ignIGcenterGHKn$sLDCH
DC$od#H
DChtm!H
Step 2/ )reate an ation mapping in the struts.x#l file.
1ere is the ode to be added in the struts.x#l/
BNxml versionM;..*; enodingM;8TF(@; NC
BF0O)T=25 struts 28#&I)
;(99'pahe Software Foundation990T0 Struts )onfiguration
2.*9954;
;http/99struts.apahe.org9dtds9struts(2.*.dtd;C
BstrutsC
BF(( Rose India Struts 2 Tutorials ((C
Bonstant nameM;struts.enable.0ynami%ethodInvoation;
valueM;false; 9C
Bonstant nameM;struts.dev%ode; valueM;true; 9C
Bpakage nameM;roseindia; namespaeM;9roseindia;
extendsM;struts(default;C
Bation nameM;pagination;C
BresultC9pages9hat`uestion9pagination.+spB9resultC
B9ationC
B9pakageC
BF(( 'dd pakages here ((C
B9strutsC
Step J/ )reate a !S2 page that ontains pagination ode/
1ere is the ode to be added in the agination.4s/
BYX taglib prefixM;s; uriM;9struts(tags; YC
BhtmlC
BheadC
BtitleC2agination 5xampleB9titleC
Bs/head themeM;a+ax; 9C
B9headC
BbodyC
Bs/formC
Bs/textarea nameM;text; labelM;2aste your text here;
themeM;a+ax;
ssStyleM;bakground(olor/ WF)F)F)S border/ .px solid
W'*'*'*S min(height/>**pxS max(height/inheritS ;9C
B9s/formC
B9bodyC
B9htmlC
9utut8
Validate *extArea
In this setion" you will learn how to validate your text area in struts 2. ' text area ontains . to
2>* haraters. It ann6t support ;null; value.
For validating your text are in your appliation follows the ertain steps/
Step ./ )reate index.4s page



1ere is the ode to be added in the index.4s/
BF0O)T=25 1T%&
28#&I) ;(99-J)990T0 1T%& ?.*
Transitional9954;C
BhtmlC
BheadC
BtitleCRoseIndia.4et Struts 2 TutorialB9titleC
B9headC
BbodyC
Bdiv alignM;enter;C
BenterC
Btable borderM;*; ellpaddingM;*;
ellspaingM;*; widthM;?**;C
BtrC
BtdCBfont olorM;W****@*;
si,eM;>;CBbCRoseIndia.net Struts 2
TutorialsB9bCBbrC
[nbspS[nbspS[nbspSB9fontCB9tdC
B9trC
BtrC
BtdCBfont olorM;W****@*;CBbCSelet the
following links to test the
examplesB9bCB9fontCB9tdC
B9trC
BtrC
BtdC
BulC
BliCBa
hrefM;roseindia9harater&imit.ation;C)har
aters and limiting 5xampleB9aCB9liC
B9ulC
B9tdC
B9trC
BtrC
BtdCBfont olorM;W****@*;C[nbspSBbrC
[nbspSBbrC
[nbspSBbrC
Aisit Ba
hrefM;http/99www.roseindia.net;Chttp/99www.
roseindia.netB9aC
for latest tutorialsB9fontCB9tdC
B9trC
B9tableC
B9enterC
B9divC
Bp alignM;enter;C[nbspSB9pC
B9bodyC
B9htmlC
Step 2/ )reate an ation mapping in the struts.x#l file.
1ere is the ode to be added in the struts.x#l/
BNxml versionM;..*; enodingM;8TF(@; NC
BF0O)T=25 struts 28#&I)
;(99'pahe Software Foundation990T0 Struts
)onfiguration 2.*9954;
;http/99struts.apahe.org9dtds9struts(2.*.dtd;C
BstrutsC
BF(( Rose India Struts 2 Tutorials ((C
Bonstant
nameM;struts.enable.0ynami%ethodInvoation;
valueM;false; 9C
Bonstant nameM;struts.dev%ode;
valueM;true; 9C
Bpakage nameM;roseindia;
namespaeM;9roseindia; extendsM;struts(
default;C
Bation nameM;harater&imit;C
BresultC9pages9hat`uestion9limited)harater.+sp
B9resultC
B9ationC
Bation nameM;harater&imit.;
lassM;net.roseindia.limited)harater'tion;C
Bresult
nameM;error;C9pages9hat`uestion9limited)hara
ter.+spB9resultC
Bresult
nameM;suess;C9pages9hat`uestion9limited)h
araterSuess.+spB9resultC
B9ationC
B9pakageC
BF(( 'dd pakages here ((C
B9strutsC
Step J/ )reate a !S2 page that ontains text area and submit button/
1ere is the ode to be added in the li#ited!haracter.4s/
BYX taglib prefixM;s; uriM;9struts(tags; YC
BhtmlC
BheadC
BtitleC&imited )haraters in Text 'reaB9titleC
Bs/head themeM;a+ax; 9C
B9headC
BbodyC
Bs/form ationM;harater&imit.; methodM;2OST;
validateM;true;C
Bs/textarea nameM;summary.; labelM;#rief Summary; rowsM;7;
olsM;?*;9C
Bs/submit valueM;Save; alignM;enter; 9C
B9s/formC
B9bodyC
B9htmlC
Step ?/ )reate an ation lass/
1ere is the ode to be added in thelimited)harater'tion.+ava/
pakage net.roseindiaS
import om.opensymphony.xwork2.'tion)ontextS
import om.opensymphony.xwork2.'tionSupportS
import +ava.io.2rintStreamS
import +ava.util.&istS
import +ava.util.QS
publi lass limited)harater'tion extends 'tionSupportR
private String summary.S
publi String getSummary.:< R
return summary.S
T
publi void setSummary.:String summary.< R
this.summary. M summary.S
T
publi String exeute:< throws 5xeptionR
String summaryText M getSummary.:<S
long ountSummaryText M summaryTextount:summaryText<S
System.out.println:;ountSummaryText/;^ountSummaryText<S
if :ountSummaryText C* [[ ountSummaryText B 2>*<R
return S8))5SSS
T
elseR
if:getSummary.:<.e3uals:;;<<
addField5rror:;summary.;";#rief Summary is re3uired.;<S
if::ountSummaryText C 2>*<<
addField5rror:;summary.;";#rief Summary must be . to 2>*
)haraters;<S
return 5RRORS
T
T
private stati long summaryTextount:String str<R
return str.length:<S
T
T
Step >/ )reate a !S2 page that ontains the inputted text in the textarea/
1ere is the ode to be added in limited)haraterSuess.+sp/
BYX taglib prefixM;s; uriM;9struts(tags;YC
BhtmlC
BheadC
BtitleC&imited )haraters in Text
'reaB9titleC
Blink hrefM;Bs/url valueM;9ss9main.ss;9C;
relM;stylesheet;
typeM;text9ss;9C
B9headC
BbodyC
BbC#rief Summary/ B9bCBs/property
valueM;summary.; 9CBbrC
B9bodyC
B9htmlC
9utut8
-hen you lik the ;Save; ommand button with out any data then you get/
If you enter more than 2>* haraters then you get /
If you enter your text between . to 2>* haraters then you get/
Introduction to Struts 2 *as
In this setion we will introdue you with the tags provided along with Struts 2 framework. It is
neessary to understand all the tags provided along with Struts 2 framework. In this page we will
have listed all the Struts 2 Tags and in subse3uent setions we will provide you the examples of
the these tags in detail.

The Struts 2 Tags can /e di"ided into two tyes8

Struts Generic Tags
The struts generi tags are used to ontrol the exeution flow when pages are rendered.
'nother use of struts generi tags are data extration.
Further Heneri Tags are lassified into !ontrol Tags and *ata Tags.
!ontrol Tags8 The )ontrol Tags are used for flow ontrol" suh as if" else and iterate.
Here are the list o& !ontrol Tags/
Q i&
Q else'&
Q else
Q aend
Q generator
Q iterator
Q #erge
Q sort
Q su/set
*ata Tags8 The 0ata Tags are used for data manipulation or reation" suh as bean" push"
and i.@n.
1ere are the list of 0ata Tags/
Q a
Q action
Q /ean
Q date
Q debug
Q i.@n
Q include
Q ara#
Q push
Q set
Q text
Q url
Q roerty

Struts 3' tags
Struts 8I Tags are mainly designed to use the data from your ation9value stak or from
0ata Tags. These tags are used to display the data on the 1T%& page. The 8I tags are
driven by templates and themes.
Struts 8I Tags are of two types Form Tags and 4on ( Form tags.
For# Tags are as &ollows8
Q autoco#leter
Q chec7/ox
Q chec7/oxlist
Q co#/o/ox
Q dateti#eic7er
Q dou/leselect
Q head
Q &ile
Q &or#
Q hidden
Q la/el
Q otiontrans&erselect
Q otgrou
Q assword
Q radio
Q reset
Q select
Q su/#it
Q textarea
Q text&ield
Q token
Q udownselect
Non2For# 3' Tags are8
Q actionerror
Q action#essage
Q omponent
Q di"
Q &ielderror
Q table
Q ta//ed6anel
Q tree
Q treenode
The main differene between Struts Generic Tags and Struts 3' Tags are/
The generi tags simply output some ontent diretly from the tag while the 8I tags uses
templates and often group the output together with theme
(ontrol *as-If 0 "lse If 0 "lse
In this setion we are going to disuss the various ontrol tags : The )ontrol Tags are used for
flow ontrol suh as if" else and iterate.<
U'&U tag ould be used by itself or with U,lse '&U Tag and9or single9multiple U,lseU Tag.
)reate a !S2 page '&!ontrolTag.4s.
Set a property 6technologyNa#e6 with a value 6$a"a6 as
<s:set name="tec&nolo"#/ame" value="O*V2avaV+"/>
'mong i&% elsei& and else tags only one tag evaluates at a time. 5valuation is based upon the
onditions being proessed. 5valuated onditions must be of #oolean type. This is illustrated in
the following !sp page.
ONote/
If the ondition in Es8i& F tag evaluates to 6true6 then only this tag is evaluated and others are
disarded. 's illustrated in the example.
If the ondition in Es8i& F tag evaluates to 6&alse6 and Es8elsei& F tag evaluates to 6true6 then the
body of the Es8elsei& F tag is proessed.
If the ondition in Es8i& F tag and Es8elsei& F tags evaluates to 6&alse6 then only the Es8else F tag
is proessed. P
'&!ontrolTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Struts 2 (ontrol Ta" -xample</title>
</&ead>
<bod#>
<s:set name="tec&nolo"#/ame" value="O*V2avaV+"/>
<s:if test="O*=tec&nolo"#/ame==V2avaV+">
<div><s:propert# value="O*=tec&nolo"#/ame+" /></div>
</s:if>
<s:elseif test="O*=tec&nolo"#/ame==V2avV+">
<div><s:propert# value="O*=tec&nolo"#/ame+" /></div>
</s:elseif>

<s:else>
<div>Tec&nolo"# ;alue is not 2ava</div>
</s:else>
</bod#>
</&tml>
struts.x#l8 'dd the following xml snippet in the struts.x#l file.
Bation nameM;doIf; C

BresultC9pages9generiTags9If)ontrolTa
g.+spB9resultC
B9ationC
index.4s 8 'dd the following +sp snippet in the index.4s file.
BulC
BliCBa hrefM;roseindia9doIf.ation;CIF
)ontrol Tag 5xampleB9aCB9liC
B9ulC
In the '&!ontrolTag.4s only Bs8i&F tag evaluates to true
<s:if test="O*=tec&nolo"#/ame==V2avaV+">
<div><s:propert# value="O*=tec&nolo"#/ame+" /></div>
</s:if>
So we get the output e3ual to $a"a
!ava
A!!end *a +(ontrol *as, "xam!le
In this setion" we are going to desribe the append tag. The append tag is a generi tag that is
used to merge multiple iterators into one iterator.
'ppend Iterator Tag is used to append iterators to form an appended iterator through whih the
entries goes from one iterator to another after eah respetive iterator is exhausted of entries.
'dd the following ode snippet
into the struts.xml file.
struts.x#l /
Bation nameM;'ppendTag;
lassM;net.roseindia.'ppendTag;C

BresultC9pages9generiTags9'ppendTag.+sp
B9resultC
B9ationC
)reate two lists in the ation lass and populate them with various items as shown in the
;AendTag; lass.
AendTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class 4ppendTa" extends 4ctionSupport*

private Fist m#Fist8
private Fist m#Fist98
public Strin" execute:<throws -xception*
m#Fist = new 4rra#Fist:<8
m#Fist.add:"666.$oseindia.net"<8
m#Fist.add:".eepa, Kumar"<8
m#Fist.add:"Sus&il Kumar"<8
m#Fist.add:";inod Kumar"<8
m#Fist.add:"4mit Kumar"<8
m#Fist9 = new 4rra#Fist:<8
m#Fist9.add:"666.javajaSSup.com"<8
m#Fist9.add:"@imans&u $aj"<8
m#Fist9.add:"Br. ,&an"<8
m#Fist9.add:"2o&n"<8
m#Fist9.add:"$avi $anjan"<8
return SC((-SS8
+
public Fist "etB#Fist:<*
return m#Fist8
+
public Fist "etB#Fist9:<*
return m#Fist98
+
+
4ow reate a +sp page using <s%append> and <s%iterator> tags as shown in the
AendTag.4s page. The append tag is used to merge multiple iterators into one iterator. The
;id; parameter keeps the resultant appended iterator stored under the stak6s ontext and the
K"alueK parameter is used to get the values ontained within the resultant iterator.
AendTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title> 4ppend Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc"> 4ppend Ta" -xample!</span></&9>
<s%append id!"m'Append#ist">
<s%param value!",-m'#ist." &>
<s%param value!",-m'#ist/." &>
<&s%append>
<s:iterator value="O*=m#4ppendFist+">
<s:propert# /><br>
</s:iterator>
</bod#>
</&tml>
9utut o& the Aend Tag ,xa#le8
3enerator *a +(ontrol *as, "xam!le
In this setion" we are going to desribe the generator tag. The generator tag is a generi tag that
is used to generate iterators based on different attri/utes passed. 1ere we will not pass any
attribute.
'dd the following ode snippet into the struts.x#l file.
sturts.x#l
Bation nameM;HeneratorTag;
lassM;net.roseindia.HeneratorTag;C

BresultC9pages9generiTags9HeneratorTag.+spB
9resultC
B9ationC
)reate an ation lass as shown/
GeneratorTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import or".apac&e.struts2.util.%terator3enerator.(onverter8
public class 3eneratorTa" extends 4ctionSupport *
public Strin" excute:< throws -xception*
return SC((-SS8
+
+
)reate a +sp page where the generator tag <s%generator> generates a simple iterator based on
the "al attribute supplied and <s%iterator> ta" prints
it out using the <s%propert' &> tag. The searator attribute is used to separate the val into
entries of the iterator.
GeneratorTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title> 3enerator Ta" -xample! </title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">3enerator Ta" -xample!
</span></&9>
<&Q><font color="=5555GG"> 3enerates a Simple %terator </font></&Q>
<s%generator val!",-0www.1oseindia.net23eepak 4umar25ushil 4umar2
6inod 4umar2Amit 4umar0." separator!"2">
<s%iterator>
<s%propert' &><br&>
<&s%iterator>
<&s%generator>
</bod#>
</&tml>
9utut o& Generator Tag ,xa#le8
3enerator *a +(ontrol *as, /sin (ount Attri.utesIn this setion" we are going to
desribe the generator tag using the count attribute.
'dd the following ode snippet into the struts.x#l file.






struts.x#l
Bation nameM;HeneratorTag)ount'ttribute;
lassM;net.roseindia.HeneratorTag;C

BresultC9pages9generiTags9HeneratorTag)ount'ttribu
te.+spB9resultC
B9ationC
)reate an ation lass as shown/
GeneratorTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import or".apac&e.struts2.util.%terator3enerator.(onverter8
public class 3eneratorTa" extends 4ctionSupport *
public Strin" excute:< throws -xception*
return SC((-SS8
+
+
)reate a +sp page where the generator tag <s%generator> generates an iterator with ;countK
attribute and <s%iterator> ta" prints it out using the <s%propert' &> tag. The searator
attribute separates the val into entries of the iterator.
This generates an iterator" but only > entries will be available in the iterator generated" namely
0www.1oseindia.net2 3eepak 4umar2 5ushil 4umar2 6inod 4umar2 Amit 4umar0
respetively beause ount attribute is set to >.
GeneratorTag!ountAttri/ute.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title> 3enerator Ta" -xample! </title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">3enerator Ta" -xample!
</span></&9>
<&Q><font color="=5555GG"> 3enerates an %terator Ait& (ount 4rrtibute</fo
nt></&Q>
<s:"enerator val="O*V666.$oseindia.net0.eepa, Kumar0Sus&il Kumar0;inod
Kumar0
4mit Kumar0 Sanja#0 ;ija# V+" count="T" separator="0">
<s:iterator>
<s:propert# /><br/>
</s:iterator>
</s:"enerator>
</bod#>
</&tml>
9utut o& the Generator Tag ,xa#le8

3enerator *a +(ontrol *as, /sin an Iterator with Id Attri.utes
n this setion" we are going to desribe the generator tag using the id attributes.
'dd the following ode snippet
into the struts.x#l file.




struts.x#l
Bation nameM;HeneratorTagId'ttribute;
lassM;net.roseindia.HeneratorTag;C

BresultC9pages9generiTags9HeneratorTagId'ttribute.
+spB9resultC
B9ationC
)reate an ation lass as shown /
GeneratorTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import or".apac&e.struts2.util.%terator3enerator.(onverter8
public class 3eneratorTa" extends 4ctionSupport *
public Strin" excute:< throws -xception*
return SC((-SS8
+
+
)reate a +sp page where the generator tag <s%generator> generates an iterator with ;idK
attribute and <s%iterator> ta" prints it out using the <s%propert' &> tag. The searator
attribute separates the val into entries of the iterator.
The sriplet as shown below generates an iterator and put it in the 2age)ontext under the key as
speified
by the id attribute.
<O
%terator i = :%terator< pa"e(ontext."et4ttribute:"m#4tt"<8
while:i.&as/ext:<< *
Strin" s = :Strin"< i.next:<8 O>
<O=sO> <br/>
<O +
O>
GeneratorTag'dAttri/ute.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<OPpa"e lan"ua"e="java" import="java.util.'"O>
<&tml>
<&ead>
<title> 3enerator Ta" -xample! </title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">3enerator Ta" -xample!
</span></&9>
<&Q><font color="=5555GG"> 3enerates an %terator Ait& %d 4rrtibute</font>
</&Q>
<s:"enerator val="O*V666.$oseindia.net0.eepa, Kumar0Sus&il Kumar0;inod
Kumar04mit KumarV+" count="W" separator="0" id!"m'Att" />
<O
%terator i = :%terator< pa"e(ontext."et4ttribute:"m#4tt"<8
while:i.&as/ext:<< *
Strin" s = :Strin"< i.next:<8 O>
<O=sO> <br/>
<O +
O>
</bod#>
</&tml>
9utut o& the Generator Tag ,xa#le8
Iterator *a +(ontrol *as, "xam!le
In this setion" we are going to desribe the Iterator tag. Iterator tag is used to iterate over a
value. 'n iterable value an be either of/ java.util.Collection" java.util.Iterator.
'dd the following ode snippet
into the struts.x#l file.
struts.x#l
Bation nameM;iteratorTag;
lassM;net.roseindia.iteratorTag;C

BresultC9pages9generiTags9iteratorTag.+sp
B9resultC
B9ationC
)reate an ation lass as shown/
iteratorTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class iteratorTa" extends 4ctionSupport*

private Fist m#Fist8

public Strin" execute:<throws -xception*
m#Fist = new 4rra#Fist:<8
m#Fist.add:"Gruits"<8
m#Fist.add:"4pple"<8
m#Fist.add:"Ban"o"<8
m#Fist.add:"Dran"e"<8
m#Fist.add:"!ine 4pple"<8
return SC((-SS8
+
public Fist "etB#Fist:<*
return m#Fist8
+
+
The following example retrieves the value of the get7'#ist:< method of the urrent ob+et on
the value stak and uses it to iterate over. The Es8roerty-F tag prints out the urrent value of
the iterator.
iteratorTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>%terator Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">%terator Ta" -xample!
</span></&9>
<s:iterator value="m#Fist">
<s:propert# /><br>
</s:iterator>
</bod#>
</&tml>
9utut o& An 'terator Tag ,xa#le8
1ere *a +(ontrol *as, "xam!le
In this setion" we are going to desribe the merge tag. The merge tag is a generi tag that is used
to merge iterators. The suessive all to the merge iterator auses eah merge iterator to have a
hane to expose its element" subse3uently next all allows the next iterator to expose its
element. One the last iterator is done exposing its element" the first iterator is allowed to do so
again :unless it is exhausted of entries<.
In the urrent example" 2 lists being merged" eah list have > entries" the following will be the
logi.
.. 0isplay first element of the first list.
2. 0isplay first element of the seond list.
J. 0isplay seond element of the first list.
?. 0isplay seond element of the seond list.
>. 0isplay third element of the first list.
7. 0isplay thrid element of the seond list.....and so on.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;mergeTag;
lassM;net.roseindia.mergeTag;C

BresultC9pages9generiTags9mergeTag.+s
pB9resultC
B9ationC
)reate two lists in the ation lass and populate them with various items as shown in the
;#ergeTag; lass.
#ergeTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class mer"eTa" extends 4ctionSupport *
private Fist m#Fist8
private Fist m#Fist98
public Strin" execute:< throws -xception*
m#Fist = new 4rra#Fist:<8
m#Fist.add:"666.$oseindia.net"<8
m#Fist.add:".eepa, Kumar"<8
m#Fist.add:"Sus&il Kumar"<8
m#Fist.add:";inod Kumar"<8
m#Fist.add:"4mit Kumar"<8
m#Fist9 = new 4rra#Fist:<8
m#Fist9.add:"666.javajaSSup.com"<8
m#Fist9.add:"@imans&u $aj"<8
m#Fist9.add:"Br. ,&an"<8
m#Fist9.add:"2o&n"<8
m#Fist9.add:"$avi $anjan"<8
return SC((-SS8
+
public Fist "etB#Fist:<*
return m#Fist8
+
public Fist "etB#Fist9:<*
return m#Fist98
+
+
4ow reate a +sp page using <s%merge> and <s%param value> tags as shown in the
#ergeTag.4s page. The merge tag is used to merge iterators. The ;id; parameter keeps the
resultant iterator stored under in the stak6s ontext and the K"alueK parameter in the
<s%iterator> is used to get the values ontained within the respetive iterators.
#ergeTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Ber"e Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Ber"e Ta" -xample!</span></&9>
<s%merge id!"merge8d">
<s%param value!",-m'#ist." &>
<s%param value!",-m'#ist/." &>
<&s%merge>
<s:iterator value="O*=mer"e%d+">
<s:propert# /><br>
</s:iterator>
</bod#>
</&tml>
9utut o& #erge Tag8
Su.set *a +(ontrol *as, "xam!le
In this setion" we are going to desribe the subset tag. The subset tag is a generi tag that takes
an iterator and outputs a subset of it. It delegates to org.apahe.struts2.util.SubsetIteratorFilter
internally to perform the subset funtionality.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;subsetTag;
lassM;net.roseindia.subsetTag;C

BresultC9pages9generiTags9subsetTag.+s
pB9resultC
B9ationC
)reate a list in the ation lass and populate it with various items as shown in the ;su/setTag;
lass.
su/setTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class subsetTa" extends 4ctionSupport *
private Fist m#Fist8
public Strin" execute:< throws -xception*
m#Fist = new 4rra#Fist:<8
m#Fist.add:new %nte"er:T5<<8
m#Fist.add:new %nte"er:25<<8
m#Fist.add:new %nte"er:955<<8
m#Fist.add:new %nte"er:NT<<8
m#Fist.add:new %nte"er:T55<<8
return SC((-SS8
+
public Fist "etB#Fist:<*
return m#Fist8
+
+
4ow reate a +sp page using <s%subset> and <s%iterator> tags as shown in the
su/setTag.4s page. The subset tag takes an iterator and outputs a subset of it.
su/setTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Subset Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Subset Ta" -xample!
</span></&9>
<s:subset source="m#Fist">
<s:iterator>
<s:propert# /><br>
</s:iterator>
</s:subset>
</bod#>
</&tml>
9utut o& Su/set Tag8
Su.set *a +(ontrol *as, "xam!le /sin (ount
In this setion" we are going to desribe the subset tag using the count parameter. The ount
parameter indiates the number of entries to be set in the resulting subset iterator.
'dd the following ode snippet
into the struts.xml file.
struts.x#l
Bation nameM;subsetTag)ount;
lassM;net.roseindia.subsetTag;C

BresultC9pages9generiTags9subsetTag)ount.+
spB9resultC
B9ationC
)reate a list in the ation lass and populate it with various items as shown in the ;su/setTag;
lass.
su/setTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class subsetTa" extends 4ctionSupport *
private Fist m#Fist8
public Strin" execute:< throws -xception*
m#Fist = new 4rra#Fist:<8
m#Fist.add:new %nte"er:T5<<8
m#Fist.add:new %nte"er:25<<8
m#Fist.add:new %nte"er:955<<8
m#Fist.add:new %nte"er:NT<<8
m#Fist.add:new %nte"er:T55<<8
return SC((-SS8
+
public Fist "etB#Fist:<*
return m#Fist8
+
+
4ow reate a +sp page using <s%subset> and <s%iterator> tags as shown in the
su/setTag.4s page. The subset tag takes an iterator and outputs a subset of it. The parameter
count is of integer type and it sets the number of entries to be kept in the resulting subset iterator.
su/setTag!ount.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Subset Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Subset Ta" -xample!
</span></&9>
<s:subset source="m#Fist" count="Q">
<s:iterator>
<s:propert# /><br>
</s:iterator>
</s:subset>
</bod#>
</&tml>
9utut o& Su/set Tag8
Output displays only three items beause ountMJ.
Su.set *a +(ontrol *as, "xam!le /sin Start
In this setion" we are going to desribe the subset tag using the start parameter. The start
parameter is of integer type. It indiates the starting index :eg. first entry is *< of entries in the
soure :needed to make available as the first entry in the resulting subset iterator<.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;subsetTagStart-ith;
lassM;net.roseindia.subsetTag;C

BresultC9pages9generiTags9subsetTagStart-ith
.+spB9resultC
B9ationC
)reate a list in the ation lass and populate it with various items as shown in ;su/setTag;
lass.
su/setTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class subsetTa" extends 4ctionSupport *
private Fist m#Fist8
public Strin" execute:< throws -xception*
m#Fist = new 4rra#Fist:<8
m#Fist.add:new %nte"er:T5<<8
m#Fist.add:new %nte"er:25<<8
m#Fist.add:new %nte"er:955<<8
m#Fist.add:new %nte"er:NT<<8
m#Fist.add:new %nte"er:T55<<8
return SC((-SS8
+
public Fist "etB#Fist:<*
return m#Fist8
+
+
4ow reate a +sp page using <s%subset> and <s%iterator> tags as shown in the
su/setTag.4s page. The subset tag takes an iterator and outputs a subset of it. The parameter
start is of integer type and it indiates the starting index :eg. first entry is *< of entries in the
soure :needed to make available as the first entry in the resulting subset iterator<.
su/setTagStartWith.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Subset Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Subset Ta" -xample!
</span></&9>
<s:subset source="m#Fist" count="Q" start="2">
<s:iterator>
<s:propert# /><br>
</s:iterator>
</s:subset>
</bod#>
</&tml>
9utut o& Su/set Tag8
1ere the items displayed are .**" @>" >**. Items displayed starts from 2nd index of the &ist.
Action *a +Data *a, "xam!le
In this setion" we are going to desribe the ation tag. The ation tag is a generi tag that is used
to all ations diretly from a !S2 page by speifying the ation name and an optional
namespae. The body ontent of the tag is used to render the results from the 'tion. 'ny result
proessor defined for this ation in struts.xml will be ignored" unless the execute(esult
parameter is speified.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;ationTag;
lassM;net.roseindia.ationTag;C
Bresult
nameM;suess;C9pages9generiTags9suess.+s
pB9resultC
B9ationC
)reate an ation lass as shown below/
actionTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class actionTa" extends 4ctionSupport *
public Strin" execute:< throws -xception*
return SC((-SS8
+
+
4ow reate a +sp page using <s:action> tag as shown in the success.4s page. The ation tag
is used to all ations diretly from a !S2 page by speifying the ation name and an optional
namespae.
success.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>4ction Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">4ction Ta"
:.ata Ta"s< -xample!</span></&9>
<s%action name!"success">
<b><i>T&e action ta" 6ill execute t&e result and include
it in this pa"e.</i></b></div>
<&s%action>
</bod#>
</&tml>
9utut o& the success.4s
4ean *a +Data *a, "xam!le
In this setion" we are going to desribe the #ean Tag. The #ean tag is a generi tag that is used
to instantiates a lass that onfirms to the !ava#eans speifiation. This tag has a body whih an
ontain a number of 2aram elements to set any mutator methods on that lass.
If the id attribute is set on the #eanTag" it will plae the instantiated bean into the stak6s
)ontext.
'dd the following ode snippet into the struts.xml file.



struts.x#l
Bation nameM;beanTag;
lassM;net.roseindia.beanTag;C
Bresult
nameM;suess;C9pages9generiTags9bean
Tag.+spB9resultC
B9ationC
)reate an ation lass as shown below/
/eanTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class beanTa" extends 4ctionSupport *
public Strin" execute:< throws -xception*
return SC((-SS8
+
+
reate a simple +ava bean as shown/
co#anyNa#e.4a"a
package net.roseindia8
public class compan#/ame *

private Strin" name8
public void set/ame:Strin" name<*
this.name =name 8
+
public Strin" "et/ame:<*
return name8
+
+
4ow reate a +sp page using <s8/ean> and <s8ara#> tags as shown in the /eanTag.4s page.
The /ean tag instantiates the ;net.roseindia.ompany4ame; lass" it onfirms to the !ava#eans
speifiation. The id attribute is set on the #eanTag" it plaes the instantiated bean into the
stak6s )ontext. The body of <s8/ean> tag ontains a param element
<s8ara# na#eJKna#eK>(ose'ndiaE-s8ara#> whih is used to set the value for the
setNa#e01 method of the ;co#anyNa#eK lass and <s8roerty "alueJKHVna#eWK ->
retrieves that value by alling the get4ame:< method.
/eanTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>1ean Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">1ean Ta"
:.ata Ta"s< -xample!</span></&9>
<s%bean name!"net.roseindia.compan'Name" id!"uid">
<s%param name!"name">1ose8ndia<&s%param>
<s%propert' value!",-name." &><br>
<&s%bean>
</bod#>
</&tml>
9utut o& the /eanTag.4s
Date *a +Data *a, "xam!le
In this setion" we are going to desribe the 0ate tag. The date tag allows to format a 0ate in a
3uik and easy way. 8ser an speify a custo# &or#at :eg. ;dd9%%9yyyy hh/mm;<" an
generate easy reada/le notations :like ;in 2 hours" .? minutes;<" or an +ust fall bak on a
rede&ined &or#at with key 6struts.date.format6 in the properties file.
If that key is not defined" it will finally fall bak to the default 0ateFormat.%50I8% formatting.
Note/ If the re3uested 0ate ob+et isn6t found on the stak" a blank will be returned.
)onfigurable attributes are /(
.. name
2. nie
J. format
'dd the following ode snippet into the ;struts.xml; file.
struts.x#l
Bation nameM;dateTag;
lassM;net.roseindia.dateTag;C
Bresult
nameM;suess;C9pages9generiTags9dateTag.+s
pB9resultC
B9ationC
)reate an ation lass as shown below/
dateTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class dateTa" extends 4ctionSupport *
private .ate current.ate8
public Strin" execute:< throws -xception*
set(urrent.ate:new .ate:<<8
return SC((-SS8
+
public void set(urrent.ate:.ate date<*
this.current.ate = date8
+
public .ate "et(urrent.ate:<*
return current.ate8
+
+
4ow reate a +sp page using <s:date> tag as shown in the success.4s page.
The <s%date name!"current3ate" format!"dd&77&''''" &> date tag formats a
0ate in a 3uik and easy way. 1ere the ;&or#atK parameter speify a custo# &or#at :eg.
;dd9%%9yyyy hh/mm;< to follow.
The nice parameter is of #oolean type whih deides whether to print out the date niely or not.
#y 0efault it is kept false whih prints out date niely i.e.
<s:date name="current.ate" nice!"false" /> ta" formats a date and similarl#
<s:date name="current.ate" nice!"true" /> does not format a date0 it is
illustrated in our current jsp pa"e.
dateTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>.ate Ta" :.ata Ta"< -xample!</title>
</&ead>
<bod#>
<&9><font color="=5555N5">(urrent .ate Gormat</font></&9>
<table border="9" 6idt&="QTO" b"color="ffffcc">
<tr>
<td 6idt&="T5O"><b><font color="=5555N5">.ate Gormat</font></b></td>
<td 6idt&="T5O"><b><font color="=5555N5">.ate</font></b></td>
</tr>
<tr>
<td 6idt&="T5O">.a#/Bont&/Eear</td>
<td 6idt&="T5O"><s:date name="current.ate" format="dd/BB/####" /></
td>
</tr>
<tr>
<td 6idt&="T5O">Bont&/.a#/Eear</td>
<td 6idt&="T5O"><s:date name="current.ate" format="BB/dd/####" /></
td>
</tr>
<tr>
<td 6idt&="T5O">Bont&/.a#/Eear</td>
<td 6idt&="T5O"><s:date name="current.ate" format="BB/dd/##" /></td>
</tr>
<tr>
<td 6idt&="T5O">Bont&/.a#/Eear @our<1>:</1>Binute</td>
<td 6idt&="T5O"><s:date name="current.ate" format="BB/dd/## &&:mm"
/></td>
</tr>
<tr>
<td 6idt&="T5O">Bont&/.a#/Eear @our<1>:</1>Binute<1>:</1>Second</td>
<td 6idt&="T5O"><s:date name="current.ate" format="BB/dd/## &&:mm:s
s" /></td>
</tr>
<tr>
<td 6idt&="T5O">/ice .ate :(urrent .ate 7 Time<</td>
<td 6idt&="T5O"><s:date name="current.ate" nice!"false" /></td>
</tr>
<tr>
<td 6idt&="T5O">/ice .ate</td>
<td 6idt&="T5O"><s:date name="current.ate" nice!"true" /></td>
</tr>
</table>

</bod#>
</&tml>
9utut o& the dateTag.4s 8
Include *a +Data *a, "xam!le
In this setion" we are going to desribe the inlude tag. The inlude tag is a generi tag that is
used to inlude a servlet6s output :result of servlet or a !S2 page< to the urrent page.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;inludeTag;
lassM;net.roseindia.inludeTag;C
Bresult
nameM;suess;C9pages9generiTags9inlud
eTag.+spB9resultC
B9ationC
)reate an ation lass as shown below/
includeTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class includeTa" extends 4ctionSupport *
private .ate m#1irt&da#8
public Strin" execute:< throws -xception*
setB#1irt&da#:new .ate:"2an 920 9?NW 99:29:Q5 4B"<<8
return SC((-SS8
+

public .ate "etB#1irt&da#:<*
return m#1irt&da#8
+
+
)reate a simple +sp :#y5irthday.4s< that we want to inlude in our main +sp page
ie..includeTag.4s.
#y5irthday.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>%nclude Ta" :.ata Ta"< -xample!</title>
</&ead>
<bod#>
<b><font color="=5555N5">B# 1irt& .a# :.ate Gormat<</font></b>
<table border="9" 6idt&="QTO" b"color="ffffcc">
<tr>
<td 6idt&="T5O"><b><font color="=5555N5">.ate Gormat</font></b></td>
<td 6idt&="T5O"><b><font color="=5555N5">.ate</font></b></td>
</tr>
<tr>
<td 6idt&="T5O">.a#/Bont&/Eear</td>
<td 6idt&="T5O"><s:date name="m#1irt&da#" format="dd/BB/####" /></t
d>
</tr>
<tr>
<td 6idt&="T5O">Bont&/.a#/Eear</td>
<td 6idt&="T5O"><s:date name="m#1irt&da#" format="BB/dd/####" /></t
d>
</tr>
<tr>
<td 6idt&="T5O">Bont&/.a#/Eear</td>
<td 6idt&="T5O"><s:date name="m#1irt&da#" format="BB/dd/##" /></td>
</tr>
<tr>
<td 6idt&="T5O">Bont&/.a#/Eear @our<1>:</1>Binute</td>
<td 6idt&="T5O"><s:date name="m#1irt&da#" format="BB/dd/## &&:mm" /
></td>
</tr>
<tr>
<td 6idt&="T5O">Bont&/.a#/Eear @our<1>:</1>Binute<1>:</1>Second</td>
<td 6idt&="T5O"><s:date name="m#1irt&da#" format="BB/dd/## &&:mm:ss"
/></td>
</tr>
<tr>
<td 6idt&="T5O">/ice .ate :(urrent .ate 7 Time<</td>
<td 6idt&="T5O"><s:date name="m#1irt&da#" nice="false" /></td>
</tr>
</table>

</bod#>
</&tml>
4ow reate a +sp page using <s%include> tag as shown in the includeTag.4s page. T&e
<s:include value="m#1irt&da#.jsp" />
ta" includes anot&er jsp usin" t&e value parameter
includeTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>%nclude Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">%nclude Ta" :.ata Ta"s<
-xample!</span></&9>
<s:include value="m#1irt&da#.jsp" />
</bod#>
</&tml>
9utut o& the includeTag.4s 8
'aram *a +Data *a, "xam!le
In this setion" we are going to desribe the param tag. The param tag is a generi tag that is used
to parameteri,e other tags. For example the inlude tag and bean tag. The parameters an be
added with or without a name as a key.
The param tag has the following two parameters.
.. name :String< ( the name of the parameter
2. value :Ob+et< ( the value of the parameter
Note8 -hen you delare the param tag" the value an be defined in either a value attribute or as
text between the start and end tag.
Struts behaves a bit different aording to these two situations.
!ase .. Bparam nameM;empname;C'mitB9paramC 1ere the value would be evaluated to the
stak as a *ava.lang.5tring ob+et.
!ase 2. Bparam nameM;empname; valueM;Ainod;9C 1ere the value would be evaluated to the
stak as a *ava.lang.+b*ect ob+et.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;paramTag;C

BresultC9pages9generiTags9paramTag.
+spB9resultC
B9ationC
4ow reate a +sp page to see the working of the param tags.
ara#Tag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>!aram Ta" :.ata Ta"< -xample</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">!aram Ta"
:.ata Ta"s< -xample!</span></&9>
<ui:component>
<ui:param name="empname">;inod</ui:param><br>
<ui:param name="empname">4mit</ui:param><br>
<ui:param name="empname">Sus&il</ui:param>
</ui:component>
</bod#>
</&tml>
9utut o& ara#Tag.4s8
Set *a +Data *a, "xam!le
In this setion" we are going to desribe the Set tag. The set tag is a generi tag that is used to
assign a value to a variable in a speified sope. It is useful when you wish to assign a variable to
a omplex expression and then simply referene that variable eah time rather than the omplex
expression.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;setTag;C

BresultC9pages9generiTags9setTag.+
spB9resultC
B9ationC
4ow reate a +sp page using <s%set> tag as shown in the setTag.4s page. The set tag is used
to assign a value to a variable in a speified sope. The parameters na#e and "alue in the tag
<s%set name!"technolog'Name" value!",-09ava0."&> ats as the name(value pair. 1ere
we set the parameters as name!"technolog'Name" value!"9ava".
setTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Set Ta" :.ata Ta"< -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Set Ta"
:.ata Ta"s< -xample!</span></&9>
<s%set name!"technolog'Name" value!",-09ava0."&>
Tec&nolo"# /ame: <s:propert# value="=tec&nolo"#/ame"/>
</bod#>
</&tml>
9utut o& the setTag.4s8
*ext *a +Data *a, "xam!le
In this setion" we are going to desribe the text tag. The text tag is a generi tag that is used to
render a I.@n text message. Follow one of the three steps/
.. Keep the message to be displayed in a resoure bundle with the same name as the ation that
it is assoiated with ie. reate a properties file in the same pakage as your !ava lass with the
same name as your lass" but with .roerties extension.
2. If the property file does(not work or the message is not found in the resoure bundle" then the
body of the tag will be used as default message.
J. If there is no body" then the name of the message will be used.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;textTag;
lassM;net.roseindia.textTag;C

BresultC9pages9generiTags9textTag.+sp
B9resultC
B9ationC
)reate an ation lass as shown below/
textTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class textTa" extends 4ctionSupport *
public Strin" execute:< throws -xception*
return SC((-SS8
+
+
)reate a property file in the same pakage where your !ava program file :textTag.4a"a< is saved
with the name as ac7age.roerties.
ac7age.roerties
webname. M
http/99www.RoseIndia.net
webname2 M
http/99www.+ava+a,,up.om
webnameJ M
http/99www.newstrakindia.om
4ow reate a +sp page to see the working of the text tags.
The first three tags <s:text name="6ebname9">0<s:text name="6ebname2"> and
<s:text name="6ebnameQ"> uses the ac7age.roerties file to display the text message.
The next tag <s:text name="empname">;inod0 4mit0 Sus&il0 .......</s:text> uses
the body of the tag as a default message.
The last tag <s:text name="empname"></s:text> does not have aess to the
ac7age.roerties files nor does it have a body so it uses name of the message to display.
textTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Text Ta" :.ata Ta"< -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Text Ta"
:.ata Ta"s< -xample!</span></&9>

<s:text name="6ebname9"></s:text><br>
<s:text name="6ebname2"></s:text><br>
<s:text name="6ebnameQ"></s:text><br>
<s:text name="empname">;inod0 4mit0 Sus&il0 .......</s:text><br>
<s:text name="empname"></s:text>
</bod#>
</&tml>
9utut o& the textTag.4s8
'ro!erty *a +Data *a, "xam!le
In this setion" we are going to desribe the property tag. The property tag is a generi tag that is
used to get the property of a value" whih will default to the top of the stak if none is speified.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;propertyTag;
lassM;net.roseindia.propertyTag;C

BresultC9pages9generiTags9propertyTag.+sp
B9resultC
B9ationC
)reate an ation lass as shown/
roertyTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class propert#Ta" extends 4ctionSupport *
public Strin" execute:< throws -xception*
return SC((-SS8
+
+
)reate a bean lass ;co#anyNa#e" as shown/
co#anyNa#e.4a"a
package net.roseindia8
public class compan#/ame *

private Strin" name8
public void set/ame:Strin" name<*
this.name =name 8
+
public Strin" "et/ame:<*
return name8
+
+
)reate a +sp using the tags.
Es8roerty "alueJKHVna#eWK -F it prints the result of my#ean6s get%y#ean2roperty:<
method.
Es8roerty "alueJKna#eK de&aultJK*e&ault ValueK -> it prints the result of
ompany4ame6s get4ame:< method and if it is null" print 6a default value6 instead.
roertyTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>!ropert# Ta" :.ata Ta"< -xample</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">!ropert# Ta"
:.ata Ta"s< -xample!</span></&9>
<! -xample to pic, t&e value t&rou"& bean class >
<s:bean name="net.roseindia.compan#/ame" id="uid">
<s:param name="name">$ose%ndia</s:param>
<s%propert' value!",-name." &><br>
</s:bean>
<! .efault value >
<s%propert' value!"name" default!"3efault 6alue" &>
</bod#>
</&tml>
9utut o& the roertyTag.4s8
Struts 2 *as +/I *as, "xam!les
For# Tags

1. Auto !o#leter ,xa#le
In this setion" we are going to desribe the autoompleter tag. The autoompleter tag
always displays a dropdown list with the options that have at least a partial math with
entered text in the textbox. If the user liks on the dropdown button then all options
shown in the dropdown list.

2. !hec7/ox Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the hekbox tag. The hekbox tag is a 8I tag
that is used to render an 1T%& input element of type hekbox" populated by the
speified property from the AalueStak.

3. !hec7/oxlist Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the hekboxlist tag. The hekboxlist tag is a 8I
tag that reates a series of hekboxes from a list. Setup is like Bs/selet 9C or Bs/radio 9C"
but reates hekbox tags.

4. !o#/o/ox Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the ombobox tag. The ombo box is basially an
1T%& I428T of type text and 1T%& S5&5)T grouped together to give you a ombo
box funtionality.

5. *ateti#eic7er Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the datetimepiker tag. The datetimepiker tag is
a 8I tag that is used to render a date9time piker in a dropdown ontainer.

6. *ou/leselect Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the doubleselet tag. The doubleselet tag is a 8I
tag that renders two 1T%& selet elements with seond one hanging displayed values
depending on seleted entry of first one.

7. File Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the file tag. The file tag is a 8I tag that renders
an 1T%& file input element ahieved through browsing.

8. For# Tag ,xa#le
In this setion" we are going to desribe the form tag. The form tag is a 8I tag that
renders 1T%& an input form.

9. )a/el Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the label tag. The label tag is a 8I tag that is used
to render an 1T%& &'#5& that allow to output la/el8na#e type of ombinations that
has the same format treatment as the rest of 8I ontrols.

10.9tiontrans&erselect Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the Optiontransferselet tag. The
Optiontransferselet tag is a 8I tag that reate an option transfer selet omponent.

11.9tgrou Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the optgroup tag. The optgroup tag is a 8I tag
that reates an optgroup omponent whih needs to resides within a selet tag
<s:select>.

12.6assword Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the password tag. The password tag is a 8I tag
that renders an 1T%& input tag of type password.

13.(adio Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the radio tag. The radio tag is a 8I tag that
renders a radio button input field.

14.(eset Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the reset tag. The reset tag is a 8I tag that is
used together with the form tag to provide form resetting.

15.Select Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the selet tag. The selet tag is a 8I tag that is
used to render a 1T%& input tag of type selet.

16.Su/#it Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the submit tag. The submit tag is a 8I tag that is
used to render a submit button. The submit tag is used together with the form tag to
provide asynhronous form submissions.

17.Textarea Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the textarea tag. The textarea tag is a 8I tag that
is used to render 1T%& textarea.

18.Text&ield Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the textfield tag. The textfield tag is a 8I tag that
is used to render an 1T%& input field of type text.

19.3downselect Tag 0For# Tag1 ,xa#le
In this setion" we are going to desribe the updownselet tag. The updownselet tag is a
8I tag that reates a selet omponent with buttons to move up and down the elements in
the selet omponent.

Non2For# 3' Tags

1. Actionerror and Action#essage Tags 0Non2For# 3' Tags1 ,xa#le
In this setion" we are going to desribe the actionerror and action#essage tags. The
ationerror tag is a 8I tag that renders ation errors:in the +sp pages.< if they exists while
the ationmessage tag renders ation messages if they exists.

2. Fielderror Tag 0Non2For# 3' Tags1 ,xa#le
In this setion" we are going to desribe the fielderror tags. The fielderror tag is a 8I tag
that renders field errors if they exists.

3. Ta//ed6anel 0A4ax Tag1 ,xa#le
In this setion" you will learn about the tabbed2anel tag. This is an '+ax omponent"
where eah tab is either a loal ontent or a remote ontent :refreshed eah time when
user selets that tab<.
4. tree and treenode 0A4ax Tag1 tags ,xa#le
In this setion" you will learn about the tree and treenode tags. These both work with the
'+ax support.

5. *i" 0A4ax Tag1 tag ,xa#le
In this setion" you will learn about the di" tag. The di" tag is an '+ax omponent that is
used with '+ax refreshes the ontents of a partiular setion without refreshing the entire
page.
Auto (om!leter "xam!le
In this setion" we are going to desribe the autoompleter tag. The autoompleter tag always
displays a dropdown list with the options that have at least a partial math with entered text in
the textbox. If the user liks on the dropdown button then all options shown in the dropdown
list. The autoompleter tag generates two input fields. First is ;text;" whose name is speified
with the ;name; attribute and another one is ;hidden; whose name is ;_:name<. Key;" where _
RnameT is the value in the ;name; attribute.
The autoompleter tag loads its options asynhronously when the page loads suggested options
based on the text entered by you in textbox. If the auto)omplete attribute is set to 6true6 :#y
defalut 6false6< then it makes suggestions in the textbox.
SNote8 -hen we use the ;simple; theme" the autoompleter an be used like the )ombo#ox.
-hen used on the ;a+ax; theme" the list an be retrieved from an ation.T
'dd the following ode snippet into the struts.x#l file.
Bation nameM;autoompleter;
lassM;net.roseindia.autoompleter;C

BresultC9pages9autoompleter.+spB9resultC
B9ationC
)reate a list in the ation lass and populate them with various states name of 8.S. as shown in
the ;autoco#leter; lass.
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class autocompleter extends 4ctionSupport*
private Fist state8
public Strin" execute:< throws -xception*
state = new 4rra#Fist:<8
state.add:"4labama"<8
state.add:"4las,a"<8
state.add:"4riSona"<8
state.add:"4r,ansas"<8
state.add:"(alifornia"<8
state.add:"(olorado"<8
state.add:"(onnecticut"<8
state.add:".ela6are"<8
state.add:".istrict of (olumbia"<8
state.add:"Glorida"<8
state.add:"3eor"ia"<8
state.add:"@a6aii"<8
state.add:"%da&o"<8
state.add:"%llinois"<8
state.add:"%ndiana"<8
state.add:"%o6a"<8
state.add:"Kansas"<8
state.add:"Kentuc,#"<8
state.add:"Fouisiana"<8
state.add:"Baine"<8
state.add:"Bar#land"<8
state.add:"Bassac&usetts"<8
state.add:"Bic&i"an"<8
state.add:"Binnesota"<8
state.add:"Bississippi"<8
state.add:"Bissouri"<8
state.add:"Bontana"<8
state.add:"/ebras,a"<8
state.add:"/evada"<8
state.add:"/e6 @amps&ire"<8
state.add:"/e6 2erse#"<8
state.add:"/e6 Bexico"<8
state.add:"/e6 Eor,"<8
state.add:"/ort& (arolina "<8
state.add:"/ort& .a,ota"<8
state.add:"D&io"<8
state.add:"D,la&oma"<8
state.add:"Dre"on"<8
state.add:"!enns#lvania"<8
state.add:"$&ode %sland"<8
state.add:"Sout& (arolina "<8
state.add:"Sout& .a,ota"<8
state.add:"Tennessee"<8
state.add:"Texas"<8
state.add:"Cta&"<8
state.add:";ermont"<8
state.add:";ir"inia"<8
state.add:"Aas&in"ton"<8
state.add:"Aest ;ir"inia "<8
state.add:"Aisconsin"<8
state.add:"A#omin""<8
return SC((-SS8
+
public Fist "etState:<*
return state8
+
+
<s%autocompleter theme!"simple" list!"state" 5tateName&> it reates a autoompleter
list with the name of 8.S. states.
autoco#leter.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Struts 2 4utocompleter -xample!</title>
<s:&ead t&eme="ajax" />
</&ead>
<bod#>
<&9>Struts 2 4utocompleter -xample!</&9>
<s:label name="state/ame" value="Select State /ame:" />
<s:autocompleter t&eme="simple" list="state" name="State/ame"/>
</bod#>
</&tml>
9utut o& the autoco#leter.4s 8
-hen you enter the 66 letter in the textbox. =ou get the following names/
(hec5.ox *a +Form *a, "xam!le
In this setion" we are going to desribe the hekbox tag. The hekbox tag is a 8I tag that is
used to render an 1T%& input element of type hekbox" populated by the speified property
from the AalueStak.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;hekboxTag;C

BresultC9pages9uiTags9hekboxTag.
+spB9resultC
B9ationC
)reate a +sp using the tag <s%checkbox> It renders an 1T%& input element of type hehbox.
chec7/oxTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>(&ec,box :Gorm Ta"< Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">(&ec,box Ta" -xample!
</span></&9>
<b>Sex</b><br>
<s%checkbox label!"7ale" name!"male" value!"true" &><br>
<s%checkbox label!":emale" name!"male" &>
</bod#>
</&tml>
9utut o& the chec7/oxTag.4s /
(hec5.oxlist *a +Form *a, "xam!le
In this setion" we are going to desribe the hekboxlist tag. The hekboxlist tag is a 8I tag
that reates a series of hekboxes from a list. Setup is like Bs/selet 9C or Bs/radio 9C" but reates
hekbox tags.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;hekboxlistTag;
lassM;net.roseindia.hekboxlistTag;C

BresultC9pages9uiTags9hekboxlistTag.+spB9res
ultC
B9ationC
)reate two lists in the ation lass and populate them with various items as shown in the
;chec7/oxlistTag; lass.
chec7/oxlistTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class c&ec,boxlistTa" extends 4ctionSupport*

private Fist fruits8
private Fist animals8
public Strin" execute:<throws -xception*
fruits = new 4rra#Fist:<8
fruits.add:"4pple"<8
fruits.add:"Ban"o"<8
fruits.add:"Dran"e"<8
fruits.add:"!ine 4pple"<8
animals = new 4rra#Fist:<8
animals.add:".o""<8
animals.add:"-lep&ant"<8
animals.add:"Dx"<8
animals.add:"Gox"<8
return SC((-SS8
+
public Fist "etGruits:<*
return fruits8
+
public Fist "et4nimals:<*
return animals8
+
+
)reate a +sp using the tags
<s%checkboxlist name!":ruitsname" list!"fruits" &> it prints a
heboxlist with name Fruits and )reates a series of hekboxes from fruits list of the ation
lass ;chec7/oxlistTag;. <s%checkboxlist name!"Animals
name" list!"animals" &> it prints a heboxlist with name 'nimals and )reates a
series of hekboxes from animals list of the ation lass ;chec7/oxlistTag;.
chec7/oxlistTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>(&ec,boxlist :Gorm Ta"< Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">(&ec,boxlist
Ta" -xample!</span></&9>
<b>Gruits</b><br>
<s%checkboxlist name!":ruitsname" list!"fruits" &><br>
<b>4nimals</b><br>
<s%checkboxlist name!"Animalsname" list!"animals" &><br>
</bod#>
</&tml>
9utut o& the chec7/oxlistTag.4s8
(om.o.ox *a +Form *a, "xam!le
In this setion" we are going to desribe the ombobox tag. The ombo box is basially an
1T%& I428T of type text and 1T%& S5&5)T grouped together to give you a ombo box
funtionality. =ou an plae text in the I428T ontrol by using the S5&5)T ontrol or type it in
diretly in the text field
.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;omboboxTag;
lassM;net.roseindia.omboboxTag;C

BresultC9pages9uiTags9omboboxTag.+spB9resul
tC
B9ationC
)reate a list in the ation lass and populate it with various items as shown in the
; co#/o/oxTag; lass.
co#/o/oxTag.4a"a
package net.roseindia8
i mport com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class comboboxTa" extends 4ctionSupport*

private Fist fruits8
public Strin" execute:<throws -xception*
fruits = new 4rra#Fist:<8
fruits.add:"4pple"<8
fruits.add:"Ban"o"<8
fruits.add:"Dran"e"<8
fruits.add:"!ine 4pple"<8
return SC((-SS8
+
public Fist "etGruits:<*
return fruits8
+
+
)reate a +sp using the tags <s:combobox>
T&e ta"
<s:combobox label="(olors /ame" name="color/ames" &eader;alue=" !lease Sel
ect "
&eaderKe#="9" list="*V1lac,V0V3reenV0VA&iteV0VEello6V0V$edV0V!in,V+" /> prints a
combobox with name color Name and an 1T%& I428T of type text and 1T%& S5&5)T
grouped together reated using the list.
T&e ta" <s%checkboxlist name!"Animals
name" list!"animals" &> prints a combobox with name :ruits Name and
an 1T%& I428T of type text and 1T%& S5&5)T grouped together reated using the
;fruits" list of the ation lass ;chec7/oxlistTag;.
co#/o/oxTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>(ombobox :Gorm Ta"< Ta" -xample!</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">(ombobox
Ta" -xample!</span></&9>
<s:form>
<s%combobox label!"Colors Name" name!"colorNames"
header6alue!" )lease 5elect "
header4e'!"/" list!"-0;lack020<reen020=hite020>ellow02
01ed020)ink0." &><br>

<! Cse arra# list ><br>
<s%combobox label!":ruits Name" name!"fruitsNames"
header6alue!" )lease 5elect "
header4e'!"/" list!"fruits" &>
</s:form>
</bod#>
</&tml>
9utut o& the co#/o/oxTag.4s8
Datetime!ic5er *a +Form *a, "xam!le
In this setion" we are going to desribe the datetimepiker tag. The datetimepiker tag is a 8I
tag that is used to render a date9time piker in a dropdown ontainer. ' stand(alone
0ateTime2iker widget
that makes it easy to selet a date9time or inrement by week" month" and9or year.
It is possible to ustomi,e the user(visible formatting with either the 6format&ength6 :long" short"
medium or full< or 6displayFormat6 attributes. #y default urrent loale will be used.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;datetimepikerTag;
lassM;net.roseindia.inludeTag;C

BresultC9pages9uiTags9datetimepikerTag.+spB9r
esultC
B9ationC
)reate an ation lass as shown/
includeTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class includeTa" extends 4ctionSupport *
private 0ate m#1irt&da#8
public Strin" execute:< throws -xception*
setB#1irt&da#:new .ate:"2an 920 9?NW 99:29:Q5 4B"<<8
return SC((-SS8
+
public void setB#1irt&da#:.ate date<*
this.m#1irt&da# = date8
+
public .ate "etB#1irt&da#:<*
return m#1irt&da#8
+
+
)reate a +sp using the tag <s%datetimepicker>
This tag renders a date9time piker in a dropdown ontainer.
The tag <s%datetimepicker name!"m';irthda'" label!"7' ;irth 3a' (dd77
'''')" displa':ormat!"dd77''''" &> piks the data from the ation lass ;includeTagK
using the parameter na#eJKm';irthda'" usin" t&e displa# format as
displa':ormat!"dd77''''".
dateti#eic7erTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>.atetimepic,er :Gorm Ta"< Ta" -xample!</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
<s:&ead t&eme="ajax" />
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">.atetimepic,er
Ta" -xample!</span></&9>
<s%datetimepicker name!"m';irthda'" label!"7' ;irth 3a'
(dd77'''')" displa':ormat!"dd77''''" &>
</bod#>
</&tml>
9utut o& the dateti#eic7erTag.4s8
Dou.leselect *a +Form *a, "xam!le
In this setion" we are going to desribe the doubleselet tag. The doubleselet tag is a 8I tag that
renders two 1T%& selet elements with seond one hanging displayed values depending on
seleted entry of first one.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;doubleseletTag;C

BresultC9pages9uiTags9doubleseletTa
g.+spB9resultC
B9ationC
)reate a +sp using the tag <s%doubleselect> that renders two 1T%& selet elements with
seond one hanging displayed values depending on seleted entry of first one. This tag ontains
various parameters/
The headerXey parameter sets the header key of the seond list. %ust not be empty. In our ase
we have set it to"9"
The headerValue parameter sets the header value of the seond list. In our ase we have set it to
;((( 2lease Selet (((;
The dou/leNa#e parameter sets the name for omplete omponent. In our ase we have set it as
/ double/ame="dis&es"
The dou/le)ist sets the seond iterable soure to populate from. In our ase we have set it as /
doubleFist="top == V(olorV I *V1lac,V0V3reenV0VA&iteV0
VEello6V0V$edV0V!in,V+ : * V4ppleV0V1ananaV0V3rapesV0VBan"oV+"
dou/leselectTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>.oubleselect Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">.oubleselect Ta" -xample!
</span></&9>
<s:form>
<s:doubleselect label="Select %tem"
&eader;alue=" !lease Select "
&eaderKe#="9" list="*V(olorV0VGruitsV+"
double/ame="dis&es"
doubleFist="top == V(olorV I *V1lac,V0V3reenV0VA&iteV0
VEello6V0V$edV0V!in,V+ : * V4ppleV0V1ananaV0V3rapesV0VBan"oV+" />
</s:form>
</bod#>
</&tml>
9utut o& the dou/leselectTag.4s8
File *a +Form *a, "xam!le
In this setion" we are going to desribe the file tag. The file tag is a 8I tag that renders an
1T%& file
input element ahieved through browsing.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;fileTag;C

BresultC9pages9uiTags9fileTag.+s
pB9resultC
B9ationC
)reate a +sp using the tag <s:file>. It renders an 1T%& file input element.
The parameter na#e is used to set a name for element whih we have used as
na#eM"uploadGile".
and the parameter accet is the 1T%& aept attribute that indiates the aepted file mime
types whih we have used as accetM"text/'".
&ileTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Gile Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Gile Ta" -xample!</span></&9>
<b>Gile /ame</b>
<s:form>
<s:file name="uploadGile" accept="text/'" />
</s:form>
</bod#>
</&tml>
9utut o& the &ileTag.4s
On liking the ;#rowse..; button. =ou will see a window that an be used to browse a file to
upload.
Form *a "xam!le
In this setion" we are going to desribe the form tag. The form tag is a 8I tag that renders
1T%& an input form. The remote form allows the form to be submitted without the page being
refreshed. The results from the form an be inserted into any 1T%& element on the page.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;formTag;C

BresultC9pages9uiTags9formTag.+sp
B9resultC
B9ationC
)reate a +sp using the tag <s%form>.%t renders 1T%& as an input form
&or#Tag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Gorm Ta" -xample!</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Gorm Ta" -xample</span></&>
<s%form>
<s:textfield name="username" label="Fo"in name"/>
<s:pass6ord name="pass6ord" label="!ass6ord"/>
<s:submit value="Fo"in" ali"n="center"/>
<&s%form>
</bod#>
</&tml>
9utut o& the &or#Tag.4s8
$a.el *a +Form *a, "xam!le
In this setion" we are going to desribe the label tag. The label tag is a 8I tag that is used
to render an 1T%& &'#5& that allows us to output la/el8na#e type of ombinations that has
the same format treatment as the rest of 8I ontrols.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;labelTag;C

BresultC9pages9uiTags9labelTag.+s
pB9resultC
B9ationC
)reate a +sp using the tag <s%label>. %t renders an 1T%& &'#5& that allows us to output
Es8 la/el na#eJK K "alueJK K -F ombination that has the same format treatment as the rest of
8I ontrols.
la/elTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Fabel Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Fabel Ta" -xample</span></&>
<s:form>
<s%label name!"name" value! "Name" &>
<s%label name!"roll" value! "1oll" &>
<s%label name!"address" value! "Address% " &>
</s:form>
</bod#>
</&tml>
9utut o& the la/elTag.4s8
6!tiontransferselect *a +Form *a, "xam!le
In this setion" we are going to desribe the Optiontransferselet tag. The Optiontransferselet
tag is a 8I tag that reates an option transfer selet omponent. There are two Bselet ...C tags
with buttons in the middle of them" whih allows options in eah of the Bselet ...C to be moved
between them. It auto(selets all its elements upon its ontaining form submission.
4OT5/ The id and dou/le'd parameters are not needed to supply as they will get generated
when the optiontransferselet tag is being used in a form tag. The generated id and doubleId will
be BformZidCZBoptiontransferseletZdouble4ameC and
BformZidCZBoptiontransferseletZdouble4ameC respetively.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;optiontransferseletTag;C

BresultC9pages9uiTags9optiontransferselet
Tag.+spB9resultC
B9ationC
)reate a +sp using the tag <s%optiontransferselect> that reates an option transfer selet
omponent. This tag ontains various parameters/
The label parameter sets label expression used for rendering an element speifi label. In our
ase we have set it to "?mplo'ee 1ecords"
The name parameter sets the name for the element. In our ase we have set it to
"left5ide?mplo'ee1ecords"
The left@itle parameter sets the left title. In our ase we have set it to "1ose8ndia"
The right@itle parameter sets the right title. In our ase we have set it to "9ava9aAABp"
The header4e' sets the header key of the given list. It must not be empty. In our ase we have
set it to/"header4e'"
The header6alue sets the header value of the given list. In our ase we have set it
to/" )lease 5elect "
The doubleName sets the name for omplete omponent. In our ase we have set it
to/"right5ide?mplo'ee1ecords"
The doubleCeader4e' sets the header key for the seond list. In our ase we have set it
to/"doubleCeader4e'"
The doubleCeader6alue sets the header value for the seond list. In our ase we have set it
to/" )lease 5elect "
otiontrans&erselectTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Dptiontransferselect Ta" -xample!</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Dptiontransferselect
Ta" -xample!</span></&>
<s:form>
<s%optiontransferselect
label!"?mplo'ee 1ecords"
name!"left5ide?mplo'ee1ecords"
left@itle!"1ose8ndia"
right@itle!"9ava9aAABp"
list!"-03eepak 4umar02 05ushil 4umar0206inod 4umar0203eepak 7onth'02
03eepak 7ihanti02 05ushil 4umar02 01avi 4ant 4umar0."
header4e'!"header4e'"
header6alue!" )lease 5elect "
doubleName!"right5ide?mplo'ee1ecords"
double#ist!"-0Amar 3eep )atel02 0Amit 4umar020Chandan 4umar02
0Noor 4umar020@ammana 4umari0."
doubleCeader4e'!"doubleCeader4e'"
doubleCeader6alue!" )lease 5elect " &>
</s:form>
</bod#>
</&tml>
9utut o& the otiontrans&erselectTag.4s8
6!trou! *a +Form *a, "xam!le
In this setion" we are going to desribe the optgroup tag. The optgroup tag is a 8I tag that
reates an optgroup omponent whih needs to reside within a selet tag <s:select>.
'dd the following ode snippet
into the struts.xml file.
struts.x#l
Bation nameM;optgroupTag;C

BresultC9pages9uiTags9optgroupTag.+
spB9resultC
B9ationC
)reate a +sp using the tag <s:opt"roup> 6it&in t&e <s%select> ta". %t reates an
optgroup omponent. This tag ontains few parameters/
The la/el parameter sets the label attribute In our ase we have set it to "@ard6are
" and "5oftware".
otgrouTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Dpt"roup Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Dpt"roup Ta" -xample!</span></&>
<s:form>
<s:select label="!lease Select"
name="select"
list="O*=*V!$D3$4BB%/3V:V!ro"rammin"V0 V.4T414S-V:V.ata1aseV0
VA-14!!F%(4T%D/V:VAeb4pplicationV++">
<s:opt"roup label="@ard6are"
list="O*=*V(!CV:V(enteral !rocessin" CnitV0VBDCS-V:VBouseV0
VK-E1D4$.V:VKe#boardV++" />
<s:opt"roup label="Soft6are"
list="O*=*VSEST-B SDGTA4$-V:VS#stem Soft6areV0V4!!F%(4T%D/
SDGTA4$-V:V4pplication Soft6areV++" />
</s:select>
</s:form>
</bod#>
</&tml>
9utut o& the otgrouTag.4s8
'assword *a +Form *a, "xam!le
In this setion" we are going to desribe the password tag. The password tag is a 8I tag that
renders an 1T%&
input tag of type password.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;passwordTag;C

BresultC9pages9uiTags9passwordTag.+
spB9resultC
B9ationC
)reate a +sp using the tag <s%password>. It renders an 1T%& input tag of type password.
asswordTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>!ass6ord Ta" -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">!ass6ord Ta" -xample!</span></&>
<s:form>
<s:pass6ord label="-nter !ass6ord" name="pass6ord" siSe="95" maxlen"t&="N"
/>
</s:form>
</bod#>
</&tml>
9utut o& the asswordTag.4s8
)adio *a +Form *a, "xam!le
In this setion" we are going to desribe the radio tag. The radio tag is a 8I tag that renders a
radio button input field.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;radioTag;
lassM;net.roseindia.hekboxlistTag;C

BresultC9pages9uiTags9radioTag.+spB9resultC
B9ationC
)reate an ation lass with two lists as shown below/
chec7/oxlistTag.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class c&ec,boxlistTa" extends 4ctionSupport*

private Fist fruits8
private Fist animals8
public Strin" execute:<throws -xception*
fruits = new 4rra#Fist:<8
fruits.add:"4pple"<8
fruits.add:"Ban"o"<8
fruits.add:"Dran"e"<8
fruits.add:"!ine 4pple"<8
animals = new 4rra#Fist:<8
animals.add:".o""<8
animals.add:"-lep&ant"<8
animals.add:"Dx"<8
animals.add:"Gox"<8
return SC((-SS8
+
public Fist "etGruits:<*
return fruits8
+
public Fist "et4nimals:<*
return animals8
+
+
)reate a +sp using the tag <s:radio>.%t renders a radio button input field.
radioTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>$adio Ta" -xample!</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">$adio Ta" -xample!</span></&>
<s:form>
<s:radio label="Gruits" name="fruitsname" list="fruits" />
<s:radio label="4nimals" name="animalsname" list="animals" />
</s:form>
</bod#>
</&tml>
9utut o& the radioTag.4s8

)eset *a +Form *a, "xam!le
In this setion" we are going to desribe the reset tag. The reset tag is a 8I tag that is used with
the form tag to provide form resetting.
It renders a reset button.
The reset an have two different types of rendering/
input/ renders as html Binput typeM;reset;...C
button/ renders as html Bbutton typeM;reset;...C
The button type has advantages as it adds the possibility to separate the submitted value from
the text shown on the button fae.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;resetTag;C

BresultC9pages9uiTags9resetTag.+s
pB9resultC
B9ationC
)reate a +sp using the tag <s%reset>. It renders a reset button whih provides the form
resetting.
resetTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>$eset Ta" -xample!</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">$eset Ta" -xample!</span></&>
<s:form>
<s:textfield name="username" label="Cser /ame" siSe="9T" maxlen"t&="95" />
<s:pass6ord name="pass6ord" label="!ass6ord" siSe="9T" maxlen"t&="95" />
<s%reset value!"1eset" &>
</s:form>
</bod#>
</&tml>
9utut o& the resetTag.4s8
Select *a +Form *a, "xam!le
In this setion" we are going to desribe the selet tag. The selet tag is a 8I tag that is used to
render an 1T%& input tag of type selet.
'dd the following ode snippet
into the struts.xml file.
struts.x#l
Bation nameM;seletTag;
lassM;net.roseindia.week0ay;C

BresultC9pages9uiTags9seletTag.+spB9res
ultC
B9ationC
)reate an ation lass with a list populated with various items as shown below/
wee7*ay.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class 6ee,.a# extends 4ctionSupport*

private Fist da#8
public Strin" execute:<throws -xception*
da# = new 4rra#Fist:<8
da#.add:"Sunda#"<8
da#.add:"Bonda#"<8
da#.add:"Tuesda#"<8
da#.add:"Aednesda#"<8
da#.add:"T&ursda#"<8
da#.add:"Grida#"<8
da#.add:"Saturda#"<8
return SC((-SS8
+
public Fist "et.a#:<*
return da#8
+
+
)reate a +sp using the tag <s%select> that reates an 1T%& input tag of type selet. This tag
ontains various parameters/
The label parameter sets the label expression used for rendering an element speifi label. In
our .st ase we have set it to "5elect 3a'"
The name parameter sets the name for the element. In our .st ase we have set it to
"da'sname"
The header4e' sets key for first item in list. It must not be empty and wrongly speified. In both
ases we have set it to/"/"
@he header6alue sets t&e ;alue expression for t&e first item in t&e list. %n
bot& cases 6e &ave set it to%" )lease 5elect "
selectTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Select Ta" -xample</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Select Ta" -xample!</span></&>
<s:form>
<s%select label!"5elect 3a'"
name!"da'sname"
header4e'!"/"
header6alue!" )lease 5elect "
list!"da'"
&>
<s%select label!"5elect 7onth"
name!"monthname"
header4e'!"/"
header6alue!" )lease 5elect "
list!"D-0E/0%09anuar'020EF0%0:ebruar'020EG0%07arch020EH0%0April02
0EI0%07a'020EJ0%09une020EK0%09ul'020EL0%0August020EM0%05eptember020/E0%
0+ctober020//0%0November020/F0%03ecember0."
&>
</s:form>
</bod#>
</&tml>
9utut o& the selectTag.4s /
Su.mit *a +Form *a, "xam!le
In this setion" we are going to desribe the submit tag. The submit tag is a 8I tag that is used to
render a submit button. The submit tag is used with the form tag to provide asynhronous form
submissions. The submit an have three different types of rendering/
input/ renders as html Binput typeM;submit;...C
image/ renders as html Binput typeM;image;...C
button/ renders as html Bbutton typeM;submit;...C
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;submitTag;C

BresultC9pages9uiTags9submitTag.+
spB9resultC
B9ationC
)reate a +sp using the tag <s%submit> that renders a submit button. This tag ontains various
parameters/
The value parameter presets the value of input element. In our .st ase we have set it to
"5ubmit"
The t'pe parameter sets the type of submit to use. Aalid values are input" button and image. In
our ase we have set it to "image"
The src supplies an image sr for image type submit button. It will have no effet for types
input and button. In our ase we have set it to/"&strutsFtags&pages&ui@ags&submit.gif"
@he align sets @TBF ali"n attribute. %n our case 6e &ave set it to%"center"
su/#itTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Submit Ta" -xample</title>

</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Submit Ta" -xample!</span></&>
<s:form>
<s:textfield name="username" label="Cser /ame" siSe="9T" maxlen"t&="95" />
<s:textfield name="pass6ord" label="!ass6ord" siSe="9T" maxlen"t&="95" />
<s%submit value!"5ubmit" &>
<! To use "if button >
<s%submit t'pe!"image" src!"&strutsFtags&pages&ui@ags&submit.gif"
align!"center" &>
</s:form>
</bod#>
</&tml>
9utut o& the su/#itTag.4s8
*extarea *a +Form *a, "xam!le
In this setion" we are going to desribe the textarea tag. The textarea tag is a 8I tag that is used
to render an 1T%& textarea.
'dd the following ode snippet
into the struts.xml file.
struts.x#l
Bation nameM;textareaTag;C

BresultC9pages9uiTags9textareaTag.+
spB9resultC
B9ationC
)reate a +sp using the tag <s%textarea > that renders an 1T%& textarea tag.
<s%textarea label!"3escription" name!"description" cols!"/I" rows!"/E" &> ta"
displays an 1T%& textarea with label e3ual to 0esription" olumn valueM.> and row
valueM.*.
textareaTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Textarea Ta" -xample</title>
<lin, &ref="<s:url value="/css/main.css"/>" rel="st#les&eet"
t#pe="text/css"/>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Textarea Ta" -xample!</span></&>
<s:form>
<s%textarea label!"3escription" name!"description" cols!"/I" rows!"/E" &>
</s:form>
</bod#>
</&tml>
9utut o& the textareaTag.4s8
*extfield *a +Form *a, "xam!le
In this setion" we are going to desribe the textfield tag. The textfield tag is a 8I tag that is used
to render an 1T%& input field of type text.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;textfieldTag;C

BresultC9pages9uiTags9textfieldTag.+
spB9resultC
B9ationC
)reate a +sp using the tag <s%textfield > that renders an 1T%& input field of type text.
<s%textfield label!"?mplo'ee Name" name!"empname" siAe!"/I" maxlength!"/E" &>
ta" displays an 1T%& text field with label e3ual to ?mplo'ee Name 6it& len"t& of 9T
columns.
text&ieldTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Textfield Ta" -xample</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Textfield Ta" -xample!
</span></&>
<s:form>
<s%textfield label!"?mplo'ee Name" name!"empname" siAe!"/I" maxlength!"/E"
&>
</s:form>
</bod#>
</&tml>
9utut o& the text&ieldTag.4s8
/!downselect *a +Form *a, "xam!le
In this setion" we are going to desribe the updownselet tag. The updownselet tag is a 8I tag
that reates a selet omponent with buttons to move up and down the elements in the selet
omponent. -hen the ontaining form is submitted" its elements will be submitted in the order
they are arranged :top to bottom<.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;updownseletTag;C

BresultC9pages9uiTags9updownseletTag
.+spB9resultC
B9ationC
)reate a +sp using the tag <s%updownselect> that reates a selet omponent with buttons to
move up and down. This tag ontains various parameters/
The name parameter presets the value of input element. In our ase we have set it to
"da'sname"
The #o"e*own)a/el parameter is used for the text to display on the move down button. In our
ase we have set it to "7ove 3own"
The #o"e3)a/el parameter is used for the text to display on the move up button. In our ase
we have set it to/"7ove Bp"
@he selectAll#abel parameter is used for the text to be displayed on the selet all button In
our ase we have set it to/"5elect All"
udownselectTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Cpdo6nselect Ta" -xample</title>

</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">Cpdo6nselect Ta" -xample!
</span></&>
<s:form>
<s%updownselect
list!"D-0E/0%09anuar'020EF0%0:ebruar'020EG0%07arch020EH0%0April020EI0%07a
'02
0EJ0%09une020EK0%09ul'020EL0%0August020EM0%05eptember020/E0%0+ctober020//0%0N
ovember0
20/F0%03ecember0."
name!"da'sname"
header4e'!"/"
header6alue!" )lease 5elect "
moveBp#abel!"7ove Bp"
move3own#abel!"7ove 3own"
selectAll#abel!"5elect All"
&>
</s:form>
</bod#>
</&tml>
9utut o& the udownselectTag.4s8
Actionerror and Actionmessae *as +7on-Form /I *as, "xam!le
In this setion" we are going to desribe the actionerror and action#essage tags. The
ationerror tag is a 8I tag that renders ation errors :in the +sp pages.< if they exists while the
ationmessage tag renders ation messages if they exists.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;ationerrorTag;C
BresultC9pages9uiTags9&ogin.+spB9resultC
B9ationC
Bation nameM;login;
lassM;net.roseindia.hekAalid8ser;C
Bresult
nameM;input;C9pages9uiTags9&ogin.+spB9result
C
Bresult
nameM;error;C9pages9uiTags9error.+spB9resultC

BresultC9pages9uiTags9valid8ser.+spB9resultC
B9ationC
)reate an ation lass that uses methods addAction7essage(5tring) and
addAction?rror(5tring) within the exeute:< method. The addAction7essage(5tring)
will print the passed string on the suess +sp page while the addAction?rror(5tring) will
print the passed string on the error +sp page.
chec7Valid3ser.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class c&ec,;alidCser extends 4ctionSupport *
private Strin" username = null8
private Strin" pass6ord = null8
public Strin" execute:< throws -xception*
if ::"etCsername:<.eMuals:"$oseindia"<< 77
:"et!ass6ord:<.eMuals:"$oseindia"<<<*

addAction7essage("6alid BserN")O
return SC((-SS8
+
else*
addAction?rror("8nvalid BserN")O
return -$$D$8
+
+
//Set and "et t&e user name
public void setCsername:Strin" name<*
username = name8
+
public Strin" "etCsername:<*
return username8
+
//set and "et t&e pass6ord
public void set!ass6ord:Strin" pass<*
pass6ord = pass8
+
public Strin" "et!ass6ord:<*
return pass6ord8
+
+
)reate a &ogin +sp page as shown/
)ogin.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>4ctionerror Ta" -xample!</title>
<bod#>
<s:form action="login" met&od="!DST">
<s:textfield label="Cser /ame" name="username" siSe="25" maxlen"t&="95" />
<s:pass6ord label="!ass6ord" name="pass6ord" siSe="25" maxlen"t&="95" />
<s:submit value="Submit" />
</s:form>

</bod#>
</&tml>
)reate a +sp page that will display your error message :when fails to logged(in< using the empty
<s%actionerror &> tag as shown/
error.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>4ctionerror Ta" -xample!</title>
<bod#>
<&9>
<s%actionerror &>
</&9>
<a &ref="/struts2ta"s/roseindia/actionerrorTa".action">3o 1ac,</a>
</bod#>
</&tml>
)reate a +sp page that will display a message :when suessfully logged(in< using the empty
<s%actionmessage &> tag as shown/
"alid3ser.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>4ctionerror Ta" -xample!</title>
<bod#>
<&9>
<s%actionmessage &>
</&9>
</bod#>
</&tml>
you will see the output of the )ogin.4s as shown below/
5nter the wrong user name but orret password in the login page.
you will get the following output/
5nter the orret user name but inorret password in the login page
you will get the following output/
5nter orret values in both fields of the login page
you will get the following output/
Fielderror *a +7on-Form /I *as, "xam!le
In this setion" we are going to desribe the fielderror tags. The fielderror tag is a 8I tag that
renders field errors if they exists.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;field5rror;C

BresultC9pages9uiTags9loginFielderrorTag.+spB9r
esultC
B9ationC
Bation nameM;hek8ser;
lassM;net.roseindia.hekField;C
Bresult
nameM;input;C9pages9uiTags9loginFielderrorTag
.+spB9resultC
Bresult
nameM;error;C9pages9uiTags9fielderrorTag.+spB9
resultC

BresultC9pages9uiTags9valid8ser.+spB9resultC
B9ationC
0evelop an ation lass using add:ield?rror(5tring fieldName2 5tring error7essage)
met&od. This method adds an error message for a given field to the orresponding +sp page.
chec7Field.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class c&ec,Gield extends 4ctionSupport *
private Strin" username = null8
private Strin" pass6ord = null8
public Strin" execute:< throws -xception*
if ::"etCsername:<.eMuals:"$oseindia"<< 77
:"et!ass6ord:<.eMuals:"$oseindia"<<<*
add4ctionBessa"e:";alid Cser!"<8
return SC((-SS8
+
if:!:"etCsername:<.eMuals:"$oseindia"<<<
add:ield?rror("username"2"8nvalid usernameN")O
if:!:"et!ass6ord:<.eMuals:"$oseindia"<<<
add:ield?rror("password"2"8nvalid passwordN")O
return -$$D$8
+
//Set and "et t&e user name
public void setCsername:Strin" username<*
this.username = username8
+
public Strin" "etCsername:<*
return username8
+
//set and "et t&e pass6ord
public void set!ass6ord:Strin" pass<*
pass6ord = pass8
+
public Strin" "et!ass6ord:<*
return pass6ord8
+
+
)reate a &ogin +sp page as shown/
loginFielderrorTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Gielderror Ta" -xample!</title>
<bod#>
<s:form action="c&ec,Cser" met&od="!DST">
<s:textfield label="Cser /ame" name="username" siSe="25" maxlen"t&="95" />
<s:pass6ord label="!ass6ord" name="pass6ord" siSe="25" maxlen"t&="95" />
<s:submit value="Submit" />
</s:form>

</bod#>
</&tml>
)reate a +sp page that will display your field error messages :when fails to logged(in< using the
empty <s%fielderror&> tag as shown/
&ielderrorTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Gielderror Ta" -xample!</title>
<bod#>
<&9>
<s%fielderror &>

</&9>
<a &ref="/struts2ta"s/roseindia/field-rror.action">3o 1ac,</a>
</bod#>
</&tml>
)reate a +sp page that will display your messages :when sueed to logged(in< using the empty
<s:actionmessa"e /> tag as shown/
"alid3ser.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Gielderror Ta" -xample!</title>
<bod#>
<&9>
<s%actionmessage &>
</&9>
</bod#>
</&tml>
you will see the output of the loginFielderrorTag.4s as shown below/
5nter the wrong user name and orret password in the login page
you will get the following output/
5nter the orret user name and wrong password in the login page
you will get the following output/
5nter inorret values in both fields of the login page
you will get the following output/
5nter orret values in both fields of the login page
you will get the following output/
*a..ed'anel +A8ax *a, "xam!le
In this setion" you will learn about the tabbed2anel tag. This is an '+ax omponent" where eah
tab is either a loal ontent or a remote ontent :refreshed eah time when user selets that tab<.
To use tabbed2anel tag" the head tag must be inluded on the +sp page and must be onfigured
for performane
or debugging purposes. 1owever" If you want to use the ookie feature then you must provide a
uni3ue id for the tabbedpanel omponent. This is used for identifying the name of omponent
that is stored by the ookie.
'dd the following ode snippet
into the struts.x#l file.
struts.x#l
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Software Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">
<action name="Tabbed!anel">
<result>/pa"es/tabbedpanel.jsp</result>
</action>
<! 4dd actions &ere >
</package>
<! 4dd pac,a"es &ere >
</struts>
)reate a +sp using the tag <s%tabbed)anel>. This tag is used for reating the tabs.

ta//ed6ane.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<s:&ead t&eme="ajax" debu"="true"/>
</&ead>
<bod#>
<table border="9" 6idt&="T5O">
<tr>
<td 6idt&="955O">
<s:tabbed!anel id="test" >
<s:div id="one" label="Tab 9" t&eme="ajax" labelposition="top" >
T&is is t&e first panel.
$ose%ndia.nt<br>
2ava2aSSCp.com<br>
/e6sTrac,%ndia.com
</s:div>
<s:div id="t6o" label="Tab 2" t&eme="ajax">
T&is is t&e second panel.
</s:div>

<s:div id="t&ree" label="Tab Q" t&eme="ajax">
T&is is t&e t&ird panel.<br>
2ava Tutorial<br>
!@! Tutorial<br>
Finux Tutorial
</s:div>
<s:div id="four" label="Tab W" t&eme="ajax">
T&is is t&e fort& panel.
</s:div>
</s:tabbed!anel>
</td>
</tr>
</table>
</bod#>
</&tml>
9utut8
-hen you run the above example" you get the output as/
-hen you lik the ;Tab 2; then you get the ontent of ;Tab 2; as shown/
If you lik ;Tab J; then you get the ontent of ;Tab J; as shown/
If you lik the ;Tab ?; you get the ontent of ;Tab ?; as/
tree and treenode +A8ax *a, tas "xam!le
In this setion" you will learn about the tree and treenode tags. These both work with the '+ax
support.
tree8 This is a tree widget
with '!'$ support. 4ormally this tag uses the ;id; attribute. The ;id; attribute is re3uired if the
;seleted4otifyTopi; or the ;href; attribute is going to be used.
treenode8 This is a tree node whih renders a tree node within a tree widget with '!'$
support. The following of the two ombinations are used depending on the re3uirement like the
tree is needed to be onstruted dynamially or statially.
*yna#ically
id ( This is an id of tree node.
title ( This is as like a label to be displayed for the tree node
Statically
root4ode ( This is the parent node where the tree is derived form.
nodeId2roperty ( This is the urrent tree node6s id.
nodeTitle2roperty ( This is the urrent tree node6s title.
hild)olletion2roperty ( This is the urrent tree node6s hildren.
In this setion" you will learn about the tree and treenode tags. These both work with the '+ax
support.
tree8 This is a tree widget
with '!'$ support. 4ormally this tag uses the ;id; attribute. The ;id; attribute is re3uired if the
;seleted4otifyTopi; or the ;href; attribute is going to be used.
treenode8 This is a tree node whih renders a tree node within a tree widget with '!'$
support. The following of the two ombinations are used depending on the re3uirement like the
tree is needed to be onstruted dynamially or statially.
*yna#ically
id ( This is an id of tree node.
title ( This is as like a label to be displayed for the tree node
Statically
root4ode ( This is the parent node where the tree is derived form.
nodeId2roperty ( This is the urrent tree node6s id.
nodeTitle2roperty ( This is the urrent tree node6s title.
hild)olletion2roperty ( This is the urrent tree node6s hildren.
Di% +A8ax *a, ta "xam!le
In this setion" you will learn about the di" tag. The di" tag is an '+ax omponent that is used
with '+ax that refreshes the ontent of a partiular setion without refreshing the entire page.
The di" tag when used with '+ax refreshes the ontent of a partiular setion without refreshing
the entire page.
1T%& E*'V -F tag reated by '+ax div tag inludes it6s ontent and is used to obtain it6s ontent
through a remote =+)Htt(e:uest all through the do+o framework.
TH, F9))9W'NG ATT('53T,S A(, VA)'* 'F A$A= 'S !9NF'G3(,*
hre&8 Set 6href6 as a url tag referene value.
errorText8 If a re3uest makes any error then 6errorText6 is displayed.
a&ter)oading8 8se 6notifyTopis6 sine 6after&oading6 has been 0epreated.
executeScrits8 Setting the value of 6exeuteSripts6 to true allows the +avasript setions
to exeute in the returned text.
loadingText8 On making the re3uest the 6targets6 element displays the text 6loadingText6.
listenToics8 The omma separated list 6listenTopis6 is the list of topi names that is
used to trigger a re3uest.
handler8 The funtion that takes are of any '!'$ re3uest is termed as 6handler6. The
funtion uses 0o+o6s widget and dom node as parameters to be passed<.
&or#'d8 The fields of the formId are used to seriali,e and pass as the parameters in the
re3uest.
&or#Filter8 The funtion 6formFilter6 is used to filter the fields that are to be seriali,ed
whih reeives the elements as parameters and returns true if the element is inluded.
targets8 1ere 6targets6 is the list of ids to be updated with the text returned from re3uest.
noti&yToics8 6notifyTopis6 is nothing but the list of topi names separated by ommas
to be published. It takes three parameters.
1. data8 is the html or +son ob+et while type M 6error6 or type M 6error6
2. tye8 it should be of the type U/e&oreU before re3uesting" UloadU whenever re3uest
sueeds and UerrorU whenever the re3uest fails.
3. re:uest8 it re3uests for the +avasript ob+ets if typeM6error6 or
typeM6load6.
show,rrorTransortText8 6show5rrorTransportText6 displays the errors on target.
indicator
The attribute 6updateFre36 refreshes after a ertain time period" speified in miliseonds.
The attribute 6autoStart6 starts the timer automatially while sets to true whih is the default
value.
The attribute 6startTimer&istenTopis6 is used to start the timer whenever 6startTimer&istenTopi6
is the omma(separated list of topis.
The attribute 66stopTimer&istenTopis6 is used to start the timer whenever
66stopTimer&istenTopis6 is the omma(separated list of topis.
6show&oadingText6 displays the loaded text on targets while 6separateSript6 runs eah sript in
eah sope that is uni3ue for eah 0iv.
'dd the following ode snippet into the struts.xml file.
strurts.x#l
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<include file="strutsdefault.xml"/>
<! 4dd pac,a"es &ere >
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">
<action name="div">
<result>/pa"es/div.jsp</result>
</action>
</package>
</struts>
)reate a +sp using the tag <s%div>.

di".4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>-nter first and last name</title>
<s:&ead t&eme="ajax" debu"="false"/>
</&ead>
<bod#>
<s:url id="test" value="/pa"es/mas,.jsp" />
<s:div
id="one"
t&eme="ajax"
&ref="O*test+">
</s:div>
</bod#>
</&tml>
#as7.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>-nter first and last name</title>
<s:&ead t&eme="ajax" debu"="false"/>
</&ead>
<bod#>
<s:div id="mas,;alue" >
<div st#le="position:absolute8top:958 left:258 6idt&:Q558
&ei"&t:9XT8bac,"roundcolor:=-T-T-T8">
<&Q>-nter first and last name:</&Q>
<s:form t&eme="ajax" action="doBas,">
<s:textfield name="firstname" label="Girstname" />
<s:textfield name="lastname" label="Fastname" />
<s:submit value="Submit" t&eme="ajax" tar"ets="mas,;alue" />
</s:form>
</div>
<br>

<div id="N" st#le="position:absolute8top:958 left:QT58
6idt&:Q558 &ei"&t:9>58bac,"roundcolor:=-T-T-T8">
<&Q>Dutput: </&Q>
Girstname : <s:propert# value="firstname" />
<br><br>
Fastname : <s:propert# value="lastname" />
</div>
</s:div>
</bod#>
</&tml>
9utut8
Actionerror and Actionmessae *as +7on-Form /I *as, "xam!le
In this setion" we are going to desribe the actionerror and action#essage tags. The
ationerror tag is a 8I tag that renders ation errors :in the +sp pages.< if they exists while the
ationmessage tag renders ation messages if they exists.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;ationerrorTag;C
BresultC9pages9uiTags9&ogin.+spB9resultC
B9ationC
Bation nameM;login;
lassM;net.roseindia.hekAalid8ser;C
Bresult
nameM;input;C9pages9uiTags9&ogin.+spB9result
C
Bresult
nameM;error;C9pages9uiTags9error.+spB9resultC

BresultC9pages9uiTags9valid8ser.+spB9resultC
B9ationC
)reate an ation lass that uses methods addAction7essage(5tring) and
addAction?rror(5tring) within the exeute:< method. The addAction7essage(5tring)
will print the passed string on the suess +sp page while the addAction?rror(5tring) will
print the passed string on the error +sp page.
chec7Valid3ser.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class c&ec,;alidCser extends 4ctionSupport *
private Strin" username = null8
private Strin" pass6ord = null8
public Strin" execute:< throws -xception*
if ::"etCsername:<.eMuals:"$oseindia"<< 77
:"et!ass6ord:<.eMuals:"$oseindia"<<<*

addAction7essage("6alid BserN")O
return SC((-SS8
+
else*
addAction?rror("8nvalid BserN")O
return -$$D$8
+
+
//Set and "et t&e user name
public void setCsername:Strin" name<*
username = name8
+
public Strin" "etCsername:<*
return username8
+
//set and "et t&e pass6ord
public void set!ass6ord:Strin" pass<*
pass6ord = pass8
+
public Strin" "et!ass6ord:<*
return pass6ord8
+
+
)reate a &ogin +sp page as shown/
)ogin.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>4ctionerror Ta" -xample!</title>
<bod#>
<s:form action="login" met&od="!DST">
<s:textfield label="Cser /ame" name="username" siSe="25" maxlen"t&="95" />
<s:pass6ord label="!ass6ord" name="pass6ord" siSe="25" maxlen"t&="95" />
<s:submit value="Submit" />
</s:form>

</bod#>
</&tml>
)reate a +sp page that will display your error message :when fails to logged(in< using the empty
<s%actionerror &> tag as shown/
error.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>4ctionerror Ta" -xample!</title>
<bod#>
<&9>
<s%actionerror &>
</&9>
<a &ref="/struts2ta"s/roseindia/actionerrorTa".action">3o 1ac,</a>
</bod#>
</&tml>
)reate a +sp page that will display a message :when suessfully logged(in< using the empty
<s%actionmessage &> tag as shown/
"alid3ser.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>4ctionerror Ta" -xample!</title>
<bod#>
<&9>
<s%actionmessage &>
</&9>
</bod#>
</&tml>
you will see the output of the )ogin.4s as shown below/
5nter the wrong user name but orret password in the login page.
you will get the following output/
5nter the orret user name but inorret password in the login page
you will get the following output/
5nter orret values in both fields of the login page
you will get the following output/
Fielderror *a +7on-Form /I *as, "xam!le
In this setion" we are going to desribe the fielderror tags. The fielderror tag is a 8I tag that
renders field errors if they exists.
'dd the following ode snippet into the struts.xml file.
struts.x#l
Bation nameM;field5rror;C

BresultC9pages9uiTags9loginFielderrorTag.+spB9r
esultC
B9ationC
Bation nameM;hek8ser;
lassM;net.roseindia.hekField;C
Bresult
nameM;input;C9pages9uiTags9loginFielderrorTag
.+spB9resultC
Bresult
nameM;error;C9pages9uiTags9fielderrorTag.+spB9
resultC

BresultC9pages9uiTags9valid8ser.+spB9resultC
B9ationC
0evelop an ation lass using add:ield?rror(5tring fieldName2 5tring error7essage)
met&od. This method adds an error message for a given field to the orresponding +sp page.
chec7Field.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class c&ec,Gield extends 4ctionSupport *
private Strin" username = null8
private Strin" pass6ord = null8
public Strin" execute:< throws -xception*
if ::"etCsername:<.eMuals:"$oseindia"<< 77
:"et!ass6ord:<.eMuals:"$oseindia"<<<*
add4ctionBessa"e:";alid Cser!"<8
return SC((-SS8
+
if:!:"etCsername:<.eMuals:"$oseindia"<<<
add:ield?rror("username"2"8nvalid usernameN")O
if:!:"et!ass6ord:<.eMuals:"$oseindia"<<<
add:ield?rror("password"2"8nvalid passwordN")O
return -$$D$8
+
//Set and "et t&e user name
public void setCsername:Strin" username<*
this.username = username8
+
public Strin" "etCsername:<*
return username8
+
//set and "et t&e pass6ord
public void set!ass6ord:Strin" pass<*
pass6ord = pass8
+
public Strin" "et!ass6ord:<*
return pass6ord8
+
+
)reate a &ogin +sp page as shown/
loginFielderrorTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Gielderror Ta" -xample!</title>
<bod#>
<s:form action="c&ec,Cser" met&od="!DST">
<s:textfield label="Cser /ame" name="username" siSe="25" maxlen"t&="95" />
<s:pass6ord label="!ass6ord" name="pass6ord" siSe="25" maxlen"t&="95" />
<s:submit value="Submit" />
</s:form>

</bod#>
</&tml>
)reate a +sp page that will display your field error messages :when fails to logged(in< using the
empty <s%fielderror&> tag as shown/
&ielderrorTag.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Gielderror Ta" -xample!</title>
<bod#>
<&9>
<s%fielderror &>

</&9>
<a &ref="/struts2ta"s/roseindia/field-rror.action">3o 1ac,</a>
</bod#>
</&tml>
)reate a +sp page that will display your messages :when sueed to logged(in< using the empty
<s:actionmessa"e /> tag as shown/
"alid3ser.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Gielderror Ta" -xample!</title>
<bod#>
<&9>
<s%actionmessage &>
</&9>
</bod#>
</&tml>
you will see the output of the loginFielderrorTag.4s as shown below/
5nter the wrong user name and orret password in the login page
you will get the following output/
5nter the orret user name and wrong password in the login page
you will get the following output/
5nter inorret values in both fields of the login page
you will get the following output/
5nter orret values in both fields of the login page
you will get the following output/
*a..ed'anel +A8ax *a, "xam!le
In this setion" you will learn about the tabbed2anel tag. This is an '+ax omponent" where eah
tab is either a loal ontent or a remote ontent :refreshed eah time when user selets that tab<.
To use tabbed2anel tag" the head tag must be inluded on the +sp page and must be onfigured
for performane or debugging purposes. 1owever" If you want to use the ookie feature then you
must provide a uni3ue id for the tabbedpanel omponent. This is used for identifying the name of
omponent that is stored by the ookie.
'dd the following ode snippet into the struts.x#l file.
struts.x#l
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">
<action name="Tabbed!anel">
<result>/pa"es/tabbedpanel.jsp</result>
</action>
<! 4dd actions &ere >
</package>
<! 4dd pac,a"es &ere >
</struts>
)reate a +sp using the tag <s%tabbed)anel>. This tag is used for reating the tabs.

ta//ed6ane.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<s:&ead t&eme="ajax" debu"="true"/>
</&ead>
<bod#>
<table border="9" 6idt&="T5O">
<tr>
<td 6idt&="955O">
<s:tabbed!anel id="test" >
<s:div id="one" label="Tab 9" t&eme="ajax" labelposition="top" >
T&is is t&e first panel.
$ose%ndia.nt<br>
2ava2aSSCp.com<br>
/e6sTrac,%ndia.com
</s:div>
<s:div id="t6o" label="Tab 2" t&eme="ajax">
T&is is t&e second panel.
</s:div>

<s:div id="t&ree" label="Tab Q" t&eme="ajax">
T&is is t&e t&ird panel.<br>
2ava Tutorial<br>
!@! Tutorial<br>
Finux Tutorial
</s:div>
<s:div id="four" label="Tab W" t&eme="ajax">
T&is is t&e fort& panel.
</s:div>
</s:tabbed!anel>
</td>
</tr>
</table>
</bod#>
</&tml>
9utut8
-hen you run the above example" you get the output as/
-hen you lik the ;Tab 2; then you get the ontent of ;Tab 2; as shown/
If you lik ;Tab J; then you get the ontent of ;Tab J; as shown/
If you lik the ;Tab ?; you get the ontent of ;Tab ?; as/
*a..ed'anel +A8ax *a, "xam!le
In this setion" you will learn about the tabbed2anel tag. This is an '+ax omponent" where eah
tab is either a loal ontent or a remote ontent :refreshed eah time when user selets that tab<.
To use tabbed2anel tag" the head tag must be inluded on the +sp page and must be onfigured
for performane or debugging purposes. 1owever" If you want to use the ookie feature then you
must provide a uni3ue id for the tabbedpanel omponent. This is used for identifying the name of
omponent that is stored by the ookie.
'dd the following ode snippet into the struts.x#l file.
struts.x#l
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">
<action name="Tabbed!anel">
<result>/pa"es/tabbedpanel.jsp</result>
</action>
<! 4dd actions &ere >
</package>
<! 4dd pac,a"es &ere >
</struts>
)reate a +sp using the tag <s%tabbed)anel>. This tag is used for reating the tabs.

ta//ed6ane.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<s:&ead t&eme="ajax" debu"="true"/>
</&ead>
<bod#>
<table border="9" 6idt&="T5O">
<tr>
<td 6idt&="955O">
<s:tabbed!anel id="test" >
<s:div id="one" label="Tab 9" t&eme="ajax" labelposition="top" >
T&is is t&e first panel.
$ose%ndia.nt<br>
2ava2aSSCp.com<br>
/e6sTrac,%ndia.com
</s:div>
<s:div id="t6o" label="Tab 2" t&eme="ajax">
T&is is t&e second panel.
</s:div>

<s:div id="t&ree" label="Tab Q" t&eme="ajax">
T&is is t&e t&ird panel.<br>
2ava Tutorial<br>
!@! Tutorial<br>
Finux Tutorial
</s:div>
<s:div id="four" label="Tab W" t&eme="ajax">
T&is is t&e fort& panel.
</s:div>
</s:tabbed!anel>
</td>
</tr>
</table>
</bod#>
</&tml>
9utut8
-hen you run the above example" you get the output as/
-hen you lik the ;Tab 2; then you get the ontent of ;Tab 2; as shown/
If you lik ;Tab J; then you get the ontent of ;Tab J; as shown/
If you lik the ;Tab ?; you get the ontent of ;Tab ?; as/
tree and treenode +A8ax *a, tas "xam!le
In this setion" you will learn about the tree and treenode tags. These both work with the '+ax
support.
tree8 This is a tree widget
with '!'$ support. 4ormally this tag uses the ;id; attribute. The ;id; attribute is re3uired if the
;seleted4otifyTopi; or the ;href; attribute is going to be used.
treenode8 This is a tree node whih renders a tree node within a tree widget with '!'$
support. The following of the two ombinations are used depending on the re3uirement like the
tree is needed to be onstruted dynamially or statially.
*yna#ically
id ( This is an id of tree node.
title ( This is as like a label to be displayed for the tree node
Statically
root4ode ( This is the parent node where the tree is derived form.
nodeId2roperty ( This is the urrent tree node6s id.
nodeTitle2roperty ( This is the urrent tree node6s title.
hild)olletion2roperty ( This is the urrent tree node6s hildren.
'dd the following ode snippet to the struts.x#l file.
struts.x#l
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">

<action name="Tree/ode">
<result>/pa"es/treenode.jsp</result>
</action>
<! 4dd actions &ere >
</package>
<! 4dd pac,a"es &ere >
</struts>
)reate a +sp using the tag <s%tree>. This tag is used for rendering a tree widget.
Similarly the tag <s%treenode> renders a tree node 6it& a label attac&ed to
t&e created tree 6id"et e"..
<s%treenode theme!"a*ax" id!"subchildF" label!"subchildF" &> ta"
attac&es a ne6 node to t&e created tree 6it& a tree node &avin"
id="subc&ild2" and a label="subc&ild2".
treenode.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<s:&ead t&eme="ajax" debu"="true"/>
</&ead>
<bod#>
<s:tree t&eme="ajax" id="root" label="$oot">
<s:treenode t&eme="ajax" id="c&ild9" label="<b>(&ild 9</b>" />
<s:treenode t&eme="ajax" id="subc&ild9" label="Sub(&ild 9">
<s:treenode t&eme="ajax" id="subc&ild2" label="Sub(&ild 2" />
<s:treenode t&eme="ajax" id="subc&ildQ" label="Sub(&ild Q" />
</s:treenode>
<s:treenode t&eme="ajax" id="c&ild2" label="<b>c&ild 2</b>" />
</s:tree>
</bod#>
</&tml>
9utut8
-hen you run the above example" you get/

Di% +A8ax *a, ta "xam!le


In this setion" you will learn about the di" tag. The di" tag is an '+ax omponent that is used
with '+ax that refreshes the ontent of a partiular setion without refreshing the entire page.
The di" tag when used with '+ax refreshes the ontent of a partiular setion without refreshing
the entire page.
1T%& E*'V -F tag reated by '+ax div tag inludes it6s ontent and is used to obtain it6s ontent
through a remote =+)Htt(e:uest all through the do+o framework.
TH, F9))9W'NG ATT('53T,S A(, VA)'* 'F A$A= 'S !9NF'G3(,*
hre&8 Set 6href6 as a url tag referene value.
errorText8 If a re3uest makes any error then 6errorText6 is displayed.
a&ter)oading8 8se 6notifyTopis6 sine 6after&oading6 has been 0epreated.
executeScrits8 Setting the value of 6exeuteSripts6 to true allows the +avasript
setions to exeute in the returned text.
loadingText8 On making the re3uest the 6targets6 element displays the text 6loadingText6.
listenToics8 The omma separated list 6listenTopis6 is the list of topi names that is
used to trigger a re3uest.
handler8 The funtion that takes are of any '!'$ re3uest is termed as 6handler6. The
funtion uses 0o+o6s widget and dom node as parameters to be passed<.
&or#'d8 The fields of the formId are used to seriali,e and pass as the parameters in the
re3uest.
&or#Filter8 The funtion 6formFilter6 is used to filter the fields that are to be seriali,ed
whih reeives the elements as parameters and returns true if the element is inluded.
targets8 1ere 6targets6 is the list of ids to be updated with the text returned from re3uest.
noti&yToics8 6notifyTopis6 is nothing but the list of topi names separated by ommas
to be published. It takes three parameters.
1. data8 is the html or +son ob+et while type M 6error6 or type M 6error6
2. tye8 it should be of the type U/e&oreU before re3uesting" UloadU whenever re3uest
sueeds and UerrorU whenever the re3uest fails.
3. re:uest8 it re3uests for the +avasript ob+ets if typeM6error6 or
typeM6load6.
show,rrorTransortText8 6show5rrorTransportText6 displays the errors on target.
indicator
The attribute 6updateFre36 refreshes after a ertain time period" speified in miliseonds.
The attribute 6autoStart6 starts the timer automatially while sets to true whih is the default
value.
The attribute 6startTimer&istenTopis6 is used to start the timer whenever 6startTimer&istenTopi6
is the omma(separated list of topis.
The attribute 66stopTimer&istenTopis6 is used to start the timer whenever
66stopTimer&istenTopis6 is the omma(separated list of topis.
6show&oadingText6 displays the loaded text on targets while 6separateSript6 runs eah sript in
eah sope that is uni3ue for eah 0iv.
'dd the following ode snippet into the struts.xml file.
strurts.x#l
<Ixml version="9.5" encodin"="CTGN" I>
<!.D(TE!- struts !C1F%(
"//4pac&e Soft6are
Goundation//.T. Struts (onfi"uration 2.5//-/"
"&ttp://struts.apac&e.or"/dtds/struts2.5.dtd">
<struts>
<! $ose %ndia Struts 2 Tutorials >
<constant name="struts.enable..#namicBet&od%nvocation" value="false" />
<constant name="struts.devBode" value="true" />
<include file="strutsdefault.xml"/>
<! 4dd pac,a"es &ere >
<package name="roseindia" namespace="/roseindia" extends="strutsdefault">
<action name="div">
<result>/pa"es/div.jsp</result>
</action>
</package>
</struts>
)reate a +sp using the tag <s%div>.

di".4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>-nter first and last name</title>
<s:&ead t&eme="ajax" debu"="false"/>
</&ead>
<bod#>
<s:url id="test" value="/pa"es/mas,.jsp" />
<s:div
id="one"
t&eme="ajax"
&ref="O*test+">
</s:div>
</bod#>
</&tml>
#as7.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>-nter first and last name</title>
<s:&ead t&eme="ajax" debu"="false"/>
</&ead>
<bod#>
<s:div id="mas,;alue" >
<div st#le="position:absolute8top:958 left:258 6idt&:Q558
&ei"&t:9XT8bac,"roundcolor:=-T-T-T8">
<&Q>-nter first and last name:</&Q>
<s:form t&eme="ajax" action="doBas,">
<s:textfield name="firstname" label="Girstname" />
<s:textfield name="lastname" label="Fastname" />
<s:submit value="Submit" t&eme="ajax" tar"ets="mas,;alue" />
</s:form>
</div>
<br>

<div id="N" st#le="position:absolute8top:958 left:QT58
6idt&:Q558 &ei"&t:9>58bac,"roundcolor:=-T-T-T8">
<&Q>Dutput: </&Q>
Girstname : <s:propert# value="firstname" />
<br><br>
Fastname : <s:propert# value="lastname" />
</div>
</s:div>
</bod#>
</&tml>
9utut8
Struts 2 Date "xam!les
In this setion we will disuss the date proessing funtionalities available in the Struts 2
Framework. 'fter reading the tutorials you will lean how to use date funtions provided by
Struts 2 Framework.
1. *ate For#at ,xa#les
In this tutorials you will learn about 0ate Format funtion in Struts 2. -e have provided
fully tested example ode to illustrate the onepts.

2. Struts 2 dateic7er ,xa#le
In this setion we will show you how to develop datetimepiker in struts 2. Struts 2 uses
the do+o toolkit for reating date piker.
Struts 2 Date Format "xam!les
In this tutorial you will learn about 0ate Format funtion in Struts 2. -e have provided fully
tested example ode to illustrate the onepts. =ou an opy the ode and use it for your fast
development.
Struts *ate tag
Struts date tag is used to output the date into re3uired format. It an be used to format the date
into several different formats. Syntax of the date tag is/
Bs/date nameM;today0ate; formatM;yyyy(%%(dd; 9C
6ara#eters
Following table shows the parameters of date tag.
Na#e (e:uired*e&ault ,"aluated Tye *escrition
format false false String The date format pattern
id false true String It will be used id tag in the 1T%&
name true true String
The date value whih is to be
formatted
nie false false true #oolean
-hether to print out the date
niely
The nie format is very interesting. The following table shows" how it will format the date
output/
i.@n key default
struts.date.format.past R*T ago
struts.date.format.future in R*T
struts.date.format.seonds an instant
struts.date.format.minutes R*"hoie".Wone minute\.BR*T minutesT
struts.date.format.hours
R*"hoie".Wone hour\.BR*T hoursTR."hoie"*W\.W" one minute\.B"
R.T minutesT
struts.date.format.days
R*"hoie".Wone day\.BR*T daysTR."hoie"*W\.W" one hour\.B" R.T
hoursT
struts.date.format.years
R*"hoie".Wone year\.BR*T yearsTR."hoie"*W\.W" one day\.B" R.T
daysT
Writing ,xa#le
In this example we will use 0ate#ean ation lass to get the urrent date of the system. This
urrent date will be used in our example. 1ere is the ode of 0ate#ean.+ava
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util..ate8
/''
' <p> ;alidate a user lo"in. </p>
'/
public class .ate1ean extends 4ctionSupport *

public Strin" execute:< throws -xception *
setToda#.ate:new .ate:<<8
return SC((-SS8
+
// Csername propert#
/''
' <p>Gield to store Toda#Vs .ate.</p>
' <p/>
'/
private .ate toda#.ate8
/''
' <p>!rovide Toda#Vs .ate.</p>
'
' Preturn $eturns t&e Toda#s date.
'/
public .ate "etToda#.ate:< *
return toda#.ate8
+
/''
' <p>Store ne6 .ate</p>
'
' Pparam value T&e username to set.
'/
public void setToda#.ate:.ate value< *
toda#.ate = value8
+
+
'dd the following entry in the struts.xml file in order to reate ation mapping/
Bation nameM;Format0ate; lassM;net.roseindia.0ate#ean;C
BresultC9pages9dateformat.+spB9resultC
B9ationC
Following +sp file:date&or#at.4s< shows the usage of date tag/
BYX taglib prefixM;s; uriM;9struts(tags; YC
BhtmlC
BheadC
BtitleCStruts 2 Format 0ate 5xampleFB9titleC
Blink hrefM;Bs/url valueM;9ss9main.ss;9C; relM;stylesheet;
typeM;text9ss;9C
B9headC
BbodyC
Bs/form ationM;Format0ate; methodM;2OST;C
BtrC
BtdC0ate in :yyyy(%%(dd< Format/B9tdC
BtdC
BbCEs8date na#eJKtoday*ateK &or#atJKyyyy2++2ddK -FB9bC
B9tdC
B9trC
BtrC
BtdC0ate in :%%9dd9yyyy hh/mm '%92%< Format/B9tdC
BtdC
BbCEs8date na#eJKtoday*ateK &or#atJK++-dd-yyyy UatU hh8## aK -FB9bC
B9tdC
B9trC
BtrC
BtdC0ate in :dd(%%%(yyyy hh/mm '%92%< Format/B9tdC
BtdC
BbCEs8date na#eJKtoday*ateK &or#atJKdd2+++2yyyy UatU hh8## aK -FB9bC
B9tdC
B9trC
BtrC
BtdC0ate in :dd9%%9yyyy hh/mm< Format/B9tdC
BtdC
BbCEs8date na#eJKtoday*ateK &or#atJKdd-++-yyyy hh8##K -FB9bC
B9tdC
B9trC
BtrC
BtdC4ie Format/B9tdC
BtdC
BbCEs8date na#eJKtoday*ateK &or#atJKyyyy2++2ddK niceJKtrueK-FB9bC
B9tdC
B9trC
B9s/formC
B9bodyC
B9htmlC
Output of the program/

In this setion you learnt how to use Struts 2 0ate format tag.
Struts 2 datetime!ic5er "xam!le
In this setion we will show you how to develop datetimepiker in struts 2. Struts 2 uses the do+o
toolkit for reating date piker. In Struts 2 its very easy to reate date time piker.
The Es8dateti#eic7er ...-F tag
The Struts 2 Bs/datetimepiker ...C atually renders date9time piker in the dropdown ontainer.
-hen user liks on the alendar ion the date9time piker is displayed on the form.
Struts 2 date piker is atually 0o+o widget" that makes it easy to selet a date. It also provides
easy way to selet any date9month9year very fast. The date time piker will make your web
appliation very user friendly.
Writing ti#e ic7er code
'tion lass to get today6s date is 0ate#ean. 1ere is the ode of 0ate#ean.+ava
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util..ate8
/''
' <p> ;alidate a user lo"in. </p>
'/
public class .ate1ean extends 4ctionSupport *

public Strin" execute:< throws -xception *
setToda#.ate:new .ate:<<8
return SC((-SS8
+
// Csername propert#
/''
' <p>Gield to store Toda#Vs .ate.</p>
' <p/>
'/
private .ate toda#.ate8
/''
' <p>!rovide Toda#Vs .ate.</p>
'
' Preturn $eturns t&e Toda#s date.
'/
public .ate "etToda#.ate:< *
return toda#.ate8
+
/''
' <p>Store ne6 .ate</p>
'
' Pparam value T&e username to set.
'/
public void setToda#.ate:.ate value< *
toda#.ate = value8
+
+
'dd the following entry in the struts.xml file in order to reate ation mapping/
Bation nameM;0ateTime2iker; lassM;net.roseindia.0ate#ean;C
BresultC9pages9datepiker.+spB9resultC
B9ationC
Following +sp file:dateic7er.4s< shows the usage of datepiker tag/
BYX taglib prefixM;s; uriM;9struts(tags; YC
BhtmlC
BheadC
BtitleCStruts 2 Format 0ate 5xampleFB9titleC
Blink hrefM;Bs/url valueM;9ss9main.ss;9C; relM;stylesheet;
typeM;text9ss;9C
Es8head the#eJKa4axK -F
B9headC
BbodyC
Bs/form ationM;0ateTime2iker; methodM;2OST;C
Es8dateti#eic7er na#eJKtoday*ateK la/elJKFor#at 0yyyy2++2dd1K
dislayFor#atJKyyyy2++2ddK-F
Es8dateti#eic7er na#eJKtoday*ateK la/elJKFor#at 0dd2+++2yyyy1K
dislayFor#atJKdd2+++2yyyyK-F
B9s/formC
B9bodyC
B9htmlC
Struts 2 date piker is do+o widget so" it is neessary to generate the lient side !avaSript ode.
The Es8head the#eJKa4axK -F generates the lient side do+o speifi +ava sript. 1ere is the
ode generated by this tag/
<lin, rel="st#les&eet"
&ref="/struts2tutorial/struts/x&tml/st#les.css" t#pe="text/css"/>
<script lan"ua"e="2avaScript" t#pe="text/javascript">
// .ojo confi"uration
dj(onfi" = *
base$elative!at&: "/struts2tutorial/struts/dojo"0
is.ebu": false0
bind-ncodin": "CTGN"0
debu"4t4ll(osts: true // not needed0 but allo6s t&e ;en,man debu""er
to 6or, 6it& t&e includes
+8
</script>
<script lan"ua"e="2avaScript" t#pe="text/javascript"
src="/struts2tutorial/struts/dojo/dojo.js"></script>
<script lan"ua"e="2avaScript" t#pe="text/javascript"
src="/struts2tutorial/struts/simple/dojo$eMuire.js"></script>
<script lan"ua"e="2avaScript" t#pe="text/javascript"
src="/struts2tutorial/struts/ajax/dojo$eMuire.js"></script>
<script lan"ua"e="2avaScript" t#pe="text/javascript"
src="/struts2tutorial/struts/(ommonGunctions.js"></script>
The ode/
Es8dateti#eic7er na#eJKtoday*ateK la/elJKFor#at 0yyyy2++2dd1K
dislayFor#atJKyyyy2++2ddK-F
generates the date9time piker on the form.
Following table summari,es the format by datepiker omponent/
For#at *escrition
dd This format is used to display day in two digits format
d Try to display day in one digit format" if annot use 2 digit format
%% The format displays month in two digits format
% It try to display month in one digits format" if annot use 2 digit format
yyyy 0isplay year in four digits format
yy 0isplay the last two digits of the year
y 0isplay the last digits of the year
1ere is the output of the program

In this setion we have studied how to use Struts 2 datepiker ontrol.
Struts 2 Format "xam!les
In this setion you will learn how to format 0ate and numbers in Struts 2 Framework. Our Struts
2 Format 5xamples are very easy to grasp and you will learn these onepts in very small time.
If you start developing any real world web appliation" at some point of time you will delve into
the problem of displaying the date and number in some speifi format. =ou an easily write
your ode and then format the output as string in your ation lass. #ut there is some drawbak it
like/
=our ode are not aware of i.@n. It will be very diffiult to adapt to different loals.
=our ation lass are also lutter with unneessary ode.
Struts 2 in(built formatting funtionality an save you from above problem. =ou an use s/text
tag built(in formatting funtionality to format your date and numbers.
Stes to *e"elo ,xa#le code
-rite 'tion lass
In the ation lass we are reating three fields/
private String produt4ameS
private 0ouble produt)ostS
private 0ate order0ateS
The values in these variables will be used for displaying on the +sp page. 1ere is the ode of
ation lass :Order#ean.+ava</
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util..ate8
/''
' <p> ;alidate a user lo"in. </p>
'/
public class Drder1ean extends 4ctionSupport *
private Strin" product/ame8
private .ouble product(ost8
public Strin" execute:< throws -xception *
setDrder.ate:new .ate:<<8
set!roduct/ame:"%(- (ream"<8
set!roduct(ost:952.5N<8
return SC((-SS8
+
// Drder .ate propert#
/''
' <p>Gield to store Toda#Vs .ate.</p>
' <p/>
'/
private .ate order.ate8
/''
' <p>!rovide Toda#Vs .ate.</p>
'
' Preturn $eturns t&e Toda#s date.
'/
public .ate "etDrder.ate:< *
return order.ate8
+
/''
' <p>Store ne6 .ate</p>
'
' Pparam value T&e Drder date to set.
'/
public void setDrder.ate:.ate value< *
order.ate = value8
+
public .ouble "et!roduct(ost:< *
return product(ost8
+
public void set!roduct(ost:.ouble product(ost< *
this.product(ost = product(ost8
+
public Strin" "et!roduct/ame:< *
return product/ame8
+
public void set!roduct/ame:Strin" product/ame< *
this.product/ame = product/ame8
+
+
The exeute method of ation lass populates 2rodut 4ame" 2rodut ost and Order date.
public Strin" execute:< throws -xception *
setDrder.ate:new .ate:<<8
set!roduct/ame:"%(- (ream"<8
set!roduct(ost:952.5N<8
return SC((-SS8
+
Writing $S6 age
In the following +sp page :struts2&or#at.4s< you an view the atual usage of the tag.
BYX taglib prefixM;s; uriM;9struts(tags; YC
BhtmlC
BheadC
BtitleCStruts 2 Format 5xampleFB9titleC
Blink hrefM;Bs/url valueM;9ss9main.ss;9C; relM;stylesheet;
typeM;text9ss;9C
B9headC
BbodyC
Bs/form ationM;Struts2Format; methodM;2OST;C
BtrC
Btd alignM;right;C2rodut 4ame/B9tdC
BtdC
BbCEs8text na#eJKroduct.na#eKF
Es8ara# na#eJK"alueK "alueJKroductNa#eK-F
E-s8textF
B9bC
B9tdC
B9trC
BtrC
Btd alignM;right;C2rodut ost/B9tdC
BtdC
Es8text na#eJKroduct.costK F
Es8ara# na#eJK"alueK "alueJKroduct!ostK-F
E-s8textF
B9tdC
B9trC
BtrC
Btd alignM;right;COrder 0ate/B9tdC
BtdC
BbCEs8text na#eJKroduct.order*ateKF
Es8ara# na#eJK"alueK "alueJKorder*ateK-F
E-s8textF
B9bC
B9tdC
B9trC
B9s/formC
B9bodyC
B9htmlC
2lease note that the formatting for roduct.na#e% roduct.cost and roduct.order*ate are
defined in the pakage.properties message resoure file.
*e&ining the &or#atting in roerties &ile
In Struts 2 the formatting is defined in the message resoure file :pakage.properties<. The
pakage.properties file is saved in the diretory :pakage< where your ation lass resides. 1ere
is the ontent of pakage.properties file/
produt.ostM 8S0 R*"number"WW*.**T
produt.order0ate M R*"date"dd(%%%(yyyyT
produt.name M R*T
So" you an easily define or hange the formatting of output +ust modifying the properties file.
+odi&ication in struts.x#l
'dd the following line in struts.xml file/
Bation nameM;Struts2Format; lassM;net.roseindia.Order#ean;C
BresultC9pages9struts2format.+spB9resultC
B9ationC
To test the program" ompile and pakage the ode and then start tomat. Type
http/99loalhost/@*@*9struts2tutorial9roseindia9Struts2Format.ation in the browser to view the
result. =our browser should show the following output/
In this setion you learnt how to use Struts 2 Format funtionality.
Struts 2 File /!load
In this setion you will learn how to write program in Struts 2 to upload the file on the server. In
this example we are also providing the ode to save the uploaded file in any diretory on the
server mahine.
The Struts 2 File8pload omponent an be used to upload the multipart file in your Struts 2
appliation. In this setion you will learn about the ode to upload file on the server.
How File 3load Wor7s in Struts 2L
Struts 2 utili,es the servie of File 3load 'ntercetor to add the support for uploading files in
the Struts appliations. The Struts 2 File 8pload Intereptor is based on
%ulti2artRe3uest-rapper" whih is automatially applied to the re3uest if it ontains the file
element. Then it adds the following parameters to the re3uest :assuming the uploaded file name
is %yFile<.
O+yFileP / File ( the atual File
O+yFileP!ontentTye / String ( the ontent type of the file
OFile Na#ePFileNa#e / String ( the atual name of the file uploaded :not the 1T%&
name<
In the ation lass you an get the file" the uploaded file name and ontent type by +ust reating
getter and setters. For example" set%yfile:File file<" set%yFile)ontentType:String ontentType<"
get%yFile:<" et..
The file upload intereptor also does the validation and adds errors" these error messages are
stored in the struts(messsages.properties file. The values of the messages an be overridden by
providing the text for the following keys/
struts.#essages.error.uloading ( error when uploading of file fails
struts.#essages.error.&ile.too.large ( error ours when file si,e is large
struts.#essages.error.content.tye.not.allowed ( when the ontent type is not allowed
6ara#eters
=ou an use the following parameters to ontrol the file upload funtionality.
#axi#u#Si<e This parameter is optional. The default value of this is 2%#.
allowedTyes This parameter is also optional. It allows you to speify the allowed
ontent type.
Writing ,xa#le code to uload &ile
4ow we will write the ode to upload the file on server.
Action !lass
In the ation lass we will define four properties to failitate the file upload.
ri"ate File uploadS 99 The atual file
ri"ate String upload)ontentTypeS99 The ontent type of the file
ri"ate String uploadFile4ameS99 The uploaded file name and path
ri"ate String file)aptionS99 The aption of the file entered by user.
1ere is the full ode of ation lass StrutsFile8pload.+ava
package net.roseindia8
import java.util..ate8
import java.io.Gile8
import com.opens#mp&on#.x6or,2.4ctionSupport8
public class StrutsGileCpload extends 4ctionSupport *

private Gile upload8//T&e actual file
private Strin" upload(ontentT#pe8 //T&e content t#pe of t&e file
private Strin" uploadGile/ame8 //T&e uploaded file name
private Strin" file(aption8//T&e caption of t&e file entered b# user
public Strin" execute:< throws -xception *
return SC((-SS8
+
public Strin" "etGile(aption:< *
return file(aption8
+
public void setGile(aption:Strin" file(aption< *
this.file(aption = file(aption8
+
public Gile "etCpload:< *
return upload8
+
public void setCpload:Gile upload< *
this.upload = upload8
+
public Strin" "etCpload(ontentT#pe:< *
return upload(ontentT#pe8
+
public void setCpload(ontentT#pe:Strin" upload(ontentT#pe< *
this.upload(ontentT#pe = upload(ontentT#pe8
+
public Strin" "etCploadGile/ame:< *
return uploadGile/ame8
+
public void setCploadGile/ame:Strin" uploadGile/ame< *
this.uploadGile/ame = uploadGile/ame8
+

+
1ere we have not shown the ode to save the uploaded file. #ut it an be done easily using the
following ode in exeute:..< method of ation lass. 1ere is ode snippet.
99Following ode an be used to save the uploaded file
try R
String fullFile4ame M ;/9upload9myfile.txt;S
File theFile M new File:fullFile4ame<S
File8tils.opyFile:upload" theFile<S
T catch :5xeption e< R
add'tion5rror:e.get%essage:<<S
return IN!"S
T
Writing $S6 age
1ere is the ode of +sp file :uload.4s< that displays the file upload form to the user.
BYX taglib prefixM;s; uriM;9struts(tags; YC
BhtmlC
BheadC
BtitleCFile 8pload 5xampleB9titleC
Blink hrefM;Bs/url valueM;9ss9main.ss;9C; relM;stylesheet; typeM;text9ss;9C
B9headC
BbodyC
Bs/ationerror 9C
Bs/fielderror 9C
Bs/form ationM;do8pload; methodM;2OST; entypeM;#ultiart-&or#2data;C
BtrC
Btd olspanM;2;CBh.CFile 8pload 5xampleB9h.CB9tdC
B9trC
Es8&ile na#eJKuloadK la/elJKFileK-F
Bs/textfield nameM;aption; labelM;)aption;9C
Bs/submit 9C
B9s/formC
B9bodyC
B9htmlC
In the above ode the form enrypt type is ;#ultiart-&or#2data; and Bs/file ..9C tag renders the
html file tag.
File uload success age
1ere is the ode of file upload:upload(suess.+sp< suess page.
BYX page
languageM;+ava;
ontentTypeM;text9htmlS harsetM8TF(@;
page5nodingM;8TF(@;YC
BYX taglib prefixM;s; uriM;9struts(tags; YC
BhtmlC
BheadC
BtitleCShowaseB9titleC
Blink hrefM;Bs/url valueM;9ss9main.ss;9C; relM;stylesheet; typeM;text9ss;9C
B9headC
BbodyC
Btable lassM;wwFormTable;C
BtrC
Btd olspanM;2;CBh.CFile 8pload 5xampleB9h.CB9tdC
B9trC
BtrC
Btd lassM;td&abel;CBlabel forM;do8ploadZupload; lassM;label;C)ontent
Type/B9labelCB9tdC
BtdCEs8roerty "alueJKuload!ontentTyeK -FB9tdC
B9trC
BtrC
Btd lassM;td&abel;CBlabel forM;do8ploadZupload; lassM;label;CFile
4ame/B9labelCB9tdC
Btd CEs8roerty "alueJKuloadFileNa#eK -FB9tdC
B9trC
BtrC
Btd lassM;td&abel;CBlabel forM;do8ploadZupload; lassM;label;CFile/B9labelCB9tdC
BtdCEs8roerty "alueJKuloadK -FB9tdC
B9trC
BtrC
Btd lassM;td&abel;CBlabel forM;do8ploadZupload; lassM;label;CFile
)aption/B9labelCB9tdC
BtdCEs8roerty "alueJKcationK -FB9tdC
B9trC
B9tableC
B9bodyC
B9htmlC
Adding #aing in struts.x#l &ile
'dd the following mapping in the struts.xml file.
BF(( File 8pload ((C
Bation nameM;show8pload;C
BresultC9pages9upload.+spB9resultC
B9ationC
Bation nameM;do8pload; lassM;net.roseindia.StrutsFile8pload;C
Bresult nameM;input;C9pages9upload.+spB9resultC
BresultC9pages9upload(suess.+spB9resultC
B9ationC
BF(( 5nd File 8pload ((C
The ;show8pload; ation displays the upload form and ;do8pload; ation atually uploads the
file.
(unning the exa#le
To test the appliation ompile ode and then run the tomat. Type
http/99loalhost/@*@*9struts2tutorial9roseindia9show8pload.ation in your browser. =ou browser
should show the following form/

4ow browse the file" enter aption and then lik on the ;Submit; button. 'ppliation will
upload your file and then following suess sreen will be displayed.

There is one important point to be noted about File 8pload Intereptor. The File 8pload
Intereptor atually deletes the the upload" one the ation is exeuted. 1ere is the sreen shot of
tomat that shows the file delete message/
I4FO/ Removing file upload )/Iapahe(tomat(7.*..*Struts2Iapahe(tomat(
7.*..*IworkI)atalinaI
loalhostIstruts2tutorialIuploadZZ.Jf>J2fGZ..J2e.d?G>?ZZ@***Z********.tmp
In this setion you learnt the onept of file upload in struts 2.
Struts 2 )esources "xam!les
Static 6ara#eter
In this section, we will develop a simple application to access the static parameters. We will use a
JavaBean to set and get the static parameters. Each static parameter has a value.
Accessing Session 9/4ect
In this setion" we will develop a simple appliation to aess the framework resoures like the
session ob+et" session ontext and the last aessed session time.
Access (e:uest and (esonse
In this setion" you will learn to develop an appliation that aesses the re3uest and response
ob+et in struts 2 appliation.
Static 'arameter
In this section, we will develop a simple application to access the static parameters. We will use a
JavaBean to set and get the static parameters. Each static parameter has a value.
Descri!tion 9
Develop a JavaBean with three properties (Static Parameters) o string t!pe ( parameter",parameter#,
parameter$ ). Deine three JavaBean properties and add their corresponding values in the action
mapping (in the application%s struts.xml ). Set the name(s) and value(s) as shown &elow'
code sni!!et from struts.xml
Bation nameM;Stati2arameter;
lassM;net.roseindia.Stati2arameter;C
Bparam nameM;pramater.;CAalue .B9paramC
Bparam nameM;pramater2;CAalue 2B9paramC
Bparam nameM;pramaterJ;CAalue JB9paramC
BresultC9pages9statiparameter9showparamerts.+spB9resultC
B9ationC
)reate a simple !ava#ean Static6ara#eter.4a"a in the ;struts2tutorialGW,52
'NFGsrcG4a"aGnetGroseindia; diretory. 1ere the ;Stati2arameter; lass extends the
ActionSuort lass. It sets and gets the three stati parameters by using the set6ara#eter101"
set6ara#eter201" set6ara#eter>01 and get6ara#eter101" get6ara#eter201" get6ara#eter>01
methods.
4ow ompile the !ava#ean :Static6ara#eter.4a"a< through the 6ant6 ommand.
Static6ara#eter.4a"a
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util..ate8
public class Static!arameter extends 4ctionSupport *
private Strin" pramater98
private Strin" pramater28
private Strin" pramaterQ8

public Strin" execute:< throws -xception *
return SC((-SS8
+
public Strin" "et!ramater9:< *
return pramater98
+
public void set!ramater9:Strin" pramater9< *
this.pramater9 = pramater98
+
public Strin" "et!ramater2:< *
return pramater28
+
public void set!ramater2:Strin" pramater2< *
this.pramater2 = pramater28
+
public Strin" "et!ramaterQ:< *
return pramaterQ8
+
public void set!ramaterQ:Strin" pramaterQ< *
this.pramaterQ = pramaterQ8
+
+
)reate a +sp page :showparameters.+sp< to view the stati parameters.
showara#eters.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<title>Static !arameter -xample!</title>
</&ead>
<bod#>
<&9>Static !arameter</&9>
<table border="9" 6idt&="2TO" b"color="=ffffcc">
<tr>
<td 6idt&="2TO"><b>Ke#</b></td>
<td 6idt&="2TO"><b>;alue</b></td>
</tr>
<tr>
<td 6idt&="2TO">pramater9</td>
<td 6idt&="2TO"><s:propert# value="pramater9" /></td>
</tr>
<tr>
<td 6idt&="2TO">pramater2</td>
<td 6idt&="2TO"><s:propert# value="pramater2" /></td>
</tr>
<tr>
<td 6idt&="2TO">pramaterQ</td>
<td 6idt&="2TO"><s:propert# value="pramaterQ" /></td>
</tr>
</table>
</bod#>
</&tml>
Open web browser and give re3uest as
htt8--localhost8C;C;-struts2tutorial-roseindia-Static6ara#eter.action. It displays a table that
ontains three stati parameters in key(value format.
9utut o& this alication8
Accessin Session 6.8ect
In this setion" we will develop a simple appliation to aess the framework resoures like the
session ob+et" session ontext and the last aessed session time. To aess the session" you
need an ation lass implementing the SessionAware interfae and extending ActionSupport
class.
org.aache.struts2.intercetor.SessionAware 'nter&ace/ 'tions that need aess to the user6s
1TT2 session should implement this interfae. This interfae is only relevant if the 'tion is
used in a servlet environment. 4ote that using this interfae makes the 'tion tied to a servlet
environment" so it should be avoided if possible sine things like unit testing will beome more
diffiult.
*escrition8
add the following ation snippet to the following struts.x#l file.
struts.x#l
Bation nameM;HetSession;
lassM;net.roseindia.HetSession;C

BresultC9pages9statiparameter9HetSessio
n.+spB9resultC
B9ationC
4ow" reate a !ava#ean :GetSesstion.4a"a<. This is a simple 69$9 :2lain Old !ava Ob+et<.
1ere" we implement Session'ware interfae.
The setSession01 method sets the session in a %ap ob+et. It is alled at the running time.
GetSession.4a"a
package net.roseindia8
import or".apac&e.struts2.interceptor.Session46are8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util.'8
public class 3etSession extends 4ctionSupport implements Session46are*
private Bap session8
public Strin" execute:< throws -xception*
return SC((-SS8
+
public void setSession:Bap session<*
session = this."etSession:<8
+
public Bap "etSession:<*
return session8
+
+
4ow" we reate a +sp page for viewing the session ob+et" session ontext and session time. The
session ob+et provides information about the session" getSession!ontext01 method provides the
information about the session ontext and get)astAccessedTi#e01 provides date and time when
the last session is aessed.
GetSession.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<OPpa"e lan"ua"e="java" import="java.util.'" O>
<&tml>
<&ead>
<title>3et Session -xample!</title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc"> Session -xample! </span></&9>
<b>Session:</b><O=sessionO><br>
<b>Session (ontext: </b><O=session."etSession(ontext:< O><br>
<b>Session Time: </b><O=new .ate:session."etFast4ccessedTime:<<O>

</bod#>
</&tml>
Finally" open the web(browser and type the
htt8--localhost8C;C;-struts2tutorial-roseindia-GetSession.action in the address bar. It
displays the information about framework session" session ontext and last aessed session
time.
9utut o& this alication8
Access )e-uest and )es!onse
In this setion" you will learn to develop an appliation that aesses the re3uest and response
ob+et in struts 2 appliation. To aess the re3uest ob+et " use the ActionContext or implement
the ServletRequestAware interfae and to aess the response ob+et" use the ActionContext or
implement the ServletResponseAware interfae.
1ere" in this appliation" we are going to implement the ServletRequestAware and
ServletResponseAware interfaes in our ation lass.
'essing the re3uest and response ob+et" you need a struts.x#l file.
struts.x#l
Bation nameM;'essRe3uest;
lassM;net.roseindia.'essRe3uest;C

BresultC9pages9statiparameter9'essRe3uest.+
spB9resultC
B9ationC
4ow" reate a simple ation ;Access(e:uest.4a"a ;
1ere we use the setSer"let(e:uest01 :for setting the re3uest ob+et< and getSer"let(e:uest01
:for getting the re3uest ob+et< methods of ServletRequestAware interfae. Similarly" we use the
setSer"let(esonse01 :for setting the response< and getSer"let(esonse01 :for getting the
response< methods of ServletResponseAware interae.
Access(e:uest.4a"a
package net.roseindia8
import javax.servlet.&ttp.@ttpServlet$eMuest8
import javax.servlet.&ttp.@ttpServlet$esponse8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import or".apac&e.struts2.interceptor.Servlet$eMuest46are8
import or".apac&e.struts2.interceptor.Servlet$esponse46are8
public class 4ccess$eMuest extends 4ctionSupport implements
Servlet$eMuest46are0Servlet$esponse46are*

private @ttpServlet$eMuest reMuest8
private @ttpServlet$esponse response8

public Strin" execute:< throws -xception*
return SC((-SS8
+
public void setServlet$eMuest:@ttpServlet$eMuest reMuest<*
this.reMuest = reMuest8
+
public @ttpServlet$eMuest "etServlet$eMuest:<*
return reMuest8
+
public void setServlet$esponse:@ttpServlet$esponse response<*
this.response = response8
+
public @ttpServlet$esponse "etServlet$esponse:<*
return response8
+
+
Finally" reate a +sp page for aessing the re3uest and response ob+et.
Access(e:uest.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<OPpa"e lan"ua"e="java" import="java.util.'" O>
<&tml>
<&ead>
<title>4ccess $eMuest and $esponse -xample! </title>
</&ead>
<bod#>
<&9><span st#le="bac,"roundcolor: =GGGGcc">4ccess $eMuest
and $esponse -xample!</span></&9>
<b>$eMuest: </b><O=reMuestO><br>
<b>$esponse: </b><O=responseO><br>
<b>.ate: </b><O=new .ate:<O>
</bod#>
</&tml>
Open the web(browser and type the
;htt8--localhost8C;C;-struts2tutorial-roseindia-Access(e:uest.actionK in the address bar and
press the ;enter key; it displays the aess re3uest and response ob+et as well as aessed date
and time.
9utut o& this alication8
Struts 2 A8ax
In this setion" we explain you '+ax based development in Struts 2. Struts 2 provides built(in
support for '+ax using 0o+o toolkit. This is one of the greatest feature added to the Struts 2
framework. '+ax allows the developers to develop H8I like web appliations. In this setion we
will provide you many examples to use '+ax in Struts 2 appliations.
1. '+ax Feature in Struts 2
2. )ogin Alication 3sing A4ax
This setion provides you an easy and omplete implementation of login form using the
'+ax :0O!O<. &ets develop a login appliation using A4ax. This login appliation first
authentiates a user" it asks for a login name and password.

3. )ogin or !ancel Alication 3sing A4ax
This setion provides you" an easy and omplete implementation of login appliation
with features like submit and anel buttons using the '+ax :0O!O<. This appliation also
heks the user validation i.e. the logging user is valid or not.
Struts 2 Session Scope
&n this section% #ou wi!! !earn to create an *,*M a!ication in )truts2 .ramework
that dis!a#s some messages with session
This setion provides you an easy and omplete implementation of login form using the '+ax
:0O!O<.
&ets develop a login appliation using A4ax. This login appliation first authentiates a user" it
asks for a login name and password :#oth the login name and password is ;Ad#in;<. It displays
a welome page" when both fields are orretly filled by the user. Otherwise it shows an error
and 05#8H message :Invalid user name and password# lease try again# and $%&!'( widget
I$ collision on I$( a)a*+ogin,-<.
)reate an ation mapping in the struts.xml file. 1ere is the ode to be added in the struts.x#l/
Bation
nameM;show'+ax&oginForm;C

BresultC9pages9a+axlogin.+spB9resultC
B9ationC
Bation nameM;a+ax&ogin;
lassM;net.roseindia.&ogin;C
Bresult
nameM;input;C9pages9a+axlogin.+spB9r
esultC
Bresult
nameM;error;C9pages9a+axlogin.+spB9r
esultC

BresultC9pages9a+axloginsuess.+spB9
resultC
B9ationC
*e"elo a )ogin For# 3sing A4ax 8 The H8I of the appliation onsists of a login form
:a4axlogin.4s<. The ;a4axlogin.4s; displays the login page to the user. This +sp page uses the
Bs8di"C tag" this tag reates a ontent area that an load its ontent using '+ax tags" optionally
refreshing. 1ere we also use the Bs8su/#itC tag that is used to update element :s< or submit a
form with the help of '+ax.
-henever an error ours then the Bs8actionerrorC and Bs8&ielderrorC tags exeute and display
an error message the login form is submitted.
1ere is the ode of a4axlogin.4s file/
<OP ta"lib prefix="s" uri="/strutsta"s"O>
<&tml>
<&ead>
<s:&ead t&eme="ajax" debu"="true"/>
</script>
</&ead>
<bod#>
<s:div id="lo"in.iv" t&eme="ajax">
<div st#le="6idt&: Q55px8borderst#le: solid">
<s:form action="ajaxFo"in" validate="true">
<tr>
<td colspan="2">
Fo"in
</td>
</tr>
<tr>
<td colspan="2">
<s:actionerror />
<s:fielderror />
</td>
</tr>
<s:textfield name="username" label="Fo"in name"/>
<s:pass6ord name="pass6ord" label="!ass6ord"/>
<s:submit t&eme="ajax" tar"ets="lo"in.iv" notif#Topics="/ajaxFo"in"
/>
</s:form>
</div>
</s:div>
</bod#>
</&tml>
0evelop an ation lass that handles the login re3uest and heks for the user authentiation. If
the user name and password is ;'dmin; then it returns S8))5SS otherwise 5RROR ob+et.
1ere is the ode of ;)ogin.4a"aK ation lass/
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util..ate8
/''
' <p> ;alidate a user lo"in. </p>
'/
public class Fo"in extends 4ctionSupport *
public Strin" execute:< throws -xception *
S#stem.out.println:";alidatin" lo"in"<8
if:!"etCsername:<.eMuals:"4dmin"< HH !"et!ass6ord:<.eMuals:"4dmin"<<*
add4ction-rror:"%nvalid user name or pass6ord! !lease tr# a"ain!"
<8
return -$$D$8
+else*
return SC((-SS8
+
+
// Csername propert#
/''
' <p>Gield to store Cser username.</p>
' <p/>
'/
private Strin" username = null8
/''
' <p>!rovide Cser username.</p>
'
' Preturn $eturns t&e Cser username.
'/
public Strin" "etCsername:< *
return username8
+
/''
' <p>Store ne6 Cser username</p>
'
' Pparam value T&e username to set.
'/
public void setCsername:Strin" value< *
username = value8
+
// Csername propert#
/''
' <p>Gield to store Cser pass6ord.</p>
' <p/>
'/
private Strin" pass6ord = null8
/''
' <p>!rovide Cser pass6ord.</p>
'
' Preturn $eturns t&e Cser pass6ord.
'/
public Strin" "et!ass6ord:< *
return pass6ord8
+
/''
' <p>Store ne6 Cser pass6ord</p>
'
' Pparam value T&e pass6ord to set.
'/
public void set!ass6ord:Strin" value< *
pass6ord = value8
+
+
The ;a4axloginsuccess.4s; page displays the &ogin Suess message :Welcome to Admin< when
the user is suessfully authentiated.
1ere is the ode of ;a4axloginsuccess.4s; file/
<&tml>
<&ead>
<title>Fo"in Success</title>
</&ead>
<bod#>
<p ali"n="center"><font color="=5555N5" siSe="T">Fo"in Successful !
</font></p>
<&9> Aelcome to <O=reMuest."et!arameter:"username"<O> </&9>
</bod#>
</&tml>
9utut o& the A4ax login alication8
-hen this appliation exeutes you get a login page/
If you leave the ;&ogin name; field empty and +ust fills the ;2assword; field in the login page
then a message is displayed as shown below/
If you fills the ;&ogin name; field empty and +ust leaves the ;2assword; field empty in the login
page then a message is displayed as shown below/
If you enter the wrong login name and password in the login page then it displays a message as
shown below//
-hen you enter the orret login name and password to the login page" it shows a suess
message as shown /
$oin or (ancel A!!lication /sin A8ax
This setion provides you" an easy and omplete implementation of login appliation with
features like submit and anel buttons using the '+ax :0O!O<. This appliation also heks the
user validation i.e. the logging user is valid or not.
&ets develop a login appliation using A4ax with features like submit and anel buttons. This
login appliation first authentiates a user" it asks the login name and password :#oth the login
name and password is ;Ad#in;< from the user. It displays a welome page" when both fields are
orretly filled by the user. Otherwise it displays an error and 05#8H messages :Invalid user
name and password# lease try again# and $%&!'( widget I$ collision on I$( a)a*+ogin,-<.
If you want to anel the filled(up details from the form then lik the ;!ancel; button. 'fter
liking" it again asks for the login name and password.
)reate an ation mapping in the struts.xml file. 1ere is the ode to be added in the struts.x#l/
Bation nameM;show'+ax&ogin)anelForm;C
BresultC9pages9a+axlogin)anel.+spB9resultC
B9ationC
Bation nameM;a+axlogin)anel;
lassM;net.roseindia.&ogin;C
Bresult
nameM;input;C9pages9a+axlogin)anel.+spB9resultC
Bresult
nameM;error;C9pages9a+axlogin)anel.+spB9resultC
Bresult nameM;anel;
typeM;rediret;C9pages9a+axlogin)anel.+spB9resultC
BresultC9pages9a+axloginsuess.+spB9resultC
B9ationC
0evelop an ation lass that handles the login and anel re3uest and it also heks for the user
authentiation. If the user name and password is ;Ad#in; then it returns S8))5SS otherwise
5RROR strings. -henever you lik the ;)anel; button" it returns the 4O45 field :4O45
field/ The ation exeution was suessful but did not show a view<.
1ere is the ode of ;)ogin.4a"aK ation lass/
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import java.util..ate8
/''
' <p> ;alidate a user lo"in. </p>
'/
public class Fo"in extends 4ctionSupport *
public Strin" execute:< throws -xception *
if:!"etCsername:<.eMuals:"4dmin"< HH !"et!ass6ord:<.eMuals:"4dmin"<<*
add4ction-rror:"%nvalid user name or pass6ord! !lease tr# a"ain!"
<8
return -$$D$8
+
if:"etCsername:<.eMuals:"4dmin"< HH "et!ass6ord:<.eMuals:"4dmin"<<*
return SC((-SS8
+else*
return /D/-8
+
+
// Csername propert#
/''
' <p>Gield to store Cser username.</p>
' <p/>
'/
private Strin" username = null8
/''
' <p>!rovide Cser username.</p>
'
' Preturn $eturns t&e Cser username.
'/
public Strin" "etCsername:< *
return username8
+
/''
' <p>Store ne6 Cser username</p>
'
' Pparam value T&e username to set.
'/
public void setCsername:Strin" value< *
username = value8
+
// Csername propert#
/''
' <p>Gield to store Cser pass6ord.</p>
' <p/>
'/
private Strin" pass6ord = null8
/''
' <p>!rovide Cser pass6ord.</p>
'
' Preturn $eturns t&e Cser pass6ord.
'/
public Strin" "et!ass6ord:< *
return pass6ord8
+
/''
' <p>Store ne6 Cser pass6ord</p>
'
' Pparam value T&e pass6ord to set.
'/
public void set!ass6ord:Strin" value< *
pass6ord = value8
+
+
*e"elo a )ogin or !ancel For# 3sing A4ax 8 The H8I of the appliation onsists of a login
form :a4axlogin!ancel.4s<. This +sp page uses the Bs8di"C tag" this tag reates a ontent area
that an load its ontent using '+ax tags" optionally refreshing. 1ere we also use the Bs8su/#itC
tag that is used to update element :s< or submit a form with the help of '+ax. The ;)anel;
button alls submit tag to notify an ation to perform anel operation.
-henever an error ours then the Bs8actionerrorC and Bs8&ielderrorC tags exeute and the
page displays an error message.
1ere is the ode of a4axlogin!ancel.4s file/
<OP ta"lib prefix="s" uri="/strutsta"s"O>
<&tml>
<&ead>
<s:&ead t&eme="ajax" debu"="true"/>
</&ead>
<bod#>
<s:div id="lo"in.iv" t&eme="ajax">
<div st#le="6idt&: Q55px8borderst#le: solid">
<s:form action="ajaxlo"in(ancel" validate="true">
<tr>
<td colspan="2">
Fo"in
</td>
</tr>
<tr>
<td colspan="2">
<s:actionerror />
<s:fielderror />
</td>
<s:textfield name="username" label="Fo"in name"/>
<s:pass6ord name="pass6ord" label="!ass6ord"/>
<s:submit value="Submit" t&eme="ajax" tar"ets="lo"in.iv"
notif#Topics="/ajaxlo"in(ancel"/>
<s:submit action="s&o64jaxFo"in(ancelGorm" value="(ancel"
onclic,="form.onsubmit=null"/>

</s:form>
</div>
</s:div>
</bod#>
</&tml>
The ;a4axloginsuccess.4s; page displays the &ogin Suess message :Welcome to Admin< when
the user is suessfully authentiated.
1ere is the ode of ;a4axloginsuccess.4s; file/
<&tml>
<&ead>
<title>Fo"in Success</title>
</&ead>
<bod#>
<p ali"n="center"><font color="=5555N5" siSe="T">Fo"in Successful !
</font></p>
<&9> Aelcome to <O=reMuest."et!arameter:"username"<O> </&9>
</bod#>
</&tml>
9utut o& the a4ax login or cancel alication8
-hen this appliation exeutes you get a login page as shown/
If you leave the ;&ogin name; and ;password; field empty in the login page then a message is
displayed as shown below/
If you leave the ;&ogin name; field empty and +ust fills the ;2assword; field in the login page
then a message is displayed as shown below/
If you fill the ;&ogin name; field empty and +ust leaves the ;2assword; field empty in the login
page then a message is displayed as shown below/
If you enter the wrong login name and password in the login page then it displays a message as
shown below/
'fter liking the ;)anel; button" you get the following/
-hen you enter the orret login name and password to the login page/
0isplays a suess message as shown/
Struts 2 Session Sco!e
In this setion" you will learn to reate an '!'$ appliation in Struts2 Framework that displays
some messages with session.
The urrent appliation displays a +sp page having the two text fields.
If the user enters nothing in the text fields and submit the form it displays an error message
;nothing entered;.
If the user enters some text in the -5&)O%5. field" then the orresponding attribute is set to
;welome.;.
If the user leaves the -5&)O%5. field empty and enters some text in the -5&)O%52 field"
then the orresponding attribute is set to ;welome2;.
This appliation is reated with '!'$ in Struts2 Framework. #efore we start the things" we need
to do the following/
.. 0ownload Struts2 from 'pahe.org
2. 0eploy the +ars under Tomat server -5#(I4F9lib
J. Rename the +ars ontaining ;plug(in; :this is very important as our appliation doesn6t
need any plugin6s and Tomat lass loader sometimes fails to find the lass files
assoiated with the plugin6s<
?. %ake sure the Tomat server is the latest :Tomat >.>.* and above<
5. 0ownload xwork(2.*.?.+ar from oensy#hony.co# as it is not available with the
Struts2 distribution.
The struts.x#l file ontains the information about the files" onstants" pakages and ations to
be inluded. The Binlude fileC tag provides standard information provided by Struts2. The
BonstantC tags are also there" you may set the struts.dev%ode onstant to true" but it is not
neessary. The pakage tag speifies a name" namespae and extends attributes.
2ay attention to namespae as it affets the 8R& you have to type in the browser. If you give a
namespae say ;9roseindia; then your 8R& will be
;http://localhost:88/struts!tutorial/roseindia/showAjax"estAction#or$.action;.
To make it simpler as we don6t have many pakages we have set the namespae to blank so that
we need only use the 8R&
;http://localhost:88/struts!tutorial/roseindia/showAjax"estAction#or$.action;
The ation with name showA4axTestActionFor# shows in the view A4axTest.4s. 4ote that the
pages don6t have to be in the lasspath.
struts.x#l
BNxml versionM;..*; enodingM;8TF(@; NC
BF0O)T=25 struts 28#&I)
;(99'pahe Software Foundation990T0 Struts
)onfiguration 2.*9954;
;http/99struts.apahe.org9dtds9struts(2.*.dtd;C
BstrutsC
BF(( Rose India Struts 2 Tutorials ((C
Bonstant
nameM;struts.enable.0ynami%ethodInvoation;
valueM;false; 9C
Bonstant nameM;struts.dev%ode; valueM;true; 9C
Binlude fileM;struts(default.xml;9C
Bpakage nameM;roseindia; namespaeM;9roseindia;
extendsM;struts(default;C
Bation nameM;show'+axTest'tionForm;C
BresultC9pages9'+axTest.+spB9resultC
B9ationC
Bation nameM;'+axTest'tion;
lassM;net.roseindia.SampleForm;C
Bresult nameM;error;C9pages9'+axTest.+spB9resultC
Bresult nameM;suess;C9pages9'+axTest.+spB9resultC
BresultC9pages9'+axTest.+spB9resultC
B9ationC
BF(( 'dd ations here ((C
B9pakageC
BF(( 'dd pakages here ((C
B9strutsC
The ation A4axTestAction is the form ation attribute. It is assoiated with the support lass
net.roseindia.Sa#leFor# whih is in the lass path. The result tags mean as follows/
If the lass returns ;error; then show the error message set in the !ava lass in the view.
If the lass returns ;suess; then update the view.
If the lass returns nothing then update the view.
The !S2 file ontains a form" two text fields and a submit button. The Es8actionerrorF"
Es8&ielderrorF and Es8action#essageF tags will display the errors assoiated while proessing
this form. The Es8di" idJKlogin*i"K the#eJKa4axKF tag prints a message at the top of the view
indiating whih textfield has been set. It displays a message from the session6s set attribute.
1ere is the ode for the !S2 form/ A4axTest.4s
<OP ta"lib prefix="s" uri="/strutsta"s" O>
<&tml>
<&ead>
<s:&ead t&eme="ajax" debu"="true"/>
</&ead>
<bod#>
<s:div id="lo"in.iv" t&eme="ajax">
<&Q> Eour Session: <s:propert# value="=session.ret" /></&Q>
<div st#le="6idt&: Q55px8borderst#le: solid">
<s:form action="4jaxTest4ction" validate="false">
<tr>
<td colspan="2">
$un Test
</td>
</tr>
<tr>
<td colspan="2">
<s:actionerror />
<s:fielderror />
<s:actionmessa"e/>
</td>
<s:textfield name="6elcome9" label="A-F(DB-9"/>
<s:textfield name="6elcome2" label="A-F(DB-2"/>
<s:submit value="Submit" t&eme="ajax" tar"ets="lo"in.iv"
notif#Topics="/4jaxTest4ction"/>
</tr>
</s:form>
</div>
</s:div>
</bod#>
</&tml>
The following +ava lass extends the ActionSuort lass that implements the SessionAware
interfae. This way we an get the best of the both worlds beause SessionAware will add
attributes to the session that an be aessed from the !S2. In our ase it will be the ;ret;
attribute. The setter and getter methods are straightforward.
1ere is the ode of Sa#leFor#.4a"a8
package net.roseindia8
import com.opens#mp&on#.x6or,2.4ctionSupport8
import or".apac&e.struts2.interceptor.Session46are8
import java.util.Bap8
public class SampleGorm extends 4ctionSupport implements Session46are*
//Gields t&at &old data
private Strin" Aelcome9=""8
private Strin" Aelcome2=""8
private Bap session8
public Strin" execute:< throws -xception *
if :"etAelcome9:<.trim:<.eMuals:""< 77 "etAelcome2:<.trim:<.eMuals:""<<*
add4ction-rror:"not&in" entered"<8
return -$$D$8
+
if :!"etAelcome9:<.trim:<.eMuals:""< 77 !"etAelcome2:<.trim:<.eMuals:""<<*
add4ctionBessa"e:"1ot& &ave data!"<8
return -$$D$8
+
if :!"etAelcome9:<.trim:<.eMuals:""<<*
"etSession:<.put:"ret"0 "6elcome9"<8
add4ctionBessa"e:"Aelcome 2 is empt#!"<8
return -$$D$8
+
if :!"etAelcome2:<.trim:<.eMuals:""<<*
"etSession:<.put:"ret"0 "6elcome2"<8
add4ctionBessa"e:"Aelcome 9 is empt#!"<8
return -$$D$8
+
return SC((-SS8
+
public void setAelcome9:Strin" s< *
this.Aelcome9= s8
+

public Strin" "etAelcome9:< *
return Aelcome98
+
public void setAelcome2:Strin" s< *
this.Aelcome2= s8
+

public Strin" "etAelcome2:< *
return Aelcome28
+
public void setSession:Bap session< *
this.session = session8
+

public Bap "etSession:< *
return session8
+
+
)ompile the lass" start the Tomat" and test the appliation by typing the following 8R& on the
address bar of web browser/
;http://localhost:88/struts!tutorial/roseindia/showAjax"estAction#or$.action;
9utut8
-hen this appliation exeutes you get a page as shown/
If you leave the ;-5&)O%5.; and ;-5&)O%52; field empty then a message is displayed
with session as shown below/
'fter liking the ;Submit; button then you get/
If you leave the ;-5&)O%5.; field empty and +ust fill the ;-5&)O%52; field then a message
is displayed with session as shown below/
If you fill the ;-5&)O%5.; field and +ust leave the ;-5&)O%52; field empty then a message
is displayed with session as shown below/
If you fill both field then you get/

Вам также может понравиться