struts for beginners
TRANSCRIPT
-
8/14/2019 Struts for Beginners
1/40
Struts for Beginners: Introduction
Struts is a mature open source MVC(Model-View-Controller) frame work for web applications.With Struts we can easily integrate arious technologies like !"## $ %ibernate$ i&'S$ !S*
and !S+$ Velocity emplates$ ,S* etc. 'part from being a framework Struts also proides
utilities and custom tags to cut down deelopment time.
Struts is a ery popular framework and has now become a de-facto standard for !aaapplications. he reasons for this popularity are gien below
'dantages of Struts
'dantage MVC
Struts imposes the MVC framework so that no body goes off loop and does his own non standard
implementation. &efore Struts MVC implementations were deelopment teams perception ofMVC which lead to lots of confusion$ errors and increased the learning cure for that
implementation. With Struts this human element is gone and a standard process of MVC is
imposed on the deelopers
'dantage ConfigurationsStruts works completely on configurations in ,M* and property filesrather than hard coding the components in the !aa code. 'll the elements like Controller
actions$ redirects$ alidations$ eceptions can be incorporated by configurations and can be easily
tracked at a later stage.
Advantage Utilities
Struts proides lots of utilities deried from 'pache Commons to make our life easier like ready
made +orm &eans for re/uest parameters$ Validation controls and Custom tags
0isadantages of Struts
Disadvantage Performance
+rameworks mean bigger call stacks due to arious function calls which results in lesser
performance. %oweer this is a performance sacrifice is offset by ma1or adantage ofstandardi2ed deelopment process adantage.
Disadvantage Beginners
hough this is not an issue with eperienced deelopers$ the new deelopers hae a biggerlearning cure. he documentation at 'pache is mostly targeted at the eperienced audience.
-
8/14/2019 Struts for Beginners
2/40
Disadvantage Imposing
f you want to use Struts then you will hae to 1ust follow the rules set by this framework. 3oing
in a different way is pretty tedious.
Disadvantage Small Programs
Struts is not always useful for a smaller programs because there is no point in wasting time on
arious Struts configurations when you can write your program in a 1iffy. he program
re/uirements should be carefully ealuated before using Struts
Struts for Beginners: Model View Controller
(MVC Design Pattern
&ack4 utorial %ome45et
#ery program has a 6ser nterface$ eent handling$ business logic and data access. f thesecomponents are mied together what we get is a spaghetti code. his kind of code though
functional is difficult to maintain and small changes to a part of code will hae a spiral effect to
other sections of the program.
o get around this problem Model View Controller approach was deeloped by small talkdeelopers and was widely embraced by the deeloper community. Various !aa technologies
like Swing$ !"##$ Struts draw a lot of features from MVC design pattern.
n MVC the programs are diided into three parts 7 Model$ View and Controller. his way thereis segregation of arious layers and the changes can be done to indiidual layers without effect or
minimal effect to the other layers. *ets us look into these layers in more detail
http://www.j2mesalsa.com/struts/intro.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/installations.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/installations.phphttp://www.j2mesalsa.com/struts/intro.php -
8/14/2019 Struts for Beginners
3/40
View
View manages the display to the end user. View should not contain any business logic.his layer
does following tasks
Show hypertet$ images$ forms to the user
8etriee processed data from the model and display to the user along with hypertet$
images and forms.
Client side alidations
Serer side alidations
f you are web programmer these are your !S9 files.
Model
Model is back bone of any program. his modal consists of data in a particular state and actions
that can modify this state. hese actions are usually called business logic. n simpler words thislayer does all the data related work gien below
&eans with get and set methods
&usiness logic
0ata 'ccess from any data source database$ flat file$ web serice$ #ntity &ean$ *0'9
serer etc.
-
8/14/2019 Struts for Beginners
4/40
f you are web programmer these are your &:s (&uisness :b1ects)$ 0':s (0ata 'ccess
:b1ects) $ V:s(Value :b1ects) etc.
Controller
Controller is the layer between View and Model. his layer does following tasks
When eer a View sends the re/uest$ the Controller finds appropriate Model component
and forwards the re/uest to this component.
8eceies the response from the model and routes the data to appropriate View
component.
f you web programmer these are your Serlet files.
's you go through net few sections you will understand how this design pattern is implemented
in Struts.
Struts for Beginners: Installation
&ack4 utorial %ome45et
!ava "nvironment
0ownload !0;., and aboe fromhttp?@@1akarta.apache.org@tomcat@and install on the
deelopment machine. 8efer to installation manual for procedure. omcat is an :pen source
!S9@Serlet web serer. We will use this web serer for our tutorial.
Struts Installation
0ownload Struts
-
8/14/2019 Struts for Beginners
5/40
C$ec% &our installation
ry 68* - http?@@localhost?EFEF@Bpro1ect-folder@ on your browser. f you can iew welcome
screen then your struts set up is done.
Setting up &our 'uild environment wit$ "clipse
Create a new pro1ect called G0ocManagerH in your #clipse 0# and set build path to include allthe 1ar files in the lib folder of the Struts download. 'lso set the build path to include !"##.1ar or
serlet.1ar.
http://localhost:8080/http://localhost:8080/ -
8/14/2019 Struts for Beginners
6/40
Struts for Beginners: Dot do(do and Action
Servlet&ack4 utorial %ome45et
*ets inestigate the deployment descriptor W#&[email protected] for struts. Iou will find
following ml configurations.
BJ-- Standard 'ction Serlet Mapping --
Bserlet-mappingBserlet-nameactionB@serlet-name
Burl-patternK.doB@url-pattern
B@serlet-mapping
he aboe Gserlet-mappingH configuration says that what eer re/uest that comes with a mimetype .do should go to serlet called GactionH. 'nd the serlet GactionH is defined in the below
configuration. he action is the alias name of the serlet org.apache.struts.action.'ctionSerlet.
his 'ctionSerlet is the Struts controller and etends %9Serlet class.
BJ-- Standard 'ction Serlet Configuration --Bserlet
Bserlet-nameactionB@serlet-name
Bserlet-classorg.apache.struts.action.'ctionSerletB@serlet-class
Binit-paramBparam-nameconfigB@param-name
Bparam-alue@W#&[email protected]@param-alue
B@init-paramBload-on-startup"B@load-on-startup
B@serlet
'ny other etension other than .do can be used by configuring accordingly in web.ml.
ActionServlet
5ow that your re/uest has reached the 'ctionSeret class. What 5etL
'ctionSerlet performs following tasks
's 'ctionSerlet etends %9Serlet class so it has init() method where W#&-
[email protected] is loaded. n struts-config we define all the tasks re/uired for
respectie re/uests.
9rocesses re/uests and delegates re/uest handling to 8e/uest9rocessor ob1ect
http://www.j2mesalsa.com/struts/installations.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/helloworld.phphttp://www.j2mesalsa.com/struts/installations.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/helloworld.php -
8/14/2019 Struts for Beginners
7/40
8e/uest9rocessor delegates these 1obs to arious 'ction classes and receies responses
from these 'ction classes and call the respectie iews. 8e/uest9rocessor is not isible to
us. his is an internal class used by 'ctionSerlet.
Struts Configuration )ile *struts+config,ml-
Struts Configuration +ile defines all the mappings re/uired by a Struts application like controller
actions$ redirects$ resource information$ alidations$ +orm &eans$ data sources etc. his is the file
where the process flow of the Struts application is defined.
'ction class is a where the arious tasks to be performed for an incoming re/uest are defined.he controller ('ctionSerlet) will call an 'ction for each re/uest based on the below action-
mappings. Set the following mappings in the struts-config.ml.
Baction-mappingsBaction pathN@helloWorldN typeNcom.salsa.%elloWorldN
Bforward nameNhelloN [email protected]@B@action
B@action-mappings
Struts for Beginners: .ello /orld Program
&ack4 utorial %ome45et
*ets follow the conentions and kick start the coding with a %ello World program.
%elloWorld.1aa
package com.salsa;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.ActionMapping;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionForm;
pulic class Hello!orld extends Action "pulic ActionForward execute#ActionMapping mapping$ActionForm %orm$HttpServletRequest request$HttpServletResponse response& throws 'xception "
return mapping.%indForward#(hello(&;)
)
http://www.j2mesalsa.com/struts/actionservlet.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/actionforms.phphttp://www.j2mesalsa.com/struts/actionservlet.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/actionforms.php -
8/14/2019 Struts for Beginners
8/40
%elloWorld etends 'ction class which is the is a class which manipulated the Model. %ere
Models like re/uest parameters$ !aa &eans can be manipulated.
'ction class has a method called eecute() which needs to be oerridden in your program tomake state changes to the Model.
ActionForward execute#ActionMapping mapping$ActionForm %orm$HttpServletRequest request$HttpServletResponse response&
'ctionMapping? his ob1ect holds all the mappings regarding this particular action like paths$
forwards etc.'ction+orm? hese are the re/uest parameters associated with the re/uest. We will take a closer
look into this class later.
%ttpSerlet8e/uest? 8e/uest :b1ect
%ttpSerlet8e/uest? 8esponse :b1ect.
*ets hae a closer look at the action-mapping$ We hae 1ust seen the %elloWorld class where the
re/uest is forwarded to GhelloH. G%elloH here is alias to GhelloWorld.1spH
Baction-mappings
Baction pathN@helloWorldN typeNcom.salsa.%elloWorldNBforward nameNhelloN [email protected]@
B@action
B@action-mappings
Write a simple !S9 file(helloWorld.1sp) which displays G%ello WorldH. 9lace this file in thesalsa-tutorial folder in webapps.
Bhtml
Bhead
BtitleStruts Classic %ello World
B@title
B@headBbody
Bh
-
8/14/2019 Struts for Beginners
9/40
he picture below shows the flow of your program
We will update this picture as the tutorial progresses.
-
8/14/2019 Struts for Beginners
10/40
Struts for Beginners: )orms 0 Action )orms
&ack4 utorial %ome45et
*ets now eplore the forms. +orms are the %M* elements where the user enters some alues
and submits the form and gets the results page. We will now create a login page to see how itworks in struts.
Struts comes with to tag libraries. Iou need to import these libraries into a !S9 page.
BOP taglib uriNhttp?@@struts.apache.org@tags-beanN prefiNbeanN O
BOP taglib uriNhttp?@@struts.apache.org@tags-htmlN prefiNhtmlN O
his works in Struts
-
8/14/2019 Struts for Beginners
11/40
action property in Bhtml?form element the and is mapped in the struts-config.ml to
repectie action. he other elements like Bhtml?tet and Bhtml?password are mapped to'ction+orm &ean. hese mappings hae to be inserted into struts-config.ml. We will study
these mappings as we create the re/uisite classes
struts+config,ml
Baction pathN@login'ctionNtypeNcom.salsa.6ser*ogin'ctionN
nameNuser*ogin+ormN
inputN@login+orm.1spN
cancellableNtrueNBforward nameNloginsuccessN [email protected] @
Bforward nameNlogincancelN [email protected] @
B@action
Complete code of *ogin+orm.1sp
BOP taglib uriNhttp?@@struts.apache.org@tags-beanN prefiNbeanN O
BOP taglib uriNhttp?@@struts.apache.org@tags-htmlN prefiNhtmlN OBhtml
Bhead
Btitle*ogin +ormB@title
B@headBbody
Bh
-
8/14/2019 Struts for Beginners
12/40
Btr
Btd
Bhtml?submit @B@td
Btd
Bhtml?cancel @B@td
B@tr
B@html?formB@table
B@body
B@html
Action)orm
'ction +orm is the bean where all the parameters sent from the from are stored. o create an this
bean your class should etend from 'ction+orm
pulic class *oginForm extends ActionForm "
+reate variales$ setter and getter methods %or %orm sumission parameters
private String user,ame;private String password;
pulic String getuser,ame#& "S-stem.out.println#(*oginFormgetuser,ame#&(&;return user,ame;
)pulic void setuser,ame#String user& "
user,ame / user;S-stem.out.println#(*oginFormsetuser,ame#&(&;
)
pulic String get0assword#& "return password;
6se reset() method to reset bean alues.
pulic void reset#ActionMapping mapping$HttpServletRequest request& "S-stem.out.println#(*oginFormreset#&(&;user,ame/null;password/null;
)
5ow that the parameters are receied$ 5et alidations hae to be done for the re/uest
parameters. Struts proides a method alidate(). 'll the re/uisite alidations are done in thismethod and the errors are logged in an 'ction#rrors ob1ect. f there are no errors then the
controller forwards the re/uest to 'ction class defined in the struts-config. 'nd if error is
detected the login+orm.1sp is inoked with error messages displayed in place of Bhtml?errors@tag in the login form.
-
8/14/2019 Struts for Beginners
13/40
-
8/14/2019 Struts for Beginners
14/40
login.user5ame.errornalid user name
login.password.errornalid password
Complete listing of *ogin+orm.1aa
package com.salsa;
import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionMapping;import org.apache.struts.action.Action'rrors;import org.apache.struts.action.ActionMessage;import javax.servlet.http.HttpServletRequest;pulic class *oginForm extends ActionForm "
private String user,ame;private String password;
pulic String getuser,ame#& "
S-stem.out.println#(*oginFormgetuser,ame#&(&;return user,ame;
)pulic void setuser,ame#String user& "
user,ame / user;S-stem.out.println#(*oginFormsetuser,ame#&(&;
)
pulic String get0assword#& "return password;
)pulic void set0assword#String pass!ord& "
password / pass!ord;
)
pulic void reset#ActionMapping mapping$HttpServletRequest request& "S-stem.out.println#(*oginFormreset#&(&;user,ame/null;password/null;
)
pulic Action'rrors validate#ActionMapping mapping$HttpServletRequest request& "S-stem.out.println#(*oginFormvalidate#&(&;Action'rrors errors / new Action'rrors#&;i% #user,ame//null 11 user,ame.trim#&.equals#((&&"
errors.add#(user,ame($ newActionMessage#(login.user,ame.error(&&;
)
i% #password//null 11 password.trim#&.equals#((&&"errors.add#(password($ new
ActionMessage#(login.password.error(&&;)
-
8/14/2019 Struts for Beginners
15/40
return errors;)
)
Create an alias for this form bean in within Bform-beans tag of struts-config.ml
Bform-beans
Bform-bean nameNuser*ogin+ormNtypeNcom.salsa.*ogin+ormN @
8ememberL Guser*ogin+ormH is used in action mapping for parameter name.
Baction pathN@login'ctionN
typeNcom.salsa.6ser*ogin'ctionNnameNuser*ogin+ormN
inputN@login+orm.1spNcancellableNtrueN
+inally add logic for cancel button.
6ser*ogin'ction.1aa
package com.salsa;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.Action;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionForm;
pulic ActionForward execute#ActionMapping mapping$ActionForm %orm$HttpServletRequest request$HttpServletResponse response& throws 'xception "
S-stem.out.println#(2ser*oginActionexecute#&(&;i% #is+ancelled#request&&"
return mapping.%indForward#(logincancel(&;)else "
return mapping.%indForward#(loginsuccess(&;)
))
Submit and Cancel &utton configurations in the Struts Config file are highlighted belowBaction pathN@login'ctionN
typeNcom.salsa.6ser*ogin'ctionN
-
8/14/2019 Struts for Beginners
16/40
nameNuser*ogin+ormN
inputN@login+orm.1spN
cancellableNtrueNBforward nameNloginsuccessN [email protected] @
Bforward nameNlogincancelN [email protected] @
B@action
f you do not set cancellableNtrueN in action mapping$ nalidCancel#ception will be thrown'nd finally create the !S9 files to display successful logins and cancelled logins. his login is
incomplete without alidating the user with the database alues for login and password. We will
complete the database part in our database section.
loginStatus.1sp
BOP taglib uriNhttp?@@struts.apache.org@tags-beanN prefiNbeanN O
Bhtml
BheadBtitle
*ogin Status
B@title
B@headBbody
Bbean?message keyNlogin.statusN @
B@bodyB@html
*ogin status uses a Struts tag library struts-bean(tags-bean) to display messages from
Message8esources.properties. 'dd he key H login.statusH in the property file.
login.status*ogin Successful.loginCancel.1sp
Bhtml
Bhead
Btitle*ogin Status
B@title
B@head
Bbody*ogin Cancelled
B@body
B@html
o check your login program fire 68* http?@@localhost?EFEF@salsa-tutorial@login+orm.1spin your
browser.
http://struts.apache.org/tags-beanhttp://localhost:8080/salsa-tutorial/loginForm.jsphttp://struts.apache.org/tags-beanhttp://localhost:8080/salsa-tutorial/loginForm.jsp -
8/14/2019 Struts for Beginners
17/40
*ook at the S:9s(Sys :uts) in omcat console to understand the work flow. 'lternatiely you
can use *og=! for better understanding of the work flow.
user*ogin.1sp
*ogin+orm??reset() - 'ction+orm
*ogin+orm??setuser5ame() - 'ction+orm
*ogin+orm??set9assword() - 'ction+orm
*ogin+orm??alidate() - 'ction+orm
6ser*ogin'ction??eecute() - 'ction
loginStatus.1sp
5ow let us see the workflow diagram to clearly understand the flow
-
8/14/2019 Struts for Beginners
18/40
-
8/14/2019 Struts for Beginners
19/40
Struts for Beginners: Data Base Connections
&ack4 utorial %ome45et
5ow lets conert our dumb login program to an intelligent login program which connects to the
data base and alidates the user name and password before spitting out the response. We will useopen source database My SR*. Iou can use any other database you are comfortable with.
his tutorial section uses the general 0ata Source and pooling proided by omcat. 'lternatiely
you can also use Struts datasources which is not ery popular and is not coered in this tutorial.
Create a database firing the following /uery in the My SR* client
create database 0:CM'5'3#8Q
Create a table to store login data
C8#'# '&*# CMS6S#8(0 5 '6:5C8#M#5$
6S#85'M# V'8C%'8(EF)$
9'SSW:80 V'8C%'8(EF)$C:5S8'5 CMS6S#89; 98M'8I ;#I (0)
)Q
nsert alues in the table
insert into cmsuser (username$ password) alues (TadminT$ Tadmin
-
8/14/2019 Struts for Beginners
20/40
import javax.naming.+ontext;import javax.naming.4nitial+ontext;
0o following changes in the eecute method
oolean loginFlag / %alse;
Change eecute method to create following ariables
+onnection conn/null; 55 For dataase connectionResultSet rs / null; 55 For dataase connectionoolean loginFlag / %alse; 55 %lag %or login check
5ow go ahead and write database access code.
i% #is+ancelled#request&&"return mapping.%indForward#(logincancel(&;
)
else "tr-"
+ontext context / new 4nitial+ontext#&;+ontext env+ontext /
#+ontext&context.lookup#(java5comp5env(&;3ataSource dataSource
/#3ataSource&env+ontext.lookup#(jdc5docmanager(&;conn / dataSource.get+onnection#&;*oginForm loginForm / #*oginForm& %orm;0reparedStatement statement /
conn.prepareStatement#(S'*'+6 2S'R7,AM'$ 0ASS!8R3 FR8M +MS72S'R !H'R'
2S'R7,AM'/9 A,3 0ASS!8R3/9(&;statement.setString#:$loginForm.getuser,ame#&&;statement.setString#$loginForm.get0assword#&&;rs / statement.execute
-
8/14/2019 Struts for Beginners
21/40
package com.salsa;
import java.sql.+onnection;import java.sql.0reparedStatement;import java.sql.ResultSet;import javax.sql.3ataSource;import javax.naming.+ontext;import javax.naming.4nitial+ontext;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionMapping;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionForm;
pulic class 2ser*oginAction extends Action "pulic ActionForward execute#ActionMapping mapping$
ActionForm %orm$HttpServletRequest request$HttpServletResponse response& throws 'xception "
S-stem.out.println#(2ser*oginActionexecute#&(&;+onnection conn/null;ResultSet rs / null;oolean loginFlag / %alse;i% #is+ancelled#request&&"
return mapping.%indForward#(logincancel(&;)else "
tr-"+ontext context / new 4nitial+ontext#&;+ontext env+ontext /
#+ontext&context.lookup#(java5comp5env(&;3ataSource dataSource
/#3ataSource&env+ontext.lookup#(jdc5docmanager(&;conn / dataSource.get+onnection#&;*oginForm loginForm / #*oginForm& %orm;0reparedStatement statement /
conn.prepareStatement#(S'*'+6 2S'R7,AM'$ 0ASS!8R3 FR8M +MS72S'R !H'R'
2S'R7,AM'/9 A,3 0ASS!8R3/9(&;statement.setString#:$loginForm.getuser,ame#&&;statement.setString#$loginForm.get0assword#&&;rs / statement.execute
-
8/14/2019 Struts for Beginners
22/40
)i% #loginFlag&
return mapping.%indForward#(loginsuccess(&;else
return mapping.%indForward#(login%ailure(&;
))
)
Configure contet and datasource as shown below in serer.ml.
BContet pathN@salsa-tutorialN doc&aseNsalsa-tutorialN debugN
-
8/14/2019 Struts for Beginners
23/40
Struts for Beginners: ",ception .andling
&ack4 utorial %ome45et
*ike all other configurable features in Struts$ #ceptions can be also handled using
configurations. his configuration methodology is usually called declaratie eception handling.5ormal eception handling we do is programmatic eception handling.
Struts configuration file can be configured to catch eception. 5ot a single line is needed in your
code needs to be changed to handle these eceptions.
Shut down your database and eecute the login page. When you submit the login details$ the
browser oerflows with eception messages. f you properly analy2e these error messages$ you
will find that the root cause is G1aa.s/l.SR*#ceptionH.
5ow let us handle this eception the S86S W'I.
Create a !S9 page GdbSerer0own.1spH with error message. his is page to be displayed when
the eception occurs.
BOP taglib uriNhttp?@@struts.apache.org@tags-htmlN prefiNhtmlN OBhtml
Bhead
Btitle
Serice 6naailableB@title
B@headBbody
Bhtml?errors@
B@body
B@html
'dd the eception handling declarations in the Struts configuration file
Baction pathN@login'ctionN
typeNcom.salsa.6ser*ogin'ctionNnameNuser*ogin+ormNinputN@login+orm.1spN
cancellableNtrueN
Bforward nameNloginsuccessN [email protected] @Bforward nameNlogincancelN [email protected] @
Bforward nameNloginfailureN pathN@login+ailure.1spN @
Beception typeN1aa.s/l.SR*#ceptionN
http://www.j2mesalsa.com/struts/database.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/jsps.phphttp://struts.apache.org/tags-htmlhttp://www.j2mesalsa.com/struts/database.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/jsps.phphttp://struts.apache.org/tags-html -
8/14/2019 Struts for Beginners
24/40
keyNdb.eceptionN
B@action
+inally create the error message referred to as GkeyH in the aboe declaration. his error message
should be configured in Message8esources.properties
db.eceptionnternal #rror$ 9lease ry after some time....................
8un the login program in the browser. 0o a proper login once and then shut down yourdatabase. #ecute the login page again. When you submit the login details you will be shown the
error message you hae configured in the Message8esources.properties.
f we properly analy2e the code aboe we haent done any changes in the 'ction class$ all we
hae done is do configurations in the configuration files.
Struts for Beginners: Accessing Action )ormsfrom !SP Pages
&ack4 utorial %ome45et
'ction +orms can be accessed from the !S9s using Gtags-beanH tag library. he below section
describes the procedure to display alues of the bean G*ogin+orm.1aaH in the !S9 page.
'dd attribute tag to the action mapping. he parameter attribute sets the *ogin+orm(aliased as
user*ogin+orm in the bean defination) ob1ect to be in session scope and can be accessed from!S9 pages.
Baction pathN@login'ctionN
typeNcom.salsa.6ser*ogin'ctionNnameNuser*ogin+ormN
attributeNlogin&eanN
inputN@login+orm.1spNcancellableNtrueN
he alue of the attribute parameter i.e. login&ean will now become the alias for *ogin+orm
bean and can be accessed from any !S9 page using Bbean? write tag.
Bbean?write nameNlogin&eanN propertyNuser5ameN @
Make sure the re/uired tag lib is imported.
BOP taglib uriNhttp?@@struts.apache.org@tags-beanN prefiNbeanN O
Complete code of loginStatus.1sp
http://www.j2mesalsa.com/struts/exceptions.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/logictags.phphttp://struts.apache.org/tags-beanhttp://www.j2mesalsa.com/struts/exceptions.phphttp://www.j2mesalsa.com/struts/index.phphttp://www.j2mesalsa.com/struts/logictags.phphttp://struts.apache.org/tags-bean -
8/14/2019 Struts for Beginners
25/40
BOP taglib uriNhttp?@@struts.apache.org@tags-beanN prefiNbeanN O
BhtmlBhead
Btitle
*ogin Status
B@titleB@head
BbodyBbean?message keyNlogin.statusN @
BbrIou are logged in as BbBbean?write nameNlogin&eanN propertyNuser5ameN @B@b
B@body
B@html
Struts for Beginners: 2ogic #ag 2i'rar&&ack4 utorial %ome
*et us assume that we hae to display a number of fields in a table iew from the database. his
will need iteration through the result set which should be done using 1aa code in your !S9 pages
or use of !S* tags. Struts gies you a ready made tag library called GlogicH for this kind ofdisplay logic.
*ets modify our login program to learn about logic tag library. We will modify this proram to
list all the users in the database. 'dd more users to the database though your SR* client.
Create a new bean G6sersV:H$ also called the alue ob1ect by some programmers which will be
a place holder for the names retrieed from the database.
package com.salsa;
import java.io.Seriali>ale;pulic class 2sers?8 implements Seriali>ale"
private String user,ame;
pulic String getuser,ame#& "return user,ame;
)pulic void setuser,ame#String user& "
user,ame / user;)
)
'dd the code to get user names from the data base upon successful login..Statement statementconn.createStatement()Q
rs statement.eecuteRuery(NS#*#C 6S#85'M# +8:M CMS6S#8N)Q
http://struts.apache.org/tags-beanhttp://www.j2mesalsa.com/struts/jsps.phphttp://www.j2mesalsa.com/struts/index.phphttp://struts.apache.org/tags-beanhttp://www.j2mesalsa.com/struts/jsps.phphttp://www.j2mesalsa.com/struts/index.php -
8/14/2019 Struts for Beginners
26/40
'dd these resultset alues an 'rray*ist
*ist user*ist / new Arra-*ist#@&;while#rs.next#&& "
String user,ame / rs.getString#:&;S-stem.out.println#(user(=user,ame&;
2sers?8 users / new 2sers?8#&;users.setuser,ame#user,ame&;user*ist.add#users&;
)
Set the 'rray*ist as re/uest attribute so that it can be accessed from the !S9 page.
re/uest.set'ttribute(NusersN$ user*ist)Q
Complete Code listing of the 'ction class
pulic class 2ser*oginAction extends Action "pulic ActionForward execute#
ActionMapping mapping$ActionForm %orm$HttpServletRequest request$HttpServletResponse response& throws 'xception "
S-stem.out.println#(2ser*oginActionexecute#&(&;+onnection conn/null;ResultSet rs / null;oolean loginFlag / %alse;i% #is+ancelled#request&&"
return mapping.%indForward#(logincancel(&;)else "
tr-"+ontext context / new 4nitial+ontext#&;
+ontext env+ontext /#+ontext&context.lookup#(java5comp5env(&;
3ataSource dataSource/#3ataSource&env+ontext.lookup#(jdc5docmanager(&;
conn / dataSource.get+onnection#&;*oginForm loginForm / #*oginForm& %orm;0reparedStatement statement /
conn.prepareStatement#(S'*'+6 2S'R7,AM'$ 0ASS!8R3 FR8M +MS72S'R !H'R'
2S'R7,AM'/9 A,3 0ASS!8R3/9(&;statement.setString#:$loginForm.getuser,ame#&&;statement.setString#$loginForm.get0assword#&&;rs / statement.execute
-
8/14/2019 Struts for Beginners
27/40
tr-"Statement
statement/conn.createStatement#&;rs / statement.execute
-
8/14/2019 Struts for Beginners
28/40
B@logic?iterate
B@logic?present
Complete listing of loginStatus.1sp
BOP taglib uriNhttp?@@struts.apache.org@tags-beanN prefiNbeanN OBOP taglib uriNhttp?@@struts.apache.org@tags-logicN prefiNlogicNO
Bhtml
BheadBtitle
*ogin Status
B@titleB@head
Bbody
Bbean?message keyNlogin.statusN @
BbrIou are logged in as BbBbean?write nameNlogin&eanN propertyNuser5ameN @B@b
Blogic?present nameNusersNBtable borderN
-
8/14/2019 Struts for Beginners
29/40
A!A3+ As&nc$ronous !avaScript and 3M2
his tutorial teaches you basic concepts of '!', to get you started with '!',. his tutorialteaches you '!', with the help of toy eamples.
5et
ntroduction? '!', is acronym for 'synchronous !aaScript and ,M*. '!', is used to
do %9 re/uests for a small portion of the web page instead of the whole web page and
thus increasing the performance.
,M*%ttp8e/uest? raditionally in web applications a %M* page has a form tag or a
link and the re/uest is sent to serer by 9:S or 3# and whole new page is receied bythe browser. %oweer in the '!', the re/uest can be sent through a !aaScript ob1ect
called ,M*%ttp8e/uest ob1ect.
9roperties of ,M*%ttp8e/uest? here are arious properties associated with
,M*%ttp8e/uest which need to be used to complete '!', life cycle. *ets learn what
these properties are all about.
+unctions of ,M*%ttp8e/uest? here are arious functions associated with
,M*%ttp8e/uest which need to be used to complete '!', life cycle. *ets learn what
these functions are all about.
+irst '!', 9rogram? Combine all your aboe learnings to write your first '!',
program - GWord of the 0ayH.
A!A3: Introduction
&ack4 utorial %ome45et
'!', is acronym for 'synchronous !aaScript and ,M*. '!', is used to do %9 re/uests
for a small portion of the web page instead of the whole web page and thus increasing theperformance. Iour browser needs to be '!', Compatible for '!', scripts to work. Most ofthe latest browsers are '!', compatible. he popular '1a compatible browsers are
nternet #plorer >.F
+irefo
-
8/14/2019 Struts for Beginners
30/40
Safari
-
8/14/2019 Struts for Beginners
31/40
3oogle Maps
'nd this list can go on and on$ &ottom line is '!', has now become an essential component in
the web programming bou/uet.
A!A3 .##P 1e4uests&ack4 utorial %ome45et
raditionally in web applications a %M* page has a form tag or a link and the re/uest is sent to
serer by 9:S or 3# and whole new page is receied by the browser. %oweer in the '!',the re/uest can be sent through a !aaScript ob1ect called ,M*%ttp8e/uest ob1ect. his ob1ect
has the capability of re/uesting the serer in the background while the user is able to iew the
same page.
A!A3 and Browsers
hough all the browsers use ,M*%ttp8e/uest ob1ect for creating an '!', re/uest ob1ect.0ifferent browsers create it in a different manner. #arliest ersion of ,M*%ttp8e/uest was first
created by Microsoft for &rowser Web Mail access to #change serer. hen it was
implemented as an 'ctie , :b1ect and not as a natie !aa Script ob1ect. %oweer # .Fsupports this ob1ect. 3ien below are the arious ways of creating this ob1ect for arious
browsers.
)or )irefo,5 6pera 7895 Safari 0 Internet ",plorer
ajaxRequest8ject /new M*HttpRequest#&;
Some ersions of Safari and Mo2illa based browsers do not process the re/uest properly if the
response in not in proper ,M*. +ollowing mime oerriding will do the trick. # does not
support function oerrideMimeype(). hats the reason an if statement before calling thisfunction.
i% #ajaxRequest8ject.overrideMime6-pe& " ajaxRequest8ject.overrideMime6-pe#Btext5xmlB&;)
)or I" ;8 and I"
-
8/14/2019 Struts for Beginners
32/40
var ajaxRequest8ject;
%unction +reatemlHttp8ject#&"var ajaxRequest8ject/null;tr- " 55 +reate native oject55 For Fire%ox$ 8pera E.@=$ Sa%ari 55 4nternet 'xplorer G ajaxRequest8ject /new M*HttpRequest#&;
55 4'G does not support overrideMime6-pe#&i% #ajaxRequest8ject.overrideMime6-pe& "
ajaxRequest8ject.overrideMime6-pe#Btext5xmlB&;
) )catch #e& " 55 +reate Active oject 55 For 4nternet 'xplorer .@ I.@
tr- " ajaxRequest8ject/new Active8ject#(Msxml.M*H660(&; ) catch #e& " ajaxRequest8ject/new Active8ject#(Microso%t.M*H660(&; ) )return ajaxRequest8ject;)C5scriptD
A!A3: Properties of 3M2.ttp1e4uest
&ack4 utorial %ome45et
here are arious properties associated with ,M*%ttp8e/uest which need to be used tocomplete '!', life cycle. +ollowing are the arious properties of ,M*%ttp8e/uest ob1ect
onreadystatechange
readyState
responseet
response,M*
status
statuset
http://www.j2mesalsa.com/ajax/requests.phphttp://www.j2mesalsa.com/ajax/index.phphttp://www.j2mesalsa.com/ajax/index.phphttp://www.j2mesalsa.com/ajax/functions.phphttp://www.j2mesalsa.com/ajax/requests.phphttp://www.j2mesalsa.com/ajax/index.phphttp://www.j2mesalsa.com/ajax/functions.php -
8/14/2019 Struts for Beginners
33/40
#$e onread&statec$ange Propert&
onreadystatechange property of ,M*%ttp8e/uest needs to be set before the re/uest is sent to the
serer. he function set to this property acts as the eent handler function when the state of there/uest changes. he arious states of the re/uest are
8e/uest not initiali2ed
8e/uest set up
8e/uest sent
8e/uest in process
8e/uest completed
When eer there is change in the state the function set for onreadystatechange property is
inoked
ml%ttpCreate,ml%ttp:b1ect()Q
ml%ttp.onreadystatechangestateChanged()QstateChanged() X
@@ Code for handling the arious state changes.
Y
read&State Propert&
readyState property of ,M*%ttp8e/uest stores arious states of the re/uest mention in the
aboe section. #ach time this property changes the function set for onreadystatechange property
is inoked. 3ien below is the arious states and their respectie alues
%ere are the possible alues for the readyState property?
State Value
8e/uest not initiali2ed F
8e/uest set up e/DCD(=loadStatus=(CDC5%ontD(;
he below code should be placed in the within the head tags and is a complete listing ofthe '!', code needed for this eample.
CscriptD
var xmlHttp %unction +reatemlHttp8ject#&
http://www.j2mesalsa.com/ajax/functions.phphttp://www.j2mesalsa.com/ajax/index.phphttp://www.j2mesalsa.com/ajax/functions.phphttp://www.j2mesalsa.com/ajax/index.php -
8/14/2019 Struts for Beginners
39/40
" var ajaxRequest8ject/null; tr- " 55 +reate native oject
55 For Fire%ox$ 8pera E.@=$ Sa%ari 4nternet 'xplorer G55 ajaxRequest8ject/new M*HttpRequest#&
55 4'G does not support overrideMime6-pe#& i% #ajaxRequest8ject.overrideMime6-pe& " ajaxRequest8ject.overrideMime6-pe#Btext5xmlB&; ) ) catch #e& " 55 +reate Active oject 55 For 4nternet 'xplorer .@ I.@ tr- " ajaxRequest8ject/new Active8ject#(Msxml.M*H660(&; )
catch #e& " ajaxRequest8ject/new Active8ject#(Microso%t.M*H660(&; ) ) return ajaxRequest8ject; ) %unction state+hanged#& "
i% #xmlHttp.read-State//K& " i% #xmlHttp.status // @@& "document.get'lementJ-4d#(wordtext(&.innerH6M*/xmlHttp.response6ext; ) else " document.get'lementJ-4d#(wordtext(&.innerH6M*/('rror %etching
data$ 0lease tr- again.(; ) ) ) %unction show!ord#loadStatus& " var loadStatus/loadStatus; 55 Show loading within div tags screen e%ore making a request. document.get'lementJ-4d#(wordtext(&.innerH6M*/(C%ont
%ace/Arial si>e/DCD(=loadStatus=(CDC5%ontD(;
55 +reate mlHttp8ject xmlHttp/+reatemlHttp8ject#&; i% #xmlHttp//null& " alert #(Lour rowser does not support AAN(&; return; )
55 use a random sid to avoid rowser caching var url/(5inc5word.php(=(9sid/(=Math.random#&; xmlHttp.onread-statechange/state+hanged;
-
8/14/2019 Struts for Beginners
40/40