This is a serializable abstract class that provides a wrapper for javabeans to enable themto interact with Struts componentsAs part of the struts framework itrsquos functions are
hold the current state of the application (remember that the ActionServletautomatically populates any associated ActionForm)
validate values passed to it by the ActionServlet using the validate() method reset field values using the reset() method
To create an ActionForm create a javabean like the DivisionBean and extend theActionForm class
ltform-beansgtltform-bean name=rdquoDivisionFormrdquo type=rdquocomffictrainingDivisionBeanrdquo gt
Also in the struts-configxml file associate this form with an Action class This will letthe ActionServlet know that when it receives a request to invoke the Action class namedldquovalidateDivisiondordquo it will populate an instance of DivisionForm with whatever valueswere entered on the browser
type=rdquocomfficexamplestrutsValidateDivisionrdquoname=rdquoDivisionFormrdquoscope=rdquorequestrdquoinput=rdquoInputjsprdquogtltforward name=rdquosuccessrdquo path=rdquoDisplayDivisionjsprdquogt
The Action class is midway between the Model and the Controller portion of MVC in thatit can act as a dispatcher as well as maintaining the state of the application using theassociated ActionForm
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
101
Itrsquos main responsibilities are
receives request from the ActionServlet and associated objects (actionmappingresponse ActionForm instance)
since this is developer-provided it can be programmed to dispatch the process toother classesjavabeans or access a db
creates objects to hold any errorsmessages (ActionErrorActionMessage) detectedduring processing
creates an object to hold redirect information (ActionForward) and returns it to theActionServlet for proper disposition
Once an Action class is invoked the ActionServlet calls itrsquos execute() method where itpasses the information necessary to process a request The signature for the executemethod is
public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)
throws IOExceptionServletException your codes here
To create an Action class create a class that extends orgapachestrutsactionAction
public class ValidateDivisionAction extends orgapachestrutsactionAction
Inside this class you must implement the execute() method
public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)
throws IOExceptionServletException your codes here
Herersquos a skeleton code to put in the execute() method with some explanations
create a container for errors that my be detected while processingActionErrors errors = new ActionErrors()
try since the ActionForm instance is one of the arguments in the execute method cast theform back to itrsquos original class type
DivisionBean divBean = (DivisionBean) form
perform any processing here example
102
The following lines check for a division number If null then an error object is created tohold an error message This object is then associated with the error container previouslydefined
if (divBeangetDivNo()trimequals(ldquordquo) ActionError error = new ActionError(ldquoerrormissingdivisionrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)
Check the error container If it contains an object then construct an ActionForwardinstructing the ActionServlet to re-render the origin of the request
if(errorssize() gt 0) saveErrors(requesterrors) return new ActionForward(mappinggetInput())
this looks up a path called ldquosuccessrdquo in the actionmapping (see ltaction-mappingsgt tagin struts-configxml) and builds the object for it
return mappingfindForward(ldquosuccessrdquo)
catch (Throwable e) eprintStackTrace()
For runtime errors an object to hold the error message is created and associated withthe container previously defined
ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
Associate the error container with the request object saveErrors(request errors)
looks up the originating path (designated by the ldquoinput=rdquo attribute in the ltaction-mappingsgt tag in struts-configxml) and creates a forward object for it For errors we usually send the user back to the page that caused the error and displaythe error messages there
return new ActionForward(mappinggetInput())
ActionMapping (orgapachestrutsactionActionMapping)
An action mapping tells the ActionServlet and Action class several things
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
103
what Action class processes a request what form is associated with the Action and the scope for that form the origin of the request redirect information any parameter to be passed to the Action class to validate or not to validate the associated form
To configure an actionmapping
Create an ltaction-mappingsgt tag in struts-configxml
Inside the ltaction-mappingsgt tag define the action information such as the following
This is the logical name for the ValidateDivision class so you would call this class usingvalidateDivisiondo from the browser
ltaction path=rdquovalidateDivisionrdquotype=rdquocomfficexamplestrutsValidateDivisionrdquo
Associate DivisionForm to this Action class with a scope of requestname=rdquoDivisionFormrdquoscope=rdquorequestrdquo
The origin of this request is Inputjsp
input=rdquoInputjsprdquogt
Any redirect information is enclosed in a ltforwardgt tag Here the logical name (or key) ofthe forward is ldquosuccessrdquo and the relative path is DisplayDivisionjsp
ltforward name=rdquosuccessrdquo path=rdquoDisplayDivisionjsprdquogt
ltactiongt
ActionErrors (orgapachestrutsactionActionErrors) ActionMessages(orgapachestrutsactionActionMessages)
An action error wraps an error message while an action message wraps a message to berendered on the browser using struts tagsWhen they are created they must be associated with their respective containers(ActionErrors and ActionMessages) so that they can be accessed by the browser
To create an ActionError
First you must instantiate an error container (ActionErrors)
104
ActionErrors errors = new ActionErrors()
Create the error object then add it to the ActionErrors object
ActionError error = new ActionError(ldquothisisanerrrorrdquo)errorsadd(ActionErrorsGLOBAL_ERROR error)
To create an ActionMessage
First you must instantiate a message container (ActionMessages)
ActionMessages messages = new ActionMessages()
Create the message object then add it to the ActionErrors object
ActionMessage message = new ActionError(ldquothisisamessagerdquo)messagesadd(ActionMessagesGLOBAL_MESSAGE message)
This is getting way ahead of the subject but just to satisfy your curiosity we can renderthese containers on the browser using the following tags (ie this goes into your jsp)
Checks for presence of messages
ltlogicmessagesPresentgt
Renders a message from the application resource file with a key of ldquoerrorsheaderrdquo
ltbeanmessage key=rdquoerrorsheaderrdquogt
ltulgt
Creates a page scope object of the messages object
lthtmlmessages id=rdquoerrorrdquogt
Renders the contents of the messages object referenced by the ldquoerrorrdquo id
ltligtltbeanwrite name=rdquoerrorrdquogtltligtlthtmlmessagesgtltulgtlthrgt
Closing tag
ltlogicmessagesPresentgt
ActionForward (orgapachestrutsactionActionForward)
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
105
This encapsulates redirect information that is recognized and acted upon by theActionServlet
Two popular ways of creating an actionforward
Search the Action classrsquo action mapping for a redirect path with a key of ldquosuccessrdquo
mappingfindForward(ldquosuccessrdquo)
Create a new ActionForward object by retrieving the redirect path from the Action classrsquoactionmapping referenced by the ldquoinput=rdquo attribute
new ActionForward(mappinggetInput())
Application resource for internationalizationlocalization of prompts and messages
Struts uses the java Locale and ResourceBundle classes to handle internationalizationand localization of prompts and messages By this we mean that we can declare keyvalues in our jsprsquos or java classes and Struts will look up the correct values using thesekeys in a properties file This is all done using custom tags provided as part of the StrutsframeworkIn initializing the ActionServlet we added an initialization parameter to tell it where to lookfor a properties file
ltinit-parametergt ltnamegtapplicationltnamegt ltvaluegtApplicationResourcesltvaluegt ltinit-parametergt
This file (physical name = ApplicationResourcesproperties) contains keyvalue pairs thatare as said previously looked up by Struts based on keys passed to it
In the ActionError example
ActionError error = new ActionError(ldquoerrormissingdivisionrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)
When we create the ActionError we pass a key to it and Struts will look it up in theApplicationResourcesproperties file In this file we may have an entry such as
errormissingdivision = You must supply a value for the Division No field
So in our jsp when we use a custom tag such as lthtmlerrors gt what we will seedisplayed on the browser is
You must supply a value for the Division No field
106
This feature of Struts enables us to maintain a central repository for all our prompts andmessages
Tag LibrariesThe framework works hand-in-hand with a set of tag libraries which can be used forcontent rendition in our jsprsquos The tag libraries work pretty much like what yoursquove learnedin Lesson 10 on custom tags This is not an exhaustive list of the available tags but theones listed here are the ones most often used
Bean Tags
ltbeandefinegt - used to create or copy existing beans
example
ltbeandefine id=rdquomyBeanrdquo
ltbeanwritegt - used to render bean properties
example
displays the value of division number in the divisionForm beanltbeanwrite name=rdquodivisionFormrdquo property=rdquodivNordquo gt
ltbeanmessagegt - used to render internationalized promptsmessages
example
displays the value for the key ldquoerrormissingdivisionrdquo in theApplicationResourcesproperties fileltbeanmessage key=rdquoerrormissingdivision gt
HTML Tags
lthtmlformgt - render an html formlthtmltextgt - render a text inputlthtmlradiogt - render a radio buttonlthtmltextareagt - render a textarealthtmlselectgt - render a select listlthtmloptiongt - render an item for select listlthtmloptionsgt - render items for a select list based on a collectionlthtmlcheckboxgt - render a checkboxlthtmlpasswordgt - render a masked field for passwordlthtmlbuttongt - render a buttonlthtmlsubmitgt - render a submit button
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
107
lthtmlcancelgt - render a submit button but bypasses the validate() method ofthe ActionForm
example
this will render a form that lets the user enter a division number and whensubmitted invokes the validateDivision action (see above action mapping instruts-configxml)
lthtmlform action=rdquovalidateDivisiondordquo gtlthtmltext property=rdquodivNordquo gtlthtmlsubmit gtlthtmlcancel gt
lthtmlformgt
lthtmlmessagesgt - render messageserrors (ActionErrorsActionMessages)
example
Creates a page scope object of the messages object
lthtmlmessages id=rdquoerrorrdquogt
Renders the contents of the messages object referenced by the ldquoerrorrdquo id
ltligtltbeanwrite name=rdquoerrorrdquogtltligtlthtmlmessagesgt
lthtmlerrorsgt - render errors (ActionErrors only)
example
using this tag as is will cause the browser to render the contents of theActionErrors object
lthtmlerrors gt
lthtmlrewritegt - rewrite the relative URL of the requestlthtmllinkgt - render a URL link
Logic Tags
ltlogicequalsgt - used to compare equal values
108
ltlogicnotEqualsgt - used to compare unequal values
example
compares the value of the division number in the instance of divisionForm withthe number 1
ltlogicequal name=rdquodivisionFormrdquo property=rdquodivNordquo value=rdquo1rdquogt
ltlogicpresentgt - checks for presence of an object (bean parameter etc)ltlogicnotPresentgt- checks for absence of an object (bean parameter etc)
example
checks for the presence of the collection divList
ltlogicpresent name=rdquodivListrdquogt
ltlogiciterategt - iterates through a collection
example
iterate through the divList collectionltlogiciterate name=rdquodivListrdquoid=rdquodivrdquoscope=rdquorequestrdquotype=rdquocomffictrainingdivListrdquogt
ltlogicmessagesPresentgt - checks for the contents of theActionMessagesActionErrors collections
Template Tags
These tags help to create a template for the jsp pages to provide a standard look lsquon feelwith minimal coding effort
lttemplategetgt- defines references for dynamic contents to be placed in the templatejsp
example
You can create a template jsp named templatejsp with the following code
this creates a reference for the placement of contents in this template
lttemplateget name=rdquocontentrdquo gt
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
109
lttemplateinsertgt - defines the template jsp to be usedlttemplateputgt- places contents in the template based on references
example
Using the above template you can start using it in a jsp (ex mySamplejsp) usingthe code below
The divContentjsprsquos contents are inserted in the template and then included inthe output of mySamplejsp
lttemplateinsert template=rdquotemplatejsprdquogtlttemplateput name=rdquocontentrdquo content=rdquodivContentjsprdquo gt
lttemplateinsertgt
To configure the tag libraries place the taglib descriptors (tld) in the WEB-INF folder ofyour application
struts-beantldstruts-htmltldstruts-logictldstruts-templatetld
and make the following entries in the webxml file for ORION (no need to do this inWebSphere)
lttaglibgtlttaglib-urigtbeanlttaglib-urigtlttaglib-locationgtWEB-INFstruts-beantldlttaglib-locationgt
lttaglibgtlttaglibgt
lttaglib-urigthtmllttaglib-urigtlttaglib-locationgtWEB-INFstruts-htmltldlttaglib-locationgt
lttaglibgtlttaglibgt
lttaglib-urigtlogiclttaglib-urigtlttaglib-locationgtWEB-INFstruts-logictldlttaglib-locationgt
lttaglibgtlttaglibgt
lttaglib-urigttemplatelttaglib-urigtlttaglib-locationgtWEB-INFstruts-templatetldlttaglib-locationgt
lttaglibgt
Learning the Struts framework and itrsquos add-ons requires more than what this lesson canprovide This is just to give you a preview of the frameworkrsquos capabilities and how you asa developer can start to use it to build your own web application
110
Useful LinksHere are some useful links to fill-in the gaps of what yoursquove learned so far
Struts homepage httpjakartaapacheorgstruts
User Guide httpjakartaapacheorgstrutsdoc-102userGuideindexhtml
Javadoc httpjakartaapacheorgstrutsdoc-102apiindexhtml
Resources (documentation etc) httpjakartaapacheorgstrutsresourceshtml
Taglib documentationBean Tags httpjakartaapacheorgstrutsdoc-102struts-beanhtmlHTML Tags httpjakartaapacheorgstrutsdoc-102struts-htmlhtmlLogic Tags httpjakartaapacheorgstrutsdoc-102struts-logichtmlTemplate Tags httpjakartaapacheorgstrutsdoc-102struts-logichtml
Struts-user Mailing List Archive (either join the list or just search the archive) httpwwwmail-archivecomstruts-user40jakartaapacheorg
Yet another tutorial httprzserv2fhnonde~lg002556strutsDokuhtmlc4
NEXTLETrsquoS BUILD A SAMPLE STRUTS-BASED WEB APPLICATION
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
111
Lesson 16 - Building a simple web applicationusing Struts
BasicsIn this lesson we will build a simple web application using Struts as our framework Wersquollalso stop referencing the ORION webserver from hereon so the coding and deploymentinstructions all relate to the WebSphere Test Environment
The example web application will have the following specificationsflow
JSP 1 ndash allows the user to enter a name and passwordAction class ndash receives the request from the ActionServlet and validates the input Itthen instructs the ActionServlet (using an ActionForward) where to go next depending onwhether an error was detected or notJSP 2 ndash takes the result passed by the ActionServlet and renders it on the screen
We will also provide error-handling in the sample application If no values were enteredthe Action class will create an ActionError object and place it in the ActionErrors instanceThe ActionErrors instance will then be rendered by JSP 1 (yes the originating JSP)
CodingTo create a struts-based application we need to keep the following tasks in mind
Create an ActionForm object that will hold the userid and password values Create the Action class that will process the form Create the JSPs that will use taglibs to render the forms and prompts Create form-bean and action-mapping entries in struts-configxml Create entries in the ApplicationResourcesproperties file for any internationalized
promptsmessages
1 In the package comffictraining create a class named LoginForm and extend theActionForm class Be sure to import the necessary packages
import orgapachestrutsactionActionForm
public class LoginForm extends orgapachestrutsactionActionForm private String userIdprivate String password
public String getUserId()return userId
112
public String getPassword()return passwordpublic void setUserId(String userId)thisuserId = userIdpublic void setPassword(String password) thispassword = password
2 In the package comffictraining create a class named LoginAction and be sure toextend the struts Action class Also make sure that you import the necessarypackages or classes
import orgapachestrutsactionActionimport orgapachestrutsactionActionFormimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOExceptionimport javautilListimport javaio
public class LoginAction extends orgapachestrutsactionAction
Using the skeleton code in Lesson 15 as basis for the Action class wersquoll implement theexecute() method as follows
public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)
throws IOExceptionServletException
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
113
create a container for errors that my be detected while processingActionErrors errors = new ActionErrors()
try
cast the LoginForm form back to itrsquos original class typeLoginForm loginForm = (LoginForm) form
The following lines make sure the user entered a userid and password Otherwise anActionError object is created
if (loginFormgetUserId()trim()equals(ldquordquo)) ActionError error = new ActionError(ldquoerrormissinguseridrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)
if (loginFormgetPassword()trim()equals(ldquordquo)) ActionError error = new ActionError(ldquoerrormissingpasswordrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)
If errors were detected the process terminates and this Action class tells theActionServlet to redirect the output back to the originating jsp where the error(s) will bedisplayed
if(errorssize() gt 0) saveErrors(requesterrors) return new ActionForward(mappinggetInput())
If no errors were detected then proceed with accessing the db
return mappingfindForward(ldquosuccessrdquo)
catch (Throwable e) eprintStackTrace()
For runtime errors an object to hold the error message is created and associated withthe container previously defined
ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
Associate the error container with the request object
114
saveErrors(request errors)
looks up the originating path (designated by the ldquoinput=rdquo attribute in the ltaction-mappingsgt tag in struts-configxml) and creates a forward object for it For errors we usually send the user back to the page that caused the error and displaythe error messages there
return new ActionForward(mappinggetInput())
3 Next is to create the JSP that will accept user input
JSP 1 ndash Create a file named Loginjsp and save it in the craft folder in VAJWTE
At the top of the jsp place the directives for the taglibs that wersquoll be using
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gt
Before anything else place tags to render errors This will display nothing when the pageis invoked for the first time
It can either be a simple lthtmlerrors gt OR
ltlogicmessagesPresentgt ltbeanmessage key=errorsheadergt ltulgt lthtmlmessages id=errorgt ltligtltbeanwrite name=errorgtltligt lthtmlmessagesgt ltulgtlthrgtltlogicmessagesPresentgt
Next place the following lines of codes to render an html form
lthtmlform action=rdquologindordquo gt
Then create an html table with 2 columns and 2 rows
lttable border=rdquo1rdquogtlttrgt lttdgtlttdgt lttdgtlttdgtlttrgtlttrgt lttdgtlttdgt
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
115
lttdgtlttdgtlttrgtlttablegt
In the first row (ie the first lttrgt tag) add the tags to render the label and text input for theuserid in each column (ie each pair of lttdgtlttdgt tags)
lttrgt lttdgtltbeanmessage key=rdquopromptloginuseridrdquo gtlttdgt lttdgtlthtmltext property=rdquopasswordrdquo gtlttdgtlttrgt
In the next row add the tags to render the label and text input for the userid
lttrgt lttdgtltbeanmessage key=rdquopromptloginpasswordrdquo gtlttdgt lttdgtlthtmlpassword property=rdquouserIdrdquo gtlttdgtlttrgt
Then render a submit button and finally properly terminate the form tag
lthtmlsubmit gtlthtmlformgt
The complete jsp will look like the following
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gt
ltlogicmessagesPresentgt ltbeanmessage key=errorsheadergt ltulgt lthtmlmessages id=errorgt ltligtltbeanwrite name=errorgtltligt lthtmlmessagesgt ltulgtlthrgtltlogicmessagesPresentgt
lthtmlform action=logindo gt
lttable border=1gtlttrgt lttdgtltbeanmessage key=promptloginuser gtlttdgt lttdgtlthtmltext property=userId gtlttdgtlttrgtlttrgt lttdgtltbeanmessage key=promptloginpassword gtlttdgt
116
lttdgtlthtmlpassword property=password gtlttdgtlttrgtlttablegt
lthtmlsubmit gtlthtmlformgt
4 Wersquoll then create the jsp that will display a welcome message and the userid
JSP 2 ndash Create a file named Welcomejsp and save it in the craft folder in VAJWTE
At the top of the jsp place the directives for the taglibs that wersquoll be using
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtThen create a 1-column1-row table so we can center the welcome message on thescreen
lttable width=100 height=100gtlttrgtlttd valign=rdquocenterrdquo align=rdquocenterrdquogtlttdgtlttrgtlttablegt
Inside the column place the welcome message and the tag that renders the userid
lth2gtltbeanmessage key=promptwelcomemsg gt ltbeanwrite property=userIdname=loginForm gt lth2gt
The complete JSP will look like the following
lttaglib uri=WEB-INFstruts-beantld prefix=bean gt
lttable width=100 height=100gtlttrgt lttd valign=center align=centergt lth2gtltbeanmessage key=promptwelcomemsg gt ltbeanwrite property=userIdname=loginForm gt lth2gt lttdgtlttrgtlttablegt
5 We then have to create the necessary entries in the struts-configxml file so theActionServlet knows the relationships of the components we previously created Soopen the struts-configxml file located in craftWEB-INF in VAJWTE and add thefollowing entries
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
117
Form bean entry ndash place this inside the ltform-beansgt tag
ltform-bean name=rdquologinFormrdquo type=rdquocomffictrainingLoginFormrdquo gt
Action mapping entry ndash place this inside the ltaction-mappingsgt tag
ltaction path=rdquologinrdquotype=rdquocomffictrainingLoginActionrdquoname=rdquologinFormrdquoscope=rdquorequestrdquoinput=rdquoLoginjsprdquogtltforward name=rdquosuccessrdquo path=rdquoWelcomejsprdquogt ltactiongt
Lastly we need to create entries for the internationalized promptsmessages that we putin our jsps and Action class
Since we already have an existing resource under the STRUTS EXAMPLE project wersquolljust update that one with the entries below In VAJ go to the Resource tab and look forthe ApplicationResourcesproperties file under the STRUTS EXAMPLE project Openit and add the following codeserrorsfooter=errorsheader=lth3gtltfont color=redgtValidation Errorltfontgtlth3gtYou must correct thefollowing error(s) before proceeding
errormissinguserid=ltfont color=redgtltbgtPlease enter a user idltbgtltfontgterrormissingpassword=ltfont color=redgtltbgtPlease enter a passwordltbgtltfontgt
promptloginuser=ltbgtUser Id ltbgtpromptloginpassword=ltbgtPassword ltbgt
promptwelcomemsg=ltbgtWelcome ltbgt
Deploying the code
1 Make sure you have all the components described in the previous section and thatthe bean and action class have no compile errors
2 Bring up WTE and start the servlet engine Make sure the class path points to allnecessary projects
3 Bring up a browser and type the following URL on the address line
httplocalhost8080craftLoginjsp
118
ResultThe initial page should look like the following
If the user did not enter anything in the form the following will be displayed
If both userid and password were entered then the following will be displayed
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
119
120
Lesson 17 ndash Validating form valuesBasicsIn Lesson 16 we created a struts-based application that uses many of the featuresprovided by the framework In the Action class (LoginAction) we placed codes that makesure the user entered values in the form fields (userid and password) If not thenActionError objects are created and rendered on the browser As you build Action classesfor different forms yoursquoll find yourself coding the same if-then-else block of code over andover again especially the codes that check if the field is null Maintaining these similarblocks of codes can quickly become a nightmare In version 10 of Struts a contributor extension was introduced which provides a genericway of performing field validation both on the client-side and server-side This extensionis now an official part of the Struts framework starting with 11b and is known as thestruts-validator With this extension you get to define validation rules for your formsrsquofields in an xml file (validationxml) and put minimal coding in your Action class to triggerthe validation process (ValidatorFormvalidate()) on the server-side On the client-sideyou can put html tags (htmljavascipt) in your jsp page to instruct the validator to generatejavascript validation codes on your html page to perform client-side validation In case theuser turns javascript off in his browser then the server-side validation will kick-in
So that was a short description of the struts validator and what it can do for you thedeveloper to shorten development time and effort So letrsquos try the struts validator on thesample application that we created in the previous lesson
InstallationAlthough it is part of the binary distribution of struts we have to make sure that we havethe necessary components installed in our webserver before we start using the struts-validator
1 You need to download the Regular Expression package from the apache website asthe struts-validator depends on this for pattern matching
Download from httpjakartaapacheorgbuildsjakarta-regexpreleasev12The link is jakarta-regexp-12zip
In VAJ create a project named Regular Expression and import the jakarta-regexp-12jar file (extract this first from the zip file) into the Regular Expressionproject
2 Make sure you have the following files in your craftWEB-INF folder in VAJWTE Ifnot go back to the struts binary distribution and extract these files
validationxml validator-rulesxml
3 Open the file struts-configxml in craftWEB-INF and make the following changes
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
121
Add the following lines of codes just before the ltstruts-configgt tag
lt-- =============================== Message Resources Definitions --gt
lt-- Validator --gt
You can put validator-related key-value pair messages here but wersquoll mostly be using theApplicationResource for the ActionServlet
ltmessage-resourcesparameter=orgapachestrutswebappvalidatorApplicationResourcesgt
lt-- ====================================== Plug Ins Configuration --gt
Here we define the validator plug-in and specify the path of the xml files that contain thevalidation rules In Struts 10 we had to extend the ActionServlet to incorporate thevalidator which was not a very elegant and performant way of adding extensions toStruts
lt-- Validator --gtlt-- Add multiple validator resource files by setting the pathname property --gtltplug-in className=orgapachestrutsvalidatorValidatorPlugIngt ltset-property property=pathname value=WEB-INFvalidator-rulesxmlgt ltset-property property=pathname value=WEB-INFvalidationxmlgtltplug-ingt
CodingNow that we have our environment all set up we can now start using the struts-validatorto validate our form fields
1 When we created our form we extended the ActionForm class To use the validatorwe instead extend the ValidatorForm class to tell the validator to perform thevalidation for that form This form like the ActionForm has a validate() method thatperforms the server-side validation which we will see later
In our LoginForm change the ActionForm to ValidatorForm
import orgapachestrutsvalidatorValidatorForm
public class LoginForm extends orgapachestrutsvalidatorValidatorForm private String userIdprivate String password
public String getUserId()
122
return userIdpublic String getPassword()return passwordpublic void setUserId(String userId)thisuserId = userIdpublic void setPassword(String password) thispassword = password
2 In the LoginAction class make the following changes
Comment outremove the following lines of codes since we want the struts-validatorto take over the validation
if (loginFormgetUserId()trim()equals()) ActionError error = new ActionError(errormissinguserid)errorsadd(ActionErrorsGLOBAL_ERRORerror)
if (loginFormgetPassword()trim()equals()) ActionError error = new ActionError(errormissingpassword)errorsadd(ActionErrorsGLOBAL_ERRORerror)
if(errorssize() gt 0) saveErrors(requesterrors)
return new ActionForward(mappinggetInput())
Replace them with the following lines of codes
errors = loginFormvalidate(mappingrequest)if (errorsempty()) saveErrors(request errors) return new ActionForward(mappinggetInput())
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
123
The above codes will invoke the validate() method of the ValidatorForm All we need todo here is to check if the errors object contains errors so that we can save them (iesaveErrors()) and render them to the browser (ie the origin)
3 Now that wersquove changed our code to use the struts-validator we have to define thevalidation rules for our LoginForm form Before we move on open the file validator-rulesxml and examine the contents Looking at the ltvalidatorgt tags yoursquoll see thatthis file contains pre-defined validation logic for required filedscommon data types (iebyte integer short double long) numeric ranges date format email addresses andeven credit card
The most useful of these is the mask validation rule You can create patterns for yourfields using regular expressions and the struts-validator will make sure that the valuethe user entered matches the pre-defined pattern Take a brief tour of the RegularExpression package in the apache website to learn how to define patterns Wersquoll usea pattern in our example to illustrate how this work
First in the topmost portion of the validator-rulesxml file there is an instruction thatsays you need to copy the default error messages in theApplicationResourcesproperties file Here are the codes (and instruction)
These are the default error messages associated with each validator defined in this file They should be added to your projects ApplicationResourcesproperties file or you can associate new ones by modifying the pluggable validators msg attributes in this file Struts Validator Error Messages errorsrequired=0 is required errorsminlength=0 can not be less than 1 characters errorsmaxlength=0 can not be greater than 1 characters errorsinvalid=0 is invalid errorsbyte=0 must be an byte errorsshort=0 must be an short errorsinteger=0 must be an integer errorslong=0 must be an long errorsfloat=0 must be an float errorsdouble=0 must be an double errorsdate=0 is not a date errorsrange=0 is not in the range 1 through 2 errorscreditcard=0 is not a valid credit card number errorsemail=0 is an invalid e-mail address
124
Open the ApplicationResourcesproperties file in the STRUTS EXAMPLE project(click on the Resources tab in VAJ) and paste the above codes (except theinstructions) if theyrsquore not there yet
Open the validationxml file and remove all the contentsAdd the following lines of codes
This tag starts the validation ruleltform-validationgt
This starts a validation rule for a form The name attribute should match the form name inyour ltform-beangt entry in struts-configxmlltform name=loginFormgt
This starts a validation rule for a form for a particular locale (language) You will need todefine a formset for each locale that you support in your application This examplehowever uses only one locale
ltformsetgt
The next codes define validation rules for each of the field in your form The propertyattribute value should match the property (gettersetter) value in your form (LoginForm)
ltfield property=userId
This attribute (depends) instructs the validator which rules in the validate-rulesxml file touse (remember these are defined by the ltvalidatorgt tag In this example we require theuserid field to a) contain a value (required) and b) be a valid email address (email)
depends=requiredemailgt
The next line simply provides a value to the argument in the message to be generated forthis rule We have the promptloginuser=User Id defined in ourApplicationResourcesproperties In case an error say no value entered was detectedfor this field the message User Id is required will be displayed on the browser Therequired validation rule contains the message key errorsrequired which points to errorsrequired=0 is required in the ApplicationResourcesproperties file The 0denotes an argument that can be replaced with whatever we want
ltarg0 key=promptloginusergt
ltfieldgt
Here we require the password to a) contain a value (required) and b) follow a pre-definedpattern (mask) For the mask validation we provided a ltvargt tag which defines thepattern for this field According to the pattern the password will only contain lowercase oruppercase alpha characters no numbers
ltfield
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
125
property=password depends=requiredmaskgt
ltvargt ltvar-namegtmaskltvar-namegt
ltvar-valuegt^[a-zA-Z]$ltvar-valuegt ltvargt
ltarg0 key=promptloginpasswordgt ltfieldgt ltformgt
ltformsetgt ltform-validationgt
The complete entry is as follows
ltform-validationgtltformsetgt
ltform name=loginFormgt
ltfield property=userId depends=requiredemailgt
ltarg0 key=promptloginusergt
ltfieldgtltfield
property=password depends=requiredmaskgt
ltarg0 key=promptloginpasswordgt ltvargt
ltvar-namegtmaskltvar-namegt ltvar-valuegt^[a-zA-Z]$ltvar-valuegt ltvargt
ltfieldgt ltformgt ltformsetgt ltform-validationgt
4 In the Loginjsp we have already provided codes that display the errors Here is theblock of code that does so
ltlogicmessagesPresentgt ltbeanmessage key=errorsheadergt
126
ltulgt lthtmlmessages id=errorgt ltligtltbeanwrite name=error filter=falsegtltligt lthtmlmessagesgt ltulgtlthrgtltlogicmessagesPresentgt
In most cases however we will want to display the error message beside the field thathas an error instead of lumping all of them up on top of the page To do this add thefollowing codes to the Loginjsp file
After the userid field add the following lines
lttdgtlthtmlmessages id=error property=userIdgt ltbeanwrite name=error filter=falsegtltbrgt lthtmlmessagesgtlttdgt
After the password field add the following lineslttdgtlthtmlmessages id=error property=passwordgt ltbeanwrite name=error filter=falsegtltbrgt lthtmlmessagesgtlttdgt
The lthtmlmessagesgt tag knows which error belongs to what field using the propertyattribute which again should match the LoginFormrsquos gettersetter values Neat isnrsquot it
5 Previously we discussed that the struts-validator can also generate javascript toperform client-side validation To do this add the following line of code just before thelthtmlgt tag
lthtmljavascript formName=loginForm gt
The formName attribute must match the ltform-beangt entry in the stuts-configxmlfile
Also change the following line of code
lthtmlform action=logindo gt
to
lthtmlform action=logindo onsubmit=return validateLoginForm(this) gt
Complete code
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gt
ltlogicmessagesPresentgt
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
127
ltbeanmessage key=errorsheadergt ltulgt lthtmlmessages id=errorgt ltligtltbeanwrite name=error filter=falsegtltligt lthtmlmessagesgt ltulgtlthrgtltlogicmessagesPresentgt
lthtmlform action=logindo onsubmit=return validateLoginForm(this) gt
lttable border=1gtlttrgt lttdgtltbeanmessage key=promptloginuser gtlttdgt lttdgtlthtmltext property=userId gtlttdgt lttdgtlthtmlmessages id=error property=userIdgt ltbeanwrite name=error filter=falsegtltbrgt lthtmlmessagesgtlttdgt lttrgtlttrgt lttdgtltbeanmessage key=promptloginpassword gtlttdgt lttdgtlthtmlpassword property=password gtlttdgt lttdgtlthtmlmessages id=error property=passwordgt ltbeanwrite name=error filter=falsegtltbrgt lthtmlmessagesgtlttdgt lttrgtlttablegt
lthtmlsubmit gtlthtmljavascript formName=loginForm gtlthtmlformgt
Thatrsquos all there is to it It may look like a lot of steps but once yoursquove done several ofthese it will be a lot quicker for you to put together a set of rules for a particular formAlso remember that these are one-time deals in that once yoursquove defined the formrsquosvalidation rules yoursquoll seldom have to change them
Deploying the code1 Bring up the WebSphere Test Environment in VAJ 2 Make sure the necessary projects are in your servlet enginersquos classpath especially
the Regular Expression package then start the servlet engine3 Bring up a browser and type the following in the address line
128
httplocalhost8080craftLoginjsp
ResultsYou will see the following screens displayed
1 Upon initial invocation of the jsp
2 Screen display if no values were entered in both fields
3 Screen display if an invalid email address was entered for the userid field and thepassword contains numeric data
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
129
4 Welcome screen displayed if valid values were entered in the userid and passwordfields
130
Lesson 18 ndash Nested BeansBasicsIn this lesson we will cover the concept of combining several beans into one form andhow to access their properties using Struts standard taglibs and the nesting extensionrecently incorporated into Struts version 11b
So what are nested beans anyway In simple terms you can think of nestedbeans as beans within beans Nesting beans provides for a parent-childrelationship which is not far from how relational dbs work Struts already providestaglibs that render nested bean properties using the standard taglibs that comewith the distribution The nesting extension however makes coding the jsp a lotsimpler
InstallationThe nested tags are already included with the binary distribution of Struts 11b Wersquoll dosome preliminary setup and verification of our environment before we proceed
1 Make sure that the file struts-nestedtld is in the craftWEB-INF folder ofVAJWTE If not go back to the binary distribution of Struts 11b and extract this file
Thatrsquos all
CodingLetrsquos do some examples three examples actually
CODING PART 1
We have an account that contains an account number gross amount and debtorinformation Debtor information includes name address and phone number
We can have the debtor information in a database table and the account information inanother table We then create beans that represent instances of each record in thesetables Wersquoll name them AccountBean and DebtorBean
Below is the code for the DebtorBean We provided a constructor to create an instance ofthis bean without using the setters In the real-world wersquoll always use the settersgettersfor the bean
1 Create a class named DebtorBean in the package comffictraining in VAJ andpaste the following code
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
131
public class DebtorBean
private String nameprivate String addressprivate String phone
constructor
public DebtorBean (String name String address String phone)
thisname = namethisaddress = addressthisphone = phone
getters
public String getName() return name
public String getAddress() return address
public String getPhone() return phone
setters
public void setName(String name) thisname = name
public void setAddress(String address) thisaddress = address
public void setName(String phone) thisphone = phone
132
2 To correctly represent the model for the account the AccountBean will extend theActionForm and then wersquoll include the DebtorBean bean inside the AccountBeanThe code for this is as follows
Create a class named AccountBean in the package comffictraining and paste thefollowing code
package comffictraining
import javautil Insert the types description here Creation date (51002 112331 AM) author Administrator public class AccountBean extends orgapachestrutsactionActionForm
We create an instance of the DebtorBean here and we used the constructor we definedfor itprivate DebtorBean debtorBean = new DebtorBean(JohnAsia(122)092-1234)
private String accountNo = 1234private String grossAmt = 10000
getters
public String getAccountNo() return accountNo
public DebtorBean getDebtorBean()
return debtorBeanpublic String getGrossAmt()
return grossAmtsetters
public void setAccountNo(String accountNo) thisaccountNo = accountNo
public void setGrossAmt(String grossAmt)
thisgrossAmt = grossAmt
3 Next wersquoll create a dummy Action class so we can create an action-mapping entry instuts-configxml that will bind the form we defined above This code does nothingbut forward the process back to the origin
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
133
Create a class named DummyAction in the package comffictraining and paste thefollowing code
import orgapachestrutsactionimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOExceptionimport javautilListimport javaio
public class DummyAction extends orgapachestrutsactionAction
public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws IOExceptionServletException
return new ActionForward(mappinggetInput())
4 Add the following entries in the struts-configxml file
Inside the ltform-beansgt tag add
ltform-bean name=acctForm type=comffictrainingAccountBeangt
Inside the ltaction-mappingsgt tag add
ltaction path=dummytype=comffictrainingDummyActionname=acctFormscope=requestinput=acctDisplayjspgtltforward name=success path=acctDisplayjspgt
ltactiongt
5 In the craft folder in WTE create a file named acctDisplayjsp and paste thefollowing code
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gt
134
lthtmlform action=dummydo gt
lttable border=1gtlttrgt lttdgtAccount No lttdgt lttdgtltbeanwrite name=acctForm property=accountNo gtlttdgt lttrgtlttrgt lttdgtGross Amtlttdgt lttdgtltbeanwrite name=acctForm property=grossAmt gtlttdgtlttrgtlttablegt
lttable border=1gtltbr gtltbgtDebtorsltbgtlttrgtltthgtNameltthgtltthgtAddressltthgtltthgtPhone Noltthgtlttrgt
ltmdashWhat you need to note here is that the debtorBean property (returned by thegetDebtorBean() method) returns an object of type DebtorBean In the jsp we canaccess the instance variables of the object using dot () notation That isbeanNameproperty --gt
lttrgt lttdgt lthtmltext property=debtorBeanname gt lttdgt lttdgt ltbeanwrite name=acctForm property=debtorBeanaddress gt lttdgt lttdgt ltbeanwrite name=acctForm property=debtorBeanphone gt lttdgtlttrgt
lttablegt
lthtmlsubmit gtlthtmlformgt
6 Deploy the code and type httplocalhost8080craftacctDisplayjsp in the commandline
7 The result should look something like
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
135
CODING PART 2
Moving on we can further simplify our jsprsquos code by using the nested tags package
To do this
1 Add the taglib directive for the nested tags on top of the acctDisplayjsp file asfollows
lttaglib uri=WEB-INFstruts-nestedtld prefix=nested gt
2 Make the following changes to the jsp
Remove the following lines
lttrgt lttdgt lthtmltext property=debtorBeanname gt lttdgt lttdgt ltbeanwrite name=acctForm property=debtorBeanaddress gt lttdgt lttdgt ltbeanwrite name=acctForm property=debtorBeanphone gt lttdgtlttrgt
Replace them with
ltnestednest property=debtorBean gtlttrgtlttdgtltnestedtext property=name gtlttdgt
136
lttdgtltnestedwrite property=address gtlttdgtlttdgtltnestedwrite property=phone gtlttdgtlttrgt
ltnestednestgt
Complete code
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gtlttaglib uri=WEB-INFstruts-nestedtld prefix=nested gt
lthtmlform action=dummydo gt
lttable border=1gtlttrgt lttdgtAccount No lttdgt lttdgtltbeanwrite name=acctForm property=accountNo gtlttdgt lttrgtlttrgt lttdgtGross Amtlttdgt lttdgtltbeanwrite name=acctForm property=grossAmt gtlttdgtlttrgtlttablegt
lttable border=1gtltbr gtltbgtDebtorsltbgtlttrgtltthgtNameltthgtltthgtAddressltthgtltthgtPhone Noltthgtlttrgt
ltnestednest property=debtorBean gtlttrgtlttdgtltnestedtext property=name gtlttdgtlttdgtltnestedwrite property=address gtlttdgtlttdgtltnestedwrite property=phone gtlttdgtlttrgt
ltnestednestgt
lttablegt
lthtmlsubmit gtlthtmlformgt
You can just see how much cleaner the code is The ltnestednestgt tag declares a parentproperty and the tags underneath it are kept aware of the parent so that we donrsquot have touse the dot notation to access the DebtorBeanrsquos instance variables We also donrsquot haveto specify the name attribute for the ltnestedwritegt tag
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
137
Since we only made changes to the jsp just re-invoke the URL
httplocalhost8080craftacctDisplayjsp
and the webserver will re-compile the jsp and re-render the output The result should bethe same as the previous exercise
CODING PART 3
Still moving on we then remember (by reading the requirements) that there can be morethan one debtor associated with an account
1 We therefore have to change our AccountBean to instead of holding just oneinstance of the DebtorBean hold a collection of DebtorBeans
Make the following changes to the AccountBean class
Remove the line
private DebtorBean debtorBean = new DebtorBean(JohnAsia(122)092-1234)
Replace it with an ArrayList called debtorListprivate ArrayList debtorList
Create a constructor for the AccountBean that builds a list of DebtorBeans
public AccountBean () thisdebtorList = new ArrayList()thisdebtorListadd(new DebtorBean(ldquoRudolphrdquordquoNorth Polerdquordquo(415)900-2934rdquo))thisdebtorListadd(new DebtorBean(ldquoFerdinandrdquordquoHawaiirdquordquo(850)123-2333rdquo))thisdebtorListadd(new DebtorBean(ldquoGeorgerdquordquoAntarcticardquordquo(231)123-3355rdquo))
Remove the following lines of code
public DebtorBean getDebtorBean() return debtorBean
Replace them with the following
public Object [] getDebtorList() return debtorListtoArray()
Here we provided a getter for the debtorList Convert the collection to an array by callingthe debtorListrsquos toArray() method We also return an array of Objects (Object [])
138
Complete code
import javautil
public class AccountBean extends orgapachestrutsactionActionForm
private ArrayList debtorList = new ArrayList()
private String accountNo = 1234private String grossAmt = 10000
constructor here we build an array of debtorBean beans In real life we get these values from thedb using an Action classpublic AccountBean ()
debtorListadd(new DebtorBean(RudolphNorth Pole(415)900-2934))debtorListadd(new DebtorBean(FerdinandHawaii(850)123-2333))debtorListadd(new DebtorBean(GeorgeAntarctica(231)123-3355))
getters
public String getAccountNo() return accountNo
public Object[] getDebtorList()
return debtorListtoArray()public String getGrossAmt()
return grossAmtsetters
public void setAccountNo(String accountNo) thisaccountNo = accountNo
public void setGrossAmt(String grossAmt)
thisgrossAmt = grossAmt
2 Since we are now passing a collection to the jsp we will make the following changesto the acctDisplayjsp
Remove the following lines of code
ltnestednest property=debtorBean gt
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
139
ltnestednestgt
Replace them with
ltnestediterate property=debtorListgt
ltnestediterategt
Complete code
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gtlttaglib uri=WEB-INFstruts-nestedtld prefix=nested gt
lthtmlform action=dummydo gt
lttable border=1gtlttrgt lttdgtAccount No lttdgt lttdgtltbeanwrite name=acctForm property=accountNo gtlttdgt lttrgtlttrgt lttdgtGross Amtlttdgt lttdgtltbeanwrite name=acctForm property=grossAmt gtlttdgtlttrgtlttablegt
lttable border=1gtltbr gtltbgtDebtorsltbgtlttrgtltthgtNameltthgtltthgtAddressltthgtltthgtPhone Noltthgtlttrgt
ltnestediterate property=debtorListgtlttrgtlttdgtltnestedwrite property=name gtlttdgtlttdgtltnestedwrite property=address gtlttdgtlttdgtltnestedwrite property=phone gtlttdgtlttrgt
ltnestediterategt
lttablegt
lthtmlsubmit gtlthtmlformgt
140
3 Restart the servlet engine and re-invoke the URLhttplocalhost8080craftacctDisplayjsp and you should see the following screendisplay
In conclusion it will not take a lot of code to say break down the phone number into aseparate bean if we have more than one phone number per debtor We just repeat thesteps in CODING PART 3 to nest a PhoneBean bean inside the DebtorBean
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
141
Lesson 19 ndash Creating reusable screen components BasicsAt this point we will cover the different ways of creating a screen template in Struts Thediagram below is a typical layout for a website
The Body and Menu contents may change from page to page so we need tocomponentize these to make them dynamic and to make the static portions the screenreusable
Outside of Struts we can accomplish this using any of the following
HTML frames (frameset) Include directives (lta include file=rdquordquo gt) JSP includes (jspinclude)
Within Struts we can either use the htmltemplate tag or use the Tiles extension Wersquollprovide examples on how to do both
Coding (Part 1)For both examples wersquoll use the examples in the previous lessons so make sure they areworking before you proceed with the rest of the lesson The flow of the application will beas follows
Loginjsp Welcomejsp = InputContentjsp
142
||=====acctDisplayjsp
We will apply the template described above in the jsprsquos except Loginjsp so we canplace render the menu that will contain the links to the two jsps (InputContentjsp andacctDisplayjsp)
HTML Template Tag
1 We will first need to create a layout to hold the components together To do this
Create a file named templatejsp then place the following codes in it
Add the declaration for the template tag
lt taglib uri=WEB-INFstruts-templatetld prefix=template gt
ltHTMLgtltHEADgtltTITLEgtFiremans Fund Insurance CRAFTltTITLEgtltHEADgt
ltBODYgt
lttable width=100 border=0gt lttrgt lttd bgcolor=graygtltdiv align=centergt
lth1gtMy Applicationlth1gtltdivgt
lttdgt lttrgtlttablegt
lttable width=100 height=75 border=0gt lttrgt lttd width=10 align=right valign=top bgcolor=ABABABgt
This tag will retrieve the menu
lttemplateget name=menu flush=truegt
lttdgt lttd width=90 valign=center align=centergtThis tag will retrieve the body
lttemplateget name=body flush=true gt lttdgt lttrgtlttablegt
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
143
lttable width=100 border=0gt lttrgt lttdgtltdiv align=centergt
ltfont size=-1gtCopyright 2002ltfontgtltdivgt
lttdgt lttrgtlttablegt
ltBODYgtltHTMLgt
2 To create the jsp that contains menu information
Create a file named Menujsp and place the following codes in it
Declare the taglib directive for the html taglib since we will be rendering links in this jsp
lt taglib uri=WEB-INFstruts-htmltld prefix=html gt
Herersquos wersquoll create the links to the other applications we created in the previous lessons
ltbr gtlthtmllink href=rdquoInputContentjsprdquolthtmllinkgtltbr gtlthtmllink href=rdquoacctDisplayjsprdquolthtmllinkgt
3 To apply the template to Welcomejsp
Rename Welcomejsp to WelcomeContentjsp
Create a file named Welcomejsp and place the following codes
lt taglib uri=WEB-INFstruts-templatetld prefix=template gt
lttemplateinsert template=templatejspgt lttemplateput name=menu content=Menujsp gt lttemplateput name=body content=WelcomeContentjsp gtlttemplateinsertgt
4 Wersquoll then apply the template to the rest of the jsp pages
First open the struts-configxml file and change the following linesinput=InputContentjspgt
ltforward name=success path=OutputContentjspgt
144
to
input=Inputjspgtltforward name=success path=Outputjspgt
Create a file named Inputjsp and place the following codes
lt taglib uri=WEB-INFstruts-templatetld prefix=template gt
lttemplateinsert template=templatejspgt lttemplateput name=menu content=Menujsp gt lttemplateput name=body content=InputContentjsp gtlttemplateinsertgt
Create a file named Outputjsp and place the following codes
lt taglib uri=WEB-INFstruts-templatetld prefix=template gt
lttemplateinsert template=templatejspgt lttemplateput name=menu content=Menujsp gt lttemplateput name=body content=OutputContentjsp gtlttemplateinsertgt
Rename the file named acctDisplayjsp to acctDisplayContentjsp
Create a file named acctDisplayjsp and place the following codes
lt taglib uri=WEB-INFstruts-templatetld prefix=template gt
lttemplateinsert template=templatejspgt lttemplateput name=menu content=Menujsp gt lttemplateput name=body content=acctDisplayContentjsp gtlttemplateinsertgt
Deploying the code (Part 1)
1 Bring up VAJ and WTE2 Start the servlet engine3 Bring up a browser and type the following URL on the address line
httplocalhost8080craftLoginjsp
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
145
Results (Part 1)The login page should look the same as before
The Welcome page will look like the following
The skills page
146
The output for the skills page
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
147
The account display page
Coding (Part 2)Tiles
Tiles is an extension to the Struts framework that lets you create pre-defined layouts inan xml file You can then invoke any of these layouts from your jsp pages based on saythe security role of a user using bean tags
First make sure that you have tilestld in craftWEB-INF If not go back to the strutsbinary zip file and extract this file
Like the template tag we need to create a layout for the different components
1 Create a file named TilesTemplatejsp and place the following codes
lt taglib uri=WEB-INFtilestld prefix=tiles gt
ltHTMLgtltHEADgtltTITLEgtFiremans Fund Insurance CRAFTltTITLEgt
148
ltHEADgt
ltBODYgt
lttable width=100 border=0gt lttrgt lttd bgcolor=graygtltdiv align=centergt
lth1gtMy Applicationlth1gtltdivgt
lttdgt lttrgtlttablegt
lttable width=100 height=75 border=0gt lttrgt lttd width=10 align=right valign=top bgcolor=ABABABgt
lttilesinsert attribute=menu flush=truegt
lttdgt lttd width=90 valign=center align=centergt
lttilesinsert name=body flush=true gt lttdgt lttrgtlttablegt
lttable width=100 border=0gt lttrgt lttdgtltdiv align=centergt
ltfont size=-1gtCopyright 2002ltfontgtltdivgt
lttdgt lttrgtlttablegt
ltBODYgtltHTMLgt
2 Using the same components that we used in Part 1 wersquoll create Tiles-managedlayouts
Rename the following files
Original name New Name
Welcomejsp _WelcomejspInputjsp _InputjspOutputjsp _Outputjsp
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
149
acctDisplayjsp _acctDisplayjsp
3 We will recreate the jsprsquos that we renamed in the previous step but this timeusing tiles tags
Create a file named Welcomejsp and place the following codes
lt taglib uri=WEB-INFtilestld prefix=tiles gt
lttilesinsert page=rdquoTilesTemplatejsprdquo gtlttilesput name=rdquomenurdquo value=rdquoMenujsprdquo gtlttilesput name=rdquobodyrdquo value=rdquoWelcomeContentjsprdquo gt
lttilesinsertgt
Create a file named Inputjsp and place the following codes
lt taglib uri=WEB-INFtilestld prefix=tiles gt
lttilesinsert page=rdquoTilesTemplatejsprdquo gtlttilesput name=rdquomenurdquo value=rdquoMenujsprdquo gtlttilesput name=rdquobodyrdquo value=rdquoInputContentjsprdquo gt
lttilesinsertgt
Create a file named Outputjsp and place the following codes
lt taglib uri=WEB-INFtilestld prefix=tiles gt
lttilesinsert page=rdquoTilesTemplatejsprdquo gtlttilesput name=rdquomenurdquo value=rdquoMenujsprdquo gtlttilesput name=rdquobodyrdquo value=rdquoOutputContentjsprdquo gt
lttilesinsertgt
Create a file named acctDisplayjsp and place the following codes
lt taglib uri=WEB-INFtilestld prefix=tiles gt
lttilesinsert page=rdquoTilesTemplatejsprdquo gtlttilesput name=rdquomenurdquo value=rdquoMenujsprdquo gtlttilesput name=rdquobodyrdquo value=rdquoacctDisplayContentjsprdquo gt
lttilesinsertgt
Up to this point Tiles and the template tags are almost alike in every aspect The nextcoding exercise will delve more in what Tiles can provide in addition to what yoursquove justlearned
150
Deploying the code (Part 2)1 Bring up VAJ and WTE2 Start the servlet engine3 Bring up a browser and type the following URL on the address line
httplocalhost8080craftLoginjsp
Result (Part 2)The result should look the same as Part 1
Coding (Part 3)More on Tiles
We can further centralize the definition of each pagersquos layout by placing them in an xmlfile that getrsquos read by Struts at startup This way we only have one place to make thechange in case a particular layout gets reused in several jsp pages We can also define abase layout which we can extend pretty much like extending a java class We can alsopass parameters to the layout definitions to dynamically change certain parts of thelayout on a page by page basis
1 We need to let the ActionServlet know about our centralized layout definition Somake the following changes to the craftwebapp file
Comment out the following line
ltcodegtorgapachestrutsactionActionServletltcodegt
Replace it with
ltcodegtorgapachestrutstilesActionComponentServletltcodegt
Add the following lines of code right after the above
ltinit-parametergt ltnamegtdefinitions-configltnamegt ltvaluegtWEB-INFtilesDefinitionxmlltvaluegt
ltinit-parametergt
2 Create a file named tilesDefinitionxml and save it in craftWEB-INF
Add the following code
ltxml version=10 encoding=ISO-8859-1gtlt-- DTD for the Struts Application Configuration File Version 11
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
151
To support validation of your configuration file include the following DOCTYPE element at the beginning (after the xml declaration)
ltDOCTYPE struts-config PUBLIC -Apache Software FoundationDTD Tiles ConfigurationEN httpjakartaapacheorgstrutsdtdstiless-config_1_1dtdgt
--gtlt-- html definition Mappings --gtltcomponent-definitionsgt
Create a master definition that uses the TilesTemplatejsp The name is arbitrarylt-- Definition description --gtltdefinition name=welcomepage path=TilesTemplatejspgt
ltput name=menu value=Menujspgtltput name=body value=Welcomejspgt
ltdefinitiongt
Create a definitions for the rest of the jsprsquos by extending the master definition
lt-- Extended definition for account display --gtltdefinition name=acctdisplaypage extends=welcomepagegt
ltput name=body value=acctDisplayjspgtltdefinitiongt
lt-- Extended definition skills input --gtltdefinition name=skillsinputpage extends=welcomepagegt
ltput name=body value=Inputjspgtltdefinitiongt
lt-- Extended definition skills output --gtltdefinition name=skillsoutputpage extends=welcomepagegt
ltput name=body value=Outputjspgtltdefinitiongt
ltcomponent-definitionsgt
3 Open the struts-configxml file and make the following changes
Change ltforward name=success path=Welcomejspgt
To ltforward name=success path=welcomepagegt
Change input=acctDisplayjspgtltforward name=success path=acctDisplayjspgt
to input=acctdisplaypagegt
152
ltforward name=success path=acctdisplaypagegt
Change input=Inputjspgtltforward name=success path=Outputjspgt
To input=skillsinputpagegtltforward name=success path=skillsoutputpagegt
Add the following entries just before the ltmessage-resourcesgt for the validator
lt-- =============================== Controllers --gt
The request processor for Tiles that will resolve the path entries above that use dotnotation
lt-- Tiles --gtltcontroller processorClass=orgapachestrutstilesTilesRequestProcessorgt
lt-- Tiles --gt ltmessage-resources parameter=orgapachestrutsexampletilesdev1_1ApplicationResourcesnull=falsegt
Deploying the code (Part 3)1 Bring up VAJ and WTE2 Start the servlet engine3 Bring up a browser and type the following URL on the address line
httplocalhost8080craftLoginjsp
Result (Part 3)The result should look the same as Part 1
As a result of centralizing the layout definitions in an xml file we do not need to createseparate jsps for each page to pull in the template and necessary components In effectwe can get rid of the Welcomejsp acctDisplayjsp Inputjsp and Outputjsp files Ourmain focus from hereon is to build to dynamic portions of the pages namely the body andthe menu components The use of the dot notation in the action-mapping paths alsorelieves us of having to think about resource paths within the struts-configxml file
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
153
Lesson 20 ndash Creating reusable menu componentsBasicsIn this lesson wersquoll look at a contributor extension to Struts that renders menus on thebrowser using struts-compatible taglibs that read menu information from an xml file Theextension uses three different kinds of menu displayers which dictate the look and feel ofthe menu
Simple - displays all menu information with the subitems indented to illustratethe hierarchy of the selection items
DropDown ndash displays expandablecollapsible items using javascript generated by thetool
CoolMenus ndash displays dropdown menus using CoolMenus javascripts similar to theone you see in Portal
As we will see in the following exercise we can easily change the type of menu displayerin our jsps without having to make massive changes in the codes
Before we move on it is important to note that since this tool generates javascript torender the menus especially DropDown and CoolMenus these will not always work in allversions of IE and Netscape These javascripts however have been tested and proven towork in IE 55 Netscape 45 cannot render the DropDown displayer and does not renderthe CoolMenus displayer as elegantly as in IE 55 We may have better browser supportin future releases of this tool (or not)
InstallationThere are two ways of installing struts-menu
Option 1
First letrsquos do some installation and configuration
1 Download a working copy of struts-menu fromhttpwwwbasebeanscomdownloadsjspSelect the link Download source files for this web site It uses menu and tilesThe downloaded file is sitezip
Note Right now this is the only version of stuts-menu that works in VAJ 40WTE Idonrsquot have any problems using the beta release in ORION so I emailed the author to askfor some help
2 In VAJ create a project named Struts Menu and import the struts-menujar filefrom sitezip Include both the classes and resources
154
3 Extract the file struts-menutld from sitezip and place it in the craftWEB-INFfolder
4 Download the latest beta release of struts menu (11 beta2) fromhttpssourceforgenetprojectsstruts-menu as we will need some files from hereThe downloaded file is StrutsMenu-11beta2zip From this file extract the followingfiles to a local folder
ISOCodeResproperties ISOCodeRes_ruproperties TrackerResproperties TrackerRes_ruproperties
5 Go back to VAJ and in the Resources tab right click on the Struts Menu project andselect AddResources then look for the files you extracted in the previous step andadd them
6 From StrutsMenu-11beta2zip extract the following image files and place them inthe craftimages folder (create this folder if you donrsquot have it)
Darrowgif Rarrowgif
7 From StrutsMenu-11beta2zip extract the following files and place them in thecraftscripts folder (again you need to create this folder if you donrsquot have it)
coolmenu-configjs coolmenus3js
8 Open the struts-configxml and make the following changes
Add the following just before the ltplug-ingt tag
lt-- Menu --gt ltmessage-resources parameter=TrackerResgt ltmessage-resources parameter=ISOCodeRes key=ISOCodeResgt
Add the following right after the last ltmessage-resourcegt tag
lt-- Menu --gt ltplug-in className=comfgmwebmenuMenuPlugIngt ltset-property property=menuConfig value=WEB-INFmenu-configxmlgt ltplug-ingt
Notice that we assigned a file menu-configxml to the menuConfig property of the plug-in We will have to create this file where we will define our menu items Wersquoll do this in thenext step
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
155
9 In VAJ bring up WTE and click on ldquoEdit Class Pathrdquo then add the following in theldquoEnter the extra class pathrdquo portion
EAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebpshere Test Environmenthostsdefault_hostcraftscripts
Option 2
First letrsquos do some installation and configuration
1 Download the latest beta release of struts menu (11 beta2) fromhttpssourceforgenetprojectsstruts-menu The downloaded file is StrutsMenu-11beta2zip
2 In VAJ create a project named Struts Menu and import the StrutsMenu-11beta2zip Remember to include java files and resources only For resourcesinclude only the following files
ISOCodeResproperties ISOCodeRes_ruproperties TrackerResproperties TrackerRes_ruproperties
3 We then need to make some code changes to the source to make this work with ourversion of Struts So in VAJ Add the following method to the classcomfgmwebmenuMenuPlugIn
Insert the methods description here Creation date (51502 31727 PM) public void init(ApplicationConfig config) throws ServletException
Systemoutprintln(Starting struts-menu initialization) String menuConfig = configgetServlet() getServletConfig()getInitParameter(menu-config) repository = new MenuRepository() repositorysetLoadParam(menuConfig) repositorysetServlet(configgetServlet()) try repositoryload() configgetServlet()getServletContext() setAttribute(MenuRepositoryMENU_REPOSITORY_KEY repository) thisappConfig = config Systemoutprintln(struts-menu initialization successfull) catch (LoadableResourceException lre)
156
throw new ServletException( Failure initializing struts-menu + lregetMessage())
4 Extract the file struts-menutld from StrutsMenu-11beta2zip and place it in thecraftWEB-INF folder
5 From StrutsMenu-11beta2zip extract the following image files and place them inthe craftimages folder (create this folder if you donrsquot have it)
Darrowgif Rarrowgif
6 From StrutsMenu-11beta2zip extract the following files and place them in thecraftscripts folder (again you need to create this folder if you donrsquot have it)
coolmenu-configjs coolmenus3js
7 Open the struts-configxml and make the following changes
Add the following just before the ltplug-ingt tag
lt-- Menu --gt ltmessage-resources parameter=TrackerResgt ltmessage-resources parameter=ISOCodeRes key=ISOCodeResgt
Add the following right after the last ltmessage-resourcegt tag
lt-- Menu --gt ltplug-in className=comfgmwebmenuMenuPlugIngt ltset-property property=menuConfig value=WEB-INFmenu-configxmlgt ltplug-ingt
Notice that we assigned a file menu-configxml to the menuConfig property of the plug-in We will have to create this file where we will define our menu items Wersquoll do this in thenext step
8 In VAJ bring up WTE and click on ldquoEdit Class Pathrdquo then add the following in theldquoEnter the extra class pathrdquo portion
EAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebpshere Test Environmenthostsdefault_hostcraftscripts
Coding
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
157
1 As discussed in the previous section create a file named menu-configxml and saveit in the craftWEB-INF folder
Wersquoll build a menu based on the menu selections that we created in the previouslesson Here are the codes to place in the menu-configxml with some explanation
ltxml version=10gt
Here we declare the different types of displayers that we can use to render our menultMenuConfiggt ltDisplayersgt ltDisplayer name=DropDown type=comfgmwebmenudisplayerDropDownMenuDisplayergt ltDisplayer name=Simple type=comfgmwebmenudisplayerSimpleMenuDisplayergt ltDisplayer name=CoolMenu type=comfgmwebmenudisplayerCoolMenuDisplayergt ltDisplayersgt lt-- ==================== Case View Menus=========================== --gtltMenusgt
This is where we start defining our menu items
We create a holder for our menu items and we named it MainMenu
ltMenu name=MainMenu title=MainMenu gt
The items are defined here and are assigned namestitles and the path of the jsp toinvoke for each item
ltItem name=SkillInv title=Skills Inventory location=InputjspgtltItem name=DispAcct title=Display Account location=acctDisplayjspgt
Note If you need to place subitems under SkillInv for example this is how you do it
ltItem name=SkillInv title=Skills Inventorygt ltItem name=SkillInv1 title=Skills Inventory 1gtlocation=InputjspgtltItem name=SkillInv2 title=Skills Inventory 2gtlocation=jspgtltItemgt
ltMenugt
ltMenusgtltMenuConfiggt
Complete code (menu-configxml)
ltxml version=10gt
158
ltMenuConfiggt ltDisplayersgt ltDisplayer name=DropDown type=comfgmwebmenudisplayerDropDownMenuDisplayergt ltDisplayer name=Simple type=comfgmwebmenudisplayerSimpleMenuDisplayergt ltDisplayer name=CoolMenu type=comfgmwebmenudisplayerCoolMenuDisplayergt ltDisplayersgt lt-- ==================== Case View Menus=========================== --gtltMenusgt
ltMenu name=MainMenu title=MainMenu gt ltItem name=SkillInv title=Skills Inventory location=Inputjspgt
ltItem name=DispAcct title=Display Account location=acctDisplayjspgtltMenugt
ltMenusgtltMenuConfiggt
2 Open the file Menujsp and make the following changes
Add the taglib directive for struts-menu
lt taglib uri=WEB-INFstruts-menutld prefix=menugt
Remove the following lines of code
ltbr gtlthtmllink href=InputjspgtSkillslthtmllinkgtltbr gtlthtmllink href=acctDisplayjspgtAccount Infolthtmllinkgt
Replace them with the following (remember that these should be inside the ltbodygt tag)
ltmenuuseMenuDisplayer name=Simple gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt
3 The previous step used the Simple menu displayer To try the DropDown displayeradd the following codes
To render the menu using the Dropdown displayer
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
159
ltmenuuseMenuDisplayer name=DropDown gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt
4 To try the CoolMenus displayer open the file TilesTemplatejsp and make thefollowing changes
Add the following code right after the ltbodygt tag
ltscript language=JavaScript12 src=scriptscoolmenus3jsgtltscriptgtltscript src=scriptscoolmenu-configjsgtltscriptgtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergt
5 To complete the setup for the CoolMenus displayer letrsquos do some configuration withthe javascript that comes with the displayer
Open the file coolmenu-configjs in craftscripts and make the following changes orjust see to it that the following variables have the same values as below Explanations forthese values are provided in the file itself right beside each field I didnrsquot include themhere as there are just too many of them
Background bar propertiesoCMenuusebar=1 oCMenubarcolor=lightblue oCMenubarwidth=menu oCMenubarheight=menu oCMenubarx=menu oCMenubary=menu oCMenubarinheritborder=0
Placement propertiesoCMenurows=0 oCMenufromleft=20 oCMenufromtop=300 oCMenupxbetween=0
oCMenumenuplacement=center
160
oCMenulevel[0]filter=progidDXImageTransformMicrosoftFade(duration=05)VALUE 0 || filter specs
oCMenulevel[0]align=right Value top || bottom || left || right
EXAMPLE SUB LEVEL[1] PROPERTIES - You have to spesify the properties you wantdifferent from LEVEL[0] - If you want all items to look the same just remove thisoCMenulevel[1]=new Array() Add this for each new level (adding one to the number)oCMenulevel[1]width=oCMenulevel[0]width-2oCMenulevel[1]height=22oCMenulevel[1]bgcoloroff=FF9900oCMenulevel[1]bgcoloron=006699oCMenulevel[1]style=padding2px font-familytahoma arialhelvetica font-size11pxfont-weightboldoCMenulevel[1]align=right oCMenulevel[1]offsetX=0oCMenulevel[1]offsetY=0oCMenulevel[1]border=1 oCMenulevel[1]bordercolor=006699
With all three displayers placed in your jsp you can see how each displayer differs fromone another even though they are displaying the same layout that we defined in menu-configxml So letrsquos deploy the application to see how it looks
Deploying the code
1 Bring up VAJ and WTE2 Bring up the ldquoEdit Class Pathrdquo window and select all projects (Remember that we
created a new project Struts Menu so we have to make sure itrsquos in the classpath ofour servlet engine)
4 Start the servlet engine5 Bring up a browser (IE 55 not NS 45) and type the following URL on the address
line
httplocalhost8080craftLoginjsp
Note You can try this in NS 45 to see whatrsquos working and whatrsquos not working
ResultThe output should look like the following after logging in with valid values
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
161
If you click on the MainMenu dropdown (the one in light gray) and place your mousepointer over the CoolMenu MainMenu you should see the following
162
These menu renditions will be displayed in the rest of your jsprsquos since wersquore using thesame jsp (Menujsp) to render our menu items
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
163
Lesson 21 ndash Connection PoolingBasicsUp to Lesson 10 we used basic java code to create a connection to the database Eachrequest that goes to the servlet will cause it to make the same request over and overagain which in real-worldhigh-traffic situations will tend to slow down your applicationThe solution here is to provide a means of creating and maintaining a pool of connectionsto the db so that when an object requires a db connection all it has to do is go the pooland retrieve an existing connection The object then has to return that connection to thepool once it is done with it In this lesson we will work with a java extensionjavaxsqlDataSource that does what we just described The implementation of theDataSource will vary between web servers and the database in our case itrsquos WebSphereand DB2 respectively Wersquoll go through the process of creating and maintaining aconnection pool the WebSphere way and how to create Struts-based code that utilizethe connection pool using best practices on web application development
Before we move on you need to keep in mind that in FFIC the responsibility for creatingDataSources lies with the AIX support group of CGI Once the database is created in theAIX environment CGI will create the DataSource definition and let us know theDataSource name
CodingHere wersquoll define a DataSource in VAJWTE that references the IOU db
1 Bring up the WebSphere Test Environment in VAJ and select Persistent NameServer
2 Accept the defaults and click on Start Name Server
164
3 Select DataSource Configuration then click Add4 Enter the DataSource information as in the screen below then click OK
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
165
Most of the fields above are self-explanatory but here are explanations on some of them
DataSource ndash an arbitrary name to identify your datasourceDatabase driver ndash we use the DB2 driver here same as in earlier examples(JDBCSample)Database URL ndash url for the DB2 database same as in JDBCSample
Minimum connections ndash minimum connections created when the datasource is createdMaximum connections ndash maximum connections to create take note that if objects donrsquotreturn connections to this pool then the application will cease working since no moreconnections will be created after this number is reached
5 In the Training project copy the JDBCSample class in comffictraining toJDBCDataSource
6 Make the following changes to JDBCDataSource
Add the following import statement
import javaxnaming
Remove the following lines of code
trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)
166
String url = ldquojdbcdb2IOUrdquoSystemoutprintln(ldquoconnectingtordquo + url)conn = DriverManagergetConnection(urluserpassword)Systemoutprintln(ldquoconnectedrdquo)
trycatch(ClassNotFoundException ex)
Systemoutprintln(ldquoCouldnrsquot load jdbc driverrdquo)Systemoutprintln(ex)
catch(SQLException ex)Systemoutprintln(ldquoDatabase Problemrdquo)Systemoutprintln(ex)
catch(Exception ex)Systemoutprintln(ldquoSome other problemrdquo)Systemoutprintln(ex)
Replace them with the following
try
javautilHashtable env= new javautilHashtable()envput(InitialContextINITIAL_CONTEXT_FACTORYcomibmejsnsjndiCNInitialContextFactory)
envput(InitialContextPROVIDER_URL iiop)
envput(InitialContextPROVIDER_URL iiop) Create the Initial Naming Contextctx = new InitialContext(env) Perform a naming service lookup to get a DataSource objectds = (javaxsqlDataSource) ctxlookup(jdbcIOUDataSource)
catch(Throwable e) Systemerrprint(Error )Systemerrprintln(egetMessage())
The above code performs a JNDI lookup to the datasource we defined in the previousstep This code is pretty much boiler plate and it works in real-world application prettywell unlike our previous version
Next add the following line after the second try statement
con = dsgetConnection(iccw0t00iccw0t00)
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
167
Since the IOU database is not configured to accept anonymous connections we need toprovide the useridpassword like in the above code
Thatrsquos all we need to do to start using the datasource we created
Before we move on take note of the following items
You need to have the persistent naming server up before you start running your javacode that uses the datasource
The command conclose() (where conn is an instance of the Connection object)takes on a new meaning when using a datasource In our early examples conclose()closes the connections so we have to create another connection to the database forevery request In a datasource conclose() returns the connection back to the pool tobe used later by another requesting object It is therefore important to make sure thatour code always returns the connection after using it Else if all connections areexhausted the application will stop workingA best practice for making sure thatconnections are returned to the pool is to place the conclose() in a finally blockwhich is always executed no matter what happens
We can then create a finally block like the one below
finally try
if (conn = null) conclose()
catch (SQLException sqle)
sqleprintStackTrace()
Place this code right after the catch block Also remember to remove the originalconclose() code
Complete code (comffictrainingJDBCSample)
Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcappimport javautil
import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource
168
import javaxnaming
public class JDBCSample
JDBCSample constructor comment public JDBCSample()
super()
public static void main(String args[]) String query = ldquoSELECT FROM IOUDIVISIONrdquoConnection conn = nullStatement stmt = nullString user = ldquoiccw0t00rdquoString password = ldquoiccw0t00rdquoString driver = ldquoCOMibmdb2jdbcappDB2Driverrdquo
try
javautilHashtable env= new javautilHashtable()envput(InitialContextINITIAL_CONTEXT_FACTORYcomibmejsnsjndiCNInitialContextFactory)envput(InitialContextPROVIDER_URL iiop) Create the Initial Naming Contextctx = new InitialContext(env) Perform a naming service lookup to get a DataSource objectds = (javaxsqlDataSource) ctxlookup(jdbcIOUDataSource)
catch(Throwable e) Systemerrprint(Error )Systemerrprintln(egetMessage())
try con = dsgetConnection(iccw0t00iccw0t00)stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)
Systemoutprintln(ldquoDivision ldquo + ldquoCoderdquo + ldquo ldquo + ldquoDescriptionrdquo) while (rsnext())
String s = rsgetString(1)String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
169
stmtclose()conclose()
catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())
finally
try if (conn = null)
conclose()
catch (SQLException sqle) sqleprintStackTrace()
Deploying the codeSince this is a stand-alone java program (because it has a main() method) we can runthis without using the servlet engine
1 Right click on the JDBCDataSource class and select Run
2 Select Check Class Path then click on Edit under Project Path
3 A list of all your projects will be displayed Click Select all then click OK
4 Right click on the JDBCDataSource class and select Run again
5 This time select Run main
6 We inserted several Systemoutprintln() in the code so you should see themdisplayed in the console which should automatically popup when you run your code
ResultThe output should look similar to the following
Division Code Description1 CID Involuntary 2 CID Voluntary 3 PID 4 CID Specialty 10 National Accounts 11 Jefferson Insurance
170
13 Allianz Life 14 Escheated Funds 15 Major Litigation 19 FF McGee WINS Claims 20 Atlas Claims 21 Boston PID Claims 22 Allianz Clms-Burbank 23 Allianz Prem-Burbank 30 JUAJUW Premium 31 ISI Involuntary 40 Employee Accounts 50 Surety Claims 51 Marine Claims 60 Third Party Deductibles 61 DBS 62 Entertainment Deduct 64 Lancer Deductibles 70 Parkway Premium 71 Parkway Claims 80 Interstate Premium 81 Interstate Claims 82 Interstate Title EampO 85 FF AgriBusiness-DCC 86 FF AgriBusiness-CGI 90 Reinsurance 91 Special Projects
With this example a datasource will be created everytime you run the code and this initself does not show a significant improvement over what we did in earlier lessons Soyou might ask ldquoHow can you make it so that the connection pool exists as one instancewithin our application so that our objects can just invoke this single instance which servesup the connectionsrdquo The next lesson will do just that
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
171
Lesson 22 ndash Creating a singleton to maintain theconnection poolBasicsAn object that implements the singleton patternThatrsquos what wersquoll create in this lesson
So whatrsquos a singleton anyway Simply put a singleton ensures that there is only oneinstance of a particular object This prevents different objects from instantiating theobject that creates the connection pool everytime a connection is needed
In this lesson we will create a singleton class that creates a datasource and maintainsthe connection to the database To initialize this class we will create a servlet thatcreates the datasource and passes this datasource to the singleton
Coding1 Wersquoll first create the singleton class In VAJ create a class named ConnectionPool
in the comffictraining package and paste the following code
Import the necessary packages
import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource
public class ConnectionPool
Create the variable for the datasourceprivate javaxsqlDataSource ds
Create an object that references itself Declaring it static makes it a singletonprivate static ConnectionPool thisPool
Create a private constructor that takes a datasource as an argumentprivate ConnectionPool(DataSource ds)
thisds = ds
Create a public method to be used by accessing objects to retrieve a connection from thepoolpublic Connection getConnection() throws SQLException
return dsgetConnection(iccw0t00iccw0t00)
172
Create a public method to be used by accessing objects to get hold of the singletoninstancepublic static ConnectionPool getInstance()
if (thisPool == null) throw new IllegalStateException( ConnectionPool is not initialized )return thisPool
Create a public method to be used by accessing objects to initialize the singleton
public static void init(DataSource ds) thisPool = new ConnectionPool(ds)
Complete code (comffictrainingConnectionPool)
import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource
Insert the types description here Creation date (11802 112731 AM) author Administrator public class ConnectionPool
private javaxsqlDataSource dsprivate static ConnectionPool thisPool
Insert the methods description here Creation date (11802 113330 AM) private ConnectionPool(DataSource ds)
thisds = ds
Insert the methods description here Creation date (11802 113935 AM) return javasqlConnection public Connection getConnection() throws SQLException
return dsgetConnection(iccw0t00iccw0t00) Insert the methods description here Creation date (11802 113724 AM) return comfficcraftdbutilConnectionPool
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
173
public static ConnectionPool getInstance() if (thisPool == null) throw new IllegalStateException( Pool not initialized )return thisPool
Insert the methods description here Creation date (11802 113545 AM) public static void init(DataSource ds)
thisPool = new ConnectionPool(ds)
2 Since we want the singleton class initialized only once within the application wersquollcreate a servlet that on startup will do just that
In the package comffictraining create a class named DBInitServlet and place thefollowing codes
Import the necessary classes
import javaxservlethttpHttpServletimport javaxservletServletConfigimport javaxservletServletException
import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource
import javaxnaming
Define the DBInitServlet class be extending HttpServlet
Insert the types description here Creation date (11802 114422 AM) author Administrator public class DBInitServlet extends javaxservlethttpHttpServlet
Leave the doGet() method empty
Process incoming HTTP GET requests
174
param request Object that encapsulates the request to the servlet param response Object that encapsulates the response from the servlet public void doGet(javaxservlethttpHttpServletRequest requestjavaxservlethttpHttpServletResponse response) throws javaxservletServletExceptionjavaioIOException
Leave the doPost() method empty Process incoming HTTP POST requests param request Object that encapsulates the request to the servlet param response Object that encapsulates the response from the servlet public void doPost(javaxservlethttpHttpServletRequest requestjavaxservlethttpHttpServletResponse response) throws javaxservletServletExceptionjavaioIOException
All we need is to implement the servletrsquos init() method to initialize the singleton class
Initializes the servlet public void init(ServletConfig config) throws ServletException
superinit(config)
The following lines may look familiar to you as wersquove used them in our previous lesson
InitialContext ctx = nullDataSource ds = null
try
javautilHashtable env= new javautilHashtable()envput(InitialContextINITIAL_CONTEXT_FACTORYcomibmejsnsjndiCNInitialContextFactory)envput(InitialContextPROVIDER_URL iiopwasdeva9001)
Create the Initial Naming Contextctx = new InitialContext(env) Perform a naming service lookup to get a DataSource objectds = (javaxsqlDataSource) ctxlookup(jdbcCRAFTDataSource)
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
175
Here we invoke the singletonrsquos init() method and passed the DataSource that we justcreated as an argument
ConnectionPoolinit(ds)
catch (Throwable e) eprintStackTrace()throw new ServletException(Unable to open datasource)
Complete code (comffictrainingDBInitServlet)
import javaxservlethttpHttpServletimport javaxservletServletConfigimport javaxservletServletException
import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource
import javaxnaming
Insert the types description here Creation date (11802 114422 AM) author Administrator public class DBInitServlet extends javaxservlethttpHttpServlet Process incoming HTTP GET requests param request Object that encapsulates the request to the servlet param response Object that encapsulates the response from the servlet public void doGet(javaxservlethttpHttpServletRequest requestjavaxservlethttpHttpServletResponse response) throws javaxservletServletExceptionjavaioIOException
Process incoming HTTP POST requests
176
param request Object that encapsulates the request to the servlet param response Object that encapsulates the response from the servlet public void doPost(javaxservlethttpHttpServletRequest requestjavaxservlethttpHttpServletResponse response) throws javaxservletServletExceptionjavaioIOException
Initializes the servlet public void init(ServletConfig config) throws ServletException
insert code to initialize the servlet heresuperinit(config)InitialContext ctx = nullDataSource ds = null
try
javautilHashtable env= new javautilHashtable()envput(InitialContextINITIAL_CONTEXT_FACTORYcomibmejsnsjndiCNInitialContextFactory)envput(InitialContextPROVIDER_URL iiopwasdeva9001)
Create the Initial Naming Contextctx = new InitialContext(env) Perform a naming service lookup to get a DataSource objectds = (javaxsqlDataSource) ctxlookup(jdbcCRAFTDataSource)
ConnectionPoolinit(ds)
catch (Throwable e) eprintStackTrace()throw new ServletException(Unable to open datasource)
3 So now we have the necessary classes to create and maintain the connection poolWersquoll then add the following entries to the craftwebapp file to load the servlet onapplication startup
ltservletgt ltnamegtDBInitltnamegt ltdescriptiongtFile serving servletltdescriptiongt
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
177
ltcodegtcomffictrainingDBInitServletltcodegt ltautostartgttrueltautostartgtltservletgt
4 Now since the singleton class is created from within a servlet it therefore follows thatthat instance is visible only to classes running within the servlet engine We cantherefore create an Action class in Struts that uses this connection pool to access thedb and render the result on the browser
In VAJ in the package comffictraining create an Action class namedViewDivisionAction and place the following code
Import the necessary packages
import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOException
import javasql
import javautil
Define ViewDivisionAction by extending Action
Insert the types description here Creation date (12402 23818 PM) author Administrator public class ViewDivisionAction extends orgapachestrutsactionAction
Here we create an instance variable for the connection pool
private ConnectionPool pool ViewClaimAction constructor comment
178
We define a constructor that gets hold of the singleton instance
public ViewDivisionAction() pool = ConnectionPoolgetInstance()
We then implement the execute() method
Insert the methods description here Creation date (12402 24105 PM) public ActionForward execute(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response)throws IOException ServletException
We define variables for the connection the query an arraylist to hold the resultset andthe ActionErrors object
Connection con = nullString query = SELECT FROM IOUDIVISIONArrayList divList = new ArrayList()ActionErrors errors = new ActionErrors()
try We get hold of a connection and then use that connection object to create a statement
con = poolgetConnection()
Statement stmt = concreateStatement()
We then run the statement and loop through the resultsetResultSet rs = stmtexecuteQuery(query)
While looping we create a new instance of DivisionBean for each retrieved row and weadd that instance to the arraylist
while (rsnext()) DivisionBean divisionBean = new DivisionBean() divisionBeansetDivNo(rsgetString(1)) divisionBeansetDivDesc(rsgetString(2))
divListadd(divisionBean)
stmtclose()
After exhausting the rows we associate the arraylist with the request object that will beforwarded to a jsp page
requestsetAttribute(divListdivList)
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
179
return mappingfindForward(success)
catch (SQLException e) eprintStackTrace()ActionError error = new ActionError(errorunexpected)errorsadd(ActionErrorsGLOBAL_ERROR error)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
Remember to add a finally block where we see to it that we return the connection to thepool by invoking a conclose()
finally try
if (con = null)conclose()
catch (SQLException e) throw new RuntimeException(errorunexpected)
saveErrors(request errors)return new ActionForward(mappinggetInput())
Complete code (comffictrainingViewDivisionAction)
import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOException
180
import javasql
import javautil
import comffictrainingConnectionPoolimport comffictrainingDivisionBean
Insert the types description here Creation date (12402 23818 PM) author Administrator public class ViewDivisionAction extends orgapachestrutsactionAction
private ConnectionPool pool ViewClaimAction constructor comment public ViewDivisionAction()
pool = ConnectionPoolgetInstance() Insert the methods description here Creation date (12402 24105 PM) public ActionForward execute(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response)throws IOException ServletException
Connection con = nullString query = SELECT FROM IOUDIVISIONArrayList divList = new ArrayList()ActionErrors errors = new ActionErrors()
try
con = poolgetConnection()
Statement stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)
while (rsnext()) DivisionBean divisionBean = new DivisionBean() divisionBeansetDivNo(rsgetString(1)) divisionBeansetDivDesc(rsgetString(2))
divListadd(divisionBean)
stmtclose()
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
181
requestsetAttribute(divListdivList)
return mappingfindForward(success)
catch (SQLException e) eprintStackTrace()ActionError error = new ActionError(errorunexpected)errorsadd(ActionErrorsGLOBAL_ERROR error)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
finally try
if (con = null)conclose()
catch (SQLException e) throw new RuntimeException(errorunexpected)
saveErrors(request errors)return new ActionForward(mappinggetInput())
5 The next step is to create an entry in the struts-configxml for the action class thatwe just created Open the struts-configxml and place the following code within theltaction-mappingsgt tag
We assign a name to the action class that we just createdltaction path=displayDiv
type=comffictrainingViewDivisionActionscope=request
If the action fails we want the user to be navigated back to the login pageinput=loginjspgt
We will build a new jsp to display the results and here we assign a tiles page nameltforward name=success path=divdisplaypage gt
ltactiongt
Herersquos the complete entry
ltaction path=displayDivtype=comffictrainingViewDivisionActionscope=requestinput=divdisplaypagegt
182
ltforward name=success path=divdisplaypage gtltactiongt
6 The next step is to create the jsp that will display the result (take note that this is theldquosuccessrdquo path in the action class config) Create a file nameddivDisplayContentjsp and save it in the craft folder in WTE Place the followingcodes
Declare the taglibs to be used
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gt
Create a table to hold the result
lttable border=1gtltbr gtltbgtDivision ListltbgtlttrgtltthgtCodeltthgtltthgtDescriptionltthgtlttrgt
Here we use the ltlogiciterategt tag to loop through the arraylist and then theltbeanwritegt tag to render the value from the beans
ltlogiciterate name=divList id=div scope=request type=comffictrainingDivisionBeangt
lttrgtlttdgtltbeanwrite name=div property=divNo gtlttdgtlttdgtltbeanwrite name=div property=divDesc gtlttdgtlttrgt
ltlogiciterategt
lttablegt
Complete code (divDisplayContentjsp)
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gt
lttable border=1gtltbr gtltbgtDivision ListltbgtlttrgtltthgtCodeltthgtltthgtDescriptionltthgtlttrgtltlogiciterate name=divList
id=div scope=request type=comffictrainingDivisionBeangt
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
183
lttrgtlttdgtltbeanwrite name=div property=divNo gtlttdgtlttdgtltbeanwrite name=div property=divDesc gtlttdgtlttrgt
ltlogiciterategt
lttablegt
7 We then go into the tiles configuration file to define our layout Open thetilesDefinitionxml file in craftWEB-INF and add the following entries
lt-- Extended definition for account display --gtltdefinition name=divdisplaypage extends=welcomepagegt
ltput name=body content=divDisplayContentjspgtltdefinitiongt
The above should be pretty much self-explanatory
8 We will also need to add an item in the menu to invoke the action class from a linkinstead of typing in a url Open the menu-configxml file and add the following entry(bold)
ltMenu name=MainMenu title=MainMenu gt ltItem name=SkillInv title=Skills Inventory location=Inputjspgt ltItem name=DispAcct title=Display Account location=acctDisplayjspgt ltItem name=DispDiv title=Display Division location=displayDivdogt
ltMenugt
Thatrsquos all there is to it We can then deploy the code and check the result
Deploying the code1 Bring up WTE in VAJ and start the servlet engine2 Start the Persistent Name Server3 Bring up IE 55 (forget NS 45 for now) and type the following url in the address line
httplocalhost8080craftLoginjsp
4 Enter a valid email address and a password then select the link Display Divisionfrom the menu in the welcome page
ResultYou should see the following
Login page
184
Welcome page showing new item in the menu
Clicking on Display Division will display the following page
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
185
In this lesson we delegated the task of accessing the db creating the collection andreturning the result entirely to the Action class In the next lesson we will learn how todecouple the data access task from the Action class so that the logic can be reused byother Action classes or beans
186
Lesson 23 ndash Data Access ObjectsBasicsIn the previous lesson we successfully created a Struts-based process that retrievesdata from a db using a connection pool We pretty much concentrated on how to createthe code that uses the connection pool and makes the call to the db without so much asconsidering the proper way of designing the process Wersquoll take this exercise a stepfurther by breaking down the tasks of the action class and delegating the db accessportion to another class that does nothing but retrieve the data from the db Afundamental principle in software design is to provide for high cohesion and less couplingamongst the classes that we create High cohesion is all about granting a singleresponsibility to a particular class to provided a well-bounded behaviour Low couplingon the other hand is all about defining our classes so that they communicate to as fewclasses as possible while achieving the desired result With both high cohesion and lowcoupling in place it makes our changes localised and our codes easier to decipher
In our example the action class (ViewDivisionAction) is evidently doing more than onething a) receives the request and performs the database access b) create the collectionfrom the resultset and c) forward the collection back to the ActionServlet for properdisposition (in our case forward to a display jsp)
Our first step to breaking down the responsbility of the action class is to create anotherclass that performs the database stuff and the creation of the collection The term usedfor such a class is Data Access Object (DAO) With this approach the action class will nolonger have any knowledge as to how to retrieve the data from the db and how to createthe collection from the resultset All it has to do is to instantiate that DAO call itrsquos methodand receive the collection that is returned to it It can then associate that collection withthe request object as it did in the previous lesson With this design we can change thesource of the data (DB2 to some other RDBMS vector text EJB) without having to makemassive changes in the action class We can also reuse the DAO in another action classor a plain javabean that requires access to the same table
Obviously the action class still has more than one responsibility which need to be brokendown some more Wersquoll cover that in the next lesson For now letrsquos move on and buildour first DAO
Coding1 In VAJ in the package comffictraining create a class named DivisionDAO and
place the following code
Import the necessary packages
import javasqlConnectionimport javasqlResultSetimport javasqlSQLException
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
187
import javasql
import javautil
Define the class and create a variable for the connection object
Insert the types description here Creation date (11802 13224 PM) author Administrator public class DivisionDAO
private javasqlConnection con
Create a constructor that has a connection object as an argument
Insert the methods description here Creation date (11802 13834 PM) param con comibmrmiiiopConnection public DivisionDAO(Connection con)
thiscon = con
Create a findAll() method that returns a collection since we are displaying all entries inthe Division table
Insert the methods description here Creation date (11802 23342 PM) public Collection findAll()
The following code may look familiar to you as we just copied it from the action class andmade some enhancements such as checking if the connection still exists before runningthe query
ResultSet rs = nullArrayList list = new ArrayList()
String sql = SELECT FROM IOUDIVISION
try
if (conisClosed()) throw new IllegalStateException(errorunexpected)
188
Statement st = concreateStatement()rs = stexecuteQuery(sql)
while(rsnext()) DivisionBean div = new DivisionBean()divsetDivNo(rsgetString(1))divsetDivDesc(rsgetString(2))
listadd(div)
return list
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
finally try
if (rs = null)rsclose()
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
Complete code (comffictrainingDivisionDAO)
import javasqlConnectionimport javasqlResultSetimport javasqlSQLExceptionimport javasql
import javautil
Insert the types description here Creation date (11802 13224 PM) author Administrator public class DivisionDAO
private javasqlConnection con
Insert the methods description here Creation date (11802 13834 PM)
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
189
param con comibmrmiiiopConnection public DivisionDAO(Connection con)
thiscon = con
Insert the methods description here Creation date (11802 23342 PM) public Collection findAll()
ResultSet rs = nullArrayList list = new ArrayList()
String sql = SELECT FROM IOUDIVISION
try
if (conisClosed()) throw new IllegalStateException(errorunexpected)
Statement st = concreateStatement()rs = stexecuteQuery(sql)
while(rsnext()) DivisionBean div = new DivisionBean()divsetDivNo(rsgetString(1))divsetDivDesc(rsgetString(2))
listadd(div)
return list
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
finally try
if (rs = null)rsclose()
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
190
2 We then need to revise the action class to take away the code that deals with the dband replace them with code that uses the DAO Open the ViewDivisionAction classin the package comffictraining and make the following changes
Remove the following lines of code
String query = SELECT FROM IOUDIVISIONArrayList divList = new ArrayList()
Statement stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)
while (rsnext()) DivisionBean divisionBean = new DivisionBean() divisionBeansetDivNo(rsgetString(1)) divisionBeansetDivDesc(rsgetString(2))
divListadd(divisionBean)
stmtclose()
After the statement con = poolgetConnection() insert the following lines of code
DivisionDAO divisionDAO = new DivisionDAO(con)Collection divList = divisionDAOfindAll()
The above code instantiates a DAO object passes a connection object to itrsquos constructorand then invokes itrsquos findAll() method to retrieve a collection
Complete code (comffictrainingViewDivisionAction)
import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
191
import javaioIOException
import javasql
import javautil
import comfficfincraftdbutilConnectionPoolimport comfficnew_to_javaDivisionBean
Insert the types description here Creation date (12402 23818 PM) author Administrator public class ViewDivisionAction extends orgapachestrutsactionAction
private ConnectionPool pool
ViewClaimAction constructor comment public ViewDivisionAction() pool = ConnectionPoolgetInstance() Insert the methods description here Creation date (12402 24105 PM) public ActionForward perform(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response) throws IOException ServletException
Connection con = null ActionErrors errors = new ActionErrors()
try con = poolgetConnection()
DivisionDAO divisionDAO = new DivisionDAO(con) Collection divList = divisionDAOfindAll() requestsetAttribute(divListdivList)
return mappingfindForward(success)
catch (SQLException e) eprintStackTrace() ActionError error = new ActionError(errorunexpected) errorsadd(ActionErrorsGLOBAL_ERROR error)
192
catch (Throwable e) eprintStackTrace() ActionError error = new ActionError(egetMessage()) errorsadd(ActionErrorsGLOBAL_ERROR error) finally try if (con = null) conclose() catch (SQLException e) throw new RuntimeException(errorunexpected)
saveErrors(request errors) return new ActionForward(mappinggetInput())
Letrsquos now deploy the code
Deploying the code1 Bring up WTE in VAJ and start the servlet engine2 Start the Persistent Name Server3 Bring up IE 55 (forget NS 45 for now) and type the following url in the address line
httplocalhost8080craftLoginjsp
4 Enter a valid email address and a password then select the link Display Divisionfrom the menu in the welcome page
ResultYou should see the following
Login page
Welcome page showing new item in the menu
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
193
Clicking on Display Division will display the following page
194
In conclusion we can add more methods to the DAO to do other types of db access suchas findByPrimaryKey() create() remove() update() and other specialized db accessmethods
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
195
Lesson 24 ndash Business ObjectsBasicsThis lesson takes our example a bit further by providing a process that lets the user edit arecord and commit it to the db The Division items will then be re-displayed to show theupdated values The previous lesson puts the task of retrieving data on the action classitself For data updates creation or deletion we will use another object that sits betweenthe action class and the DAO class usually termed Business Object (BO) We use thisobject to encapsulate business logic such as business-specific validations andorcalculations The discussion on form validation in Lesson 17 concentrated on genericpresentation layer validation such as data format and null checking so do not confusethis with the validation that occurs on the business layer An example of business-specificvalidation is to check for dollar ranges A user may have entered the correct dollar formaton the browser but our BO will make sure that the amount is say between 0 and 100dollars However it is still up to you the designerdeveloper to figure out which validationis done at the presentation and business layers This is one case where there may bemore than one correct answer
The exercise in this lesson will walk you through the creation of a BO and how to invoke itfrom an action class We will also update the DAO to implement a new method that willdo the update to the db We will then create a new jsp for the edit screen and of coursemore struts configuration
Coding1 First wersquoll have to make changes to the DivisionBean in comffictraining so that
struts can recognize it and automatically populate itrsquos properties from the browser
Add an import statement for the ActionForm class
import orgapachestrutsactionActionForm
Change the class declaration so that it extends the ActionForm class
public class DivisionBean extends ActionForm(
Change the DivNo variable type to int
int DivNo
Change the gettersetter for DivNo to work with int instead of String
public int getDivNo()
return divNo
196
public void setDivNo(int divNo)
thisdivNo = divNo
Note This change may affect some of the classes that you created in previouslessons You can go back to them and make the necessary corrections if you want torun them again
Complete code (comffictrainingDivisionBean)
import orgapachestrutsactionActionForm
public class DivisionBean extends ActionForm
private int divNoprivate String divDesc
public String getDivDesc()
return divDescpublic int getDivNo()
return divNopublic void setDivDesc(String divDesc)
thisdivDesc = divDescpublic void setDivNo(int divNo)
thisdivNo = divNo
2 Wersquoll then make changes to the DivisionDAO so open this class for editing
Since wersquoll be editing one record we need to provide a way of retrieving that record usingitrsquos primary key (division number) So add the method findByPrimaryKey() with thefollowing code
We pass the primary key (divNo) to the method
public DivisionBean findByPrimaryKey(int divNo) throws Exception
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
197
Here we use a PreparedStatement instead of Statement for performance reasons (notevident in this exercise) We also define the resultset object and a DivisionBean objectthat will hold the result from the db
PreparedStatement ps = nullResultSet rs = nullDivisionBean divisionBean
Define the SQL
String sql = SELECT FROM IOUDIVISION WHERE DI_NO =
try
if (conisClosed()) throw new IllegalStateException(errorunexpected)
Run the query and put the results in the bean
ps = conprepareStatement(sql)pssetInt(1divNo)rs = psexecuteQuery()
if (rsnext())
divisionBean = new DivisionBean()divisionBeansetDivNo(rsgetInt(1))divisionBeansetDivDesc(rsgetString(2)trim())
return divisionBean else
throw new Exception(errorremoveddivision)
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
finally try
if (ps = null)psclose()
if (rs = null)rsclose()
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
198
Next on our list is to define a method that updates the database Add the methodupdate() with the following code
We pass a divisionBean object that contains the information for the update operation
public void update(DivisionBean divisionBean) throws Exception
PreparedStatement ps = null
Define the SQL
String sql = UPDATE IOUDIVISION SET DI_DESCRIPTION = WHERE + DI_NO =
try
if (conisClosed()) throw new IllegalStateException(errorunexpected)
Set the parameters (the ) run the query and make sure that the update was successful
ps = conprepareStatement(sql)pssetString(1divisionBeangetDivDesc())pssetInt(2divisionBeangetDivNo())
if (psexecuteUpdate() = 1)
throw new Exception(errorupdatedivision)
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
finally try
if (ps = null)psclose()
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
199
3 Next we will create a BO that will implement the following public methods
update() findByPrimaryKey()
In VAJ in the package comffictraining create a class named DivisionBO and placethe following code
import javaioIOException
import javautilimport javaxservletServletExceptionimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpSession
import javasqlConnectionimport javasqlSQLException
import comfficfincraftdbutilConnectionPool
Insert the types description here Creation date (13002 30549 PM) author Administrator public class DivisionBO
private ConnectionPool pool
public DivisionBO() pool = ConnectionPoolgetInstance()
Add an update() method to this class with the following code
The method accepts a divisionBean object containing the information for the updateoperation
public void update(DivisionBean divisionBean) throws Exception
Connection con = null
In this try block a connection is created from the pool and passed to a new instance ofthe DivisionDAO This DAO then updates the db using the divisionBean object thatrsquospassed to it
200
try
con = poolgetConnection()
DivisionDAO divisionDAO = new DivisionDAO(con)divisionDAOupdate(divisionBean)
concommit()
catch (Exception e) try
if (con = null) conrollback()throw new Exception(egetMessage())
catch (SQLException sqle)
eprintStackTrace()throw new RuntimeException(errorunexpected)
finally
try if (con = null)
conclose()
catch (SQLException sqle) sqleprintStackTrace()throw new RuntimeException(errorunexpected)
Add a findByPrimaryKey() method to this class with the following code
The method accepts an integer as the key
public DivisionBean findByPrimaryKey(int divNo)
DivisionBean divisionBean = nullConnection con = null
In this try block a connection is created from the pool and passed to a new instance ofthe DivisionDAO This DAO then searches the db using the primary key passed to it
try
con = poolgetConnection()DivisionDAO divisionDAO = new DivisionDAO(con)
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
201
divisionBean = divisionDAOfindByPrimaryKey(divNo)
return divisionBean
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
catch (Throwable e) eprintStackTrace()throw new RuntimeException(errorunexpected)
finally try
if (con = null)conclose()
catch (SQLException e) throw new RuntimeException(errorunexpected)
Complete code (comffictrainingDivisionDAO)
import javasqlConnectionimport javasqlPreparedStatementimport javasqlResultSetimport javasqlSQLExceptionimport javasql
import javautilCollectionimport javautilArrayList
Insert the types description here Creation date (11802 13224 PM) author Administrator public class DivisionDAO
private javasqlConnection con DivisionDAO constructor comment public DivisionDAO()
super() Insert the methods description here Creation date (11802 13834 PM)
202
param con comibmrmiiiopConnection public DivisionDAO(Connection con)
thiscon = con
public DivisionBean findByPrimaryKey(int divNo) throws Exception
PreparedStatement ps = nullResultSet rs = nullDivisionBean divisionBean
String sql = SELECT FROM IOUDIVISION WHERE DI_NO =
try
if (conisClosed()) throw new IllegalStateException(errorunexpected)
ps = conprepareStatement(sql)pssetInt(1divNo)rs = psexecuteQuery()
if (rsnext())
divisionBean = new DivisionBean()divisionBeansetDivNo(rsgetInt(1))divisionBeansetDivDesc(rsgetString(2))
return divisionBean else
throw new Exception(errorremoveddivision)
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
finally try
if (ps = null)psclose()
if (rs = null)rsclose()
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
203
public void update(DivisionBean divisionBean) throws Exception
PreparedStatement ps = null
String sql = UPDATE IOUDIVISION SET DI_DESCRIPTION = WHERE + DI_NO =
try
if (conisClosed()) throw new IllegalStateException(errorunexpected)
ps = conprepareStatement(sql)pssetString(1divisionBeangetDivDesc()trim())pssetInt(2divisionBeangetDivNo())
if (psexecuteUpdate() = 1)
throw new Exception(errorupdatedivision)
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
finally try
if (ps = null)psclose()
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
4 Next is to create the action class that uses the BO that we just created We actuallyneed two action classes one is to do the findByPrimaryKey() and return the data tothe browser for editing and the other is to accept the updated data and do theupdate()
Still in comffictraining create a class named EditDivisionAction and place thefollowing code
204
Import the necessary packages
import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOException
Be sure to extend the Action class the implement the execute() method
public class EditDivisionAction extends orgapachestrutsactionAction
public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)
throws IOException ServletException
ActionErrors errors = new ActionErrors()
DivisionBean divisionBean
try
Here we anticipate the divNo to come from the request object Wersquoll see why in the nextsteps
int divNo = IntegerparseInt(requestgetParameter(divNo))
Instantiate a BO do a finrByPrimaryKey using the key from the request and thenassociate the resulting bean to the request object so the jsp can render it
DivisionBO divisionBO = new DivisionBO()divisionBean = divisionBOfindByPrimaryKey(divNo)requestsetAttribute(divFormdivisionBean)
return mappingfindForward(success)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
205
errorsadd(ActionErrorsGLOBAL_ERROR error)
saveErrors(request errors)return new ActionForward(mappinggetInput())
Complete code (comffictrainingEditDivisionAction)
import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOException
Insert the types description here Creation date (12402 23818 PM) author Administrator public class EditDivisionAction extends orgapachestrutsactionAction
Insert the methods description here Creation date (12402 24105 PM) public ActionForward execute(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response)throws IOException ServletException
ActionErrors errors = new ActionErrors()
DivisionBean divisionBean
try
206
int divNo = IntegerparseInt(requestgetParameter(divNo))
DivisionBO divisionBO = new DivisionBO()divisionBean = divisionBOfindByPrimaryKey(divNo)requestsetAttribute(divFormdivisionBean)
return mappingfindForward(success)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
saveErrors(request errors)return new ActionForward(mappinggetInput())
Create another action class named UpdateDivisionAction and place the following code
Import the necessary packages
import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOException
Extend the Action class and implement the execute() method
public class UpdateDivisionAction extends orgapachestrutsactionAction
Insert the methods description here Creation date (12402 24105 PM)
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
207
public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)
throws IOException ServletException
ActionErrors errors = new ActionErrors()
try
Here itrsquos a little different in that the divisionBean is passed to this method as anActionForm so we have to cast it back to itrsquos original class The form was populated bythe ActionServlet using values entered in the browser as we will see later
DivisionBean divisionBean = (DivisionBean) form
Instantiate a new BO and do an update using the divisionBean object
DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)
return mappingfindForward(success)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
saveErrors(request errors)return new ActionForward(mappinggetInput())
Complete code (comffictrainingEditDivisionAction)
import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponse
208
import javaxservletServletException
import javaioIOException
import javasqlConnectionimport javasqlSQLException
import javautilCollection
Insert the types description here Creation date (12402 23818 PM) author Administrator public class UpdateDivisionAction extends orgapachestrutsactionAction
Insert the methods description here Creation date (12402 24105 PM) public ActionForward execute(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response)throws IOException ServletException
ActionErrors errors = new ActionErrors()
try
DivisionBean divisionBean = (DivisionBean) form
DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)
return mappingfindForward(success)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
saveErrors(request errors)return new ActionForward(mappinggetInput())
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
209
5 We will then create the jsp that will let the user edit the division description Create afile named divEditContentjsp in the craft folder in WTE and place the followingcode
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gt
The usual lines of code to render error messages
ltlogicmessagesPresentgt ltbeanmessage key=errorsheadergt ltulgt lthtmlmessages id=errorgt ltligtltbeanwrite name=error filter=falsegtltligt lthtmlmessagesgt ltulgtlthrgtltlogicmessagesPresentgt
Here we use an lthtmlformgt to render a form It will invoke updateDivdo whensubmitted
lthtmlform action=updateDivdo gt
lttable border=1gt
We use a ltbeanwritegt to render a display-only value of the division numberlttrgt lttdgtDivision No lttdgt lttdgtltbeanwrite name=divForm property=divNo gtlttdgtlttrgt
We use a lthtmltextgt to render an input field for the division descriptionlttrgt lttdgtDescriptionlttdgt lttdgtlthtmltext name=divForm property=divDesc gtlttdgtlttrgtlttablegt
Render a submit buttonlthtmlsubmit gtlthtmlformgt
Complete code (divEditContentjsp)
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gt
210
ltlogicmessagesPresentgt ltbeanmessage key=errorsheadergt ltulgt lthtmlmessages id=errorgt ltligtltbeanwrite name=error filter=falsegtltligt lthtmlmessagesgt ltulgtlthrgtltlogicmessagesPresentgt
lthtmlform action=updateDivdo gtlthtmlhidden property=divNogtlttable border=1gtlttrgt lttdgtDivision No lttdgt lttdgtltbeanwrite name=divForm property=divNo gtlttdgt lttrgtlttrgt lttdgtGross Amtlttdgt lttdgtlthtmltext name=divForm property=divDesc gtlttdgtlttrgtlttablegt
lthtmlsubmit gtlthtmlformgt
6 We then need to add a link beside each record in the divDisplayContentjsp thatinvokes an editDivdo link so open the file and place the following code after thesecond ltbeanwritegt tag
lttdgtlta href=editDivdodivNo=ltbeanwrite name=divproperty=divNogtgteditltagtlttdgt
Complete code (divDisplayContentjsp)
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gt
ltlogicmessagesPresentgt ltbeanmessage key=errorsheadergt ltulgt lthtmlmessages id=errorgt
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
211
ltligtltbeanwrite name=error filter=falsegtltligt lthtmlmessagesgt ltulgtlthrgtltlogicmessagesPresentgt
lttable border=1gtltbr gtltbgtDivision ListltbgtlttrgtltthgtCodeltthgtltthgtDescriptionltthgtlttrgtltlogiciterate name=divList
id=div scope=request type=comffictrainingDivisionBeangt
lttrgtlttdgtltbeanwrite name=div property=divNo gtlttdgtlttdgtltbeanwrite name=div property=divDesc gtlttdgtlttdgtlta href=editDivdodivNo=ltbeanwrite name=div
property=divNogtgteditltagtlttdgt
lttrgtltlogiciterategt
lttablegt
7 Since we created two action classes we then need to create entries in the struts-configxml file Place the following code in the ltaction-mappingsgt tag
ltaction path=editDivtype=comffictrainingEditDivisionActionscope=requestinput=divdisplaypagegtltforward name=success path=diveditpage gt
ltactiongt
ltaction path=updateDivtype=comffictrainingUpdateDivisionActionscope=requestname=divForminput=diveditpagegtltforward name=success path=displayDivdo gt
ltactiongt
In the same file place the following code in the ltform-beansgt tag since we changedthe DivisionBean to extend ActionForm
ltform-bean name=divForm type=comffictrainingDivisionBeangt
212
Take note that we associated divForm with updateDiv This tells struts to update theDivisionBean form with whatever is entered in the browser when updateDiv is invokedThe forward name success for updateDiv maps to displayDivdo which tells theActionServlet to redisplay all items in the Division table so the user can check if thechange to the data occurred
8 Open the tileDefinitionxml located in craftWEB-INF and add the following entriesthat define the page layout for the edit page
lt-- Extended definition for account display --gtltdefinition name=diveditpage extends=welcomepagegt
ltput name=body content=divEditContentjspgtltdefinitiongt
We have all the pieces that we need so we can now deploy the application
Deploying the code5 Bring up WTE in VAJ and start the servlet engine6 Start the Persistent Name Server7 Bring up IE 55 (forget NS 45 for now) and type the following url in the address line
httplocalhost8080craftLoginjsp
8 Enter a valid email address and a password then select the link Display Divisionfrom the menu in the welcome page
ResultThe new page that displays the Division items should look like the following
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
213
If the user clicks on the first item hersquoll get the following screen
214
Change the description as shown in the screen below then click submit
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
215
The Division items will be redisplayed showing the change made to the first item
We can further improve on the codes that we just built by minimizing the number of actionclasses that we create Wersquoll cover that in the next lesson
216
Lesson 25 ndash Action subclassesUp to this point we have been subclassing the class orgapachestrutsactionAction tocreate our own Action classes The Struts Javadoc lists some pre-written subclasses ofthe Action class that have been found to be very useful and therefore worth coveringWersquoll mention some the subclasses and then create an example app using one of themost usefule Action subclass the DispatchAction
Here are the subclasses of the Action class with some definitons taken from the Javadoc
DispatchAction - An abstract Action that dispatches to a public method that is named bythe request parameter whose name is specified by the parameter property of thecorresponding ActionMapping This Action is useful for developers who prefer tocombine many similar actions into a single Action class in order to simplify theirapplication design
ForwardAction - An Action that forwards to the context-relative URI specified by theparameter property of our associated ActionMapping This can be used to integrateStruts with other business logic components that are implemented as servlets (or JSPpages) but still take advantage of the Struts controller servlets functionality (such asprocessing of form beans)
IncludeAction - An Action that includes the context-relative URI specified by theparameter property of our associated ActionMapping This can be used to integrateStruts with other business logic components that are implemented as servlets (or JSPpages) but still take advantage of the Struts controller servlets functionality (such asprocessing of form beans)
LookUpDispatchAction - An abstract Action that dispatches to the subclass mappedperform method This is useful in cases where an HTML form has multiple submitbuttons with the same name The button name is specified by the parameter property ofthe corresponding ActionMapping
Wersquoll discuss the DispatchAction in this lesson and improve on the previous lessonrsquosexample app to demonstrate the use of this particular Action subclass You can consultthe Struts javadoc for the usage of the rest of the Action sublasses
The idea here is according to experts to minimize the amount of Action classes that wecreate by grouping related functions within one Action class Currently in our exampleapp there are three (3) Action classes that work with the Division table By using theDispatchAction we can define three methods in one Action class to perform the find editand update functions without putting in a lot of ldquoif-then-elserdquo logic All we need to do is touse the ldquoparameterrdquo attribute in the Action classrsquo action-mapping entry to distinguish thekind of operation that wersquore trying to perform for that Action class For example a classthat extends the DispatchAction might have the following action-mapping entry
ltaction path=adminDivtype=comffictrainingDivisionAction
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
217
scope=request name=divForm parameter=method input=diveditpagegtltforward name=editpage path=diveditpagegtltforward name=success path=displayDivdogtltactiongt
We use a parameter named ldquomethodrdquo (can be anything) and our Action class will checkfor the value that is passed to this parameter and match it with a method name in ourAction class In our Action class we may have the following methods
public ActionForward view(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)
throws IOException ServletException
public ActionForward edit(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)
throws IOException ServletException
If we invoke our Action class using the url
httplocalhost8080craftadminDivdomethod=edit
Then our Action class will match the value in the ldquomethodrdquo parameter in this case itrsquosldquoeditrdquo and perform the edit() method that we defined above
This will become clearer as we go into the next section so letrsquos move on
Coding1 First wersquoll have to change our DivisionBO to include the findAll() method This will
make the resulting Action class more generic as all connection pool handling will bedone at the BO level rather than at the Action level In VAJ open the DivisionBOclass and add the following code
The findAll() method returns a collection
public Collection findAll() throws Exception
Collection list = nullConnection con = null
try
Get a connection from the pool instantiate a DAO and perform a findAll() then return theresult
218
con = poolgetConnection()DivisionDAO divisionDAO = new DivisionDAO(con)list = divisionDAOfindAll()
return list
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
catch (Throwable e) eprintStackTrace()throw new RuntimeException(errorunexpected)
finally try
if (con = null)conclose()
catch (SQLException e) throw new RuntimeException(errorunexpected)
Complete code (comffictrainingDivisionBOrsquos findAll() method)
public Collection findAll() throws Exception
Collection list = nullConnection con = null
try
con = poolgetConnection()DivisionDAO divisionDAO = new DivisionDAO(con)list = divisionDAOfindAll()
return list
catch (SQLException e) eprintStackTrace()throw new RuntimeException(errorunexpected)
catch (Throwable e) eprintStackTrace()throw new RuntimeException(errorunexpected)
finally try
if (con = null)conclose()
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
219
catch (SQLException e) throw new RuntimeException(errorunexpected)
2 In VAJ in the package comffictraining create a class named DivisionAction withthe following code
Import the necessary packages
import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOException
import javautil
Define the DivisionAction Action class by extending DispatchAction
public class DivisionAction extends orgapachestrutsactionsDispatchAction
In this class create the following methods OR cut and paste execute() methods from theEditDivisionAction (rename to edit() method) UpdateDivisionAction (rename toupdate() method) The view() method is new since we just created a new method in theBO in the first step
public ActionForward edit(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)
throws IOException ServletException
ActionErrors errors = new ActionErrors()
DivisionBean divisionBean
try
220
int divNo = IntegerparseInt(requestgetParameter(divNo))
DivisionBO divisionBO = new DivisionBO()divisionBean = divisionBOfindByPrimaryKey(divNo)requestsetAttribute(divFormdivisionBean)
return mappingfindForward(editpage)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
saveErrors(request errors)return new ActionForward(mappinggetInput())
public ActionForward update(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)
throws IOException ServletException
ActionErrors errors = new ActionErrors()
try
DivisionBean divisionBean = (DivisionBean) form
DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)
return mappingfindForward(success)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
saveErrors(request errors)return new ActionForward(mappinggetInput())
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
221
public ActionForward view(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)
throws IOException ServletException
ActionErrors errors = new ActionErrors()
try
DivisionBO divisionBO = new DivisionBO()Collection divList = divisionBOfindAll()requestsetAttribute(divListdivList)
return mappingfindForward(displaypage)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
saveErrors(request errors)return new ActionForward(mappinggetInput())
Complete code (comffictrainingDivisionAction)
import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOExceptionimport javautil
Insert the types description here Creation date (12402 23818 PM) author Administrator
222
public class DivisionAction extends orgapachestrutsactionsDispatchAction
Insert the methods description here Creation date (12402 24105 PM) public ActionForward edit(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response)throws IOException ServletException
ActionErrors errors = new ActionErrors()
DivisionBean divisionBean
try
int divNo = IntegerparseInt(requestgetParameter(divNo))
DivisionBO divisionBO = new DivisionBO()divisionBean = divisionBOfindByPrimaryKey(divNo)requestsetAttribute(divFormdivisionBean)
return mappingfindForward(editpage)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
saveErrors(request errors)return new ActionForward(mappinggetInput())
Insert the methods description here Creation date (12402 24105 PM) public ActionForward update(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response)throws IOException ServletException
ActionErrors errors = new ActionErrors()
try
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
223
DivisionBean divisionBean = (DivisionBean) form
DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)
return mappingfindForward(success)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
saveErrors(request errors)return new ActionForward(mappinggetInput())
Insert the methods description here Creation date (12402 24105 PM) public ActionForward view(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response)throws IOException ServletException
ActionErrors errors = new ActionErrors()
try
DivisionBO divisionBO = new DivisionBO()Collection divList = divisionBOfindAll()requestsetAttribute(divListdivList)
return mappingfindForward(displaypage)
catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
saveErrors(request errors)return new ActionForward(mappinggetInput())
224
3 Now that we have created our Action class wersquoll need to create the following entriesin the struts-configxml in craftWEB-INF
ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divForm parameter=method input=diveditpagegt
ltforward name=editpage path=diveditpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegt
ltactiongt
Note that we provided several forwards in this entry because the different processes willhave different navigation requirements We didnrsquot touch the ldquoinput=rdquo parameter but thisshould be changed in case we want all error messages displayed in a common jsp
4 Next wersquoll change the link in the menu-configxml file that invokes the old Actionclass Open the menu-configxml file in craftWEB-INF and change the followingline of code
ltItem name=DispDiv title=Display Division location=displayDivdogt
to
ltItem name=DispDiv title=Display Division location=adminDivdomethod=viewgt
5 Wersquoll then make changes to the links in the following jsprsquos
Open the divDisplayContentjsp in the craft folder and make the following changes
Change the following line
lttdgtlta href=editDivdodivNo=ltbeanwrite name=divproperty=divNogtgteditltagtlttdgt
to
lttdgtlta href=adminDivdodivNo=ltbeanwrite name=divproperty=divNogtampmethod=editgteditltagtlttdgt
Open the divEditContentjsp in the craft folder and make the following changes
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
225
Change the following line
lthtmlform action=updateDivdo gt
to
lthtmlform action=adminDivdomethod=update gt
We now have all the components necessary to test our new Action class
Deploying the code1 Bring up WTE in VAJ and start the servlet engine2 Start the Persistent Name Server3 Bring up IE 55 (forget NS 45 for now) and type the following url in the address line
httplocalhost8080craftLoginjsp
4 Enter a valid email address and a password then select the link Display Divisionfrom the menu in the welcome page
ResultThe result should be the same as in lesson 24 except that we are now using a singleAction class for all our operations on the Division table
226
If the user clicks on the first item hersquoll get the following screen
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
227
Change the description as shown in the screen below then click submit
The Division items will be redisplayed showing the change made to the first item
228
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
229
Lesson 26 ndash Exception handling Basics Struts provides a unique mechanism for exception handling which deserves a lesson onitrsquos own We have been mentioning exception handling in small amounts here and therebut we have not quite discussed it as thoroughly as needed In this lesson wersquoll highlightthe ActionErrorsActionError classes and provide an example of the new exceptionhandling capability of Struts 11b A primer on java exception handling can be found inhttpjavasuncomdocsbookstutorialessentialexceptionsindexhtml
In case you didnrsquo t have the time to go through the tutorial here are diagrams thatcompare exception handling using nested ifrsquos vs exception handling using trycatchblocks
Using nested ifrsquos
public void mainProcess ()
process1()
if (normal condition detected for process 1)
process2()
if (normal condition detected for process 2)
process3()
else if (error is detected for process 2)
process error
else if (error detected for process 1)
process error
Using trycatch blocks
public void mainProcess()
try
230
process1()
process2()
process3()
catch (Exception1 e)
process error
catch Exception2 e)
process error
finally
do something no matter what happens in the process
You can also throw an exception to a higher level method (ie another class may invokethe mainPocess() method) instead of catching it in a catch block Just make sure that thehigher level method catches this thrown exception in a trycatch block This is how it maybe coded
public void mainProcess throws Exception1 Exception2 ()
process1()process2()process3()
Then a class that invokes mainProcess might have something like this
try
mainProcess()
catch (Exception1 e)
process error
catch Exception2 e)
process error
finally
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
231
do something no matter what happens in the process
In our example application we throw exceptions from the DAO level all the way up to theAction class where we create an ActionError object for any exception that may occurCurrently we are using the default message from the Exception object as an argument increating an ActionError object We however should be passing a key to be matched withentries in the ApplicationResourcesproperties file instead of just a plain messagestring To do this we can create custom exceptions where we pass the key value to theconstructor and this will in turn be passed to the ActionError constructor
In this lesson wersquoll create another process in the application to perform a search againstthe Division table and if no match is found an ActionError object will be created andrendered on the page You can later on change the other processes to throw customexceptions instead of the Exception object
There are two exercises in this lesson The first deals with programmatic exceptionhandling in Struts and the next one demonstrates declarative exception handling usingentries in the struts-configxml to catch exception objects
Coding (Part 1 ndash programmatic exception handling)We will create a process that lets the user type in a division code and the application willperform a search against the Division table If a match is found the result will bedisplayed in an edit page otherwise an error message will be displayed on the searchpage
1 First wersquoll create a custom exception to be used in our DAO when we do afindByPrimaryKey In comffictraining create class named FindException thatextends Exception and place the following code
public class FindException extends Exception public FindException(String s)
super(s)
2 Now that we have a custom exception wersquoll make the following changes in theDivisionDAO to start using this exception object Open the DivisionDAO class andin the method FindByPrimaryKey() make the following changes
Change the following line of code
public DivisionBean findByPrimaryKey(int divNo) throws Exception
to
232
public DivisionBean findByPrimaryKey(int divNo) throws FindException
The above code will throw the FindException object to the higher level method which is inthe BO
In the same method change the following line of code
throw new Exception(errorremoveddivision)
to
throw new FindException(errordivisionnotfound)
The above code will initialized a new FindException object and assign the keyldquoerrordivisionnotfoundrdquo to it
3 We need to propagate this error up to the Action class so open the DivisionBO classand make the following changes
Change the following line of code
public DivisionBean findByPrimaryKey(int divNo) throws Exception
to
public DivisionBean findByPrimaryKey(int divNo) throws FindException
4 Now we move up to the Action class DivisionAction where wersquoll need to createanother method named findByPrimaryKey() to handle the exception and to serviceour search request Add the following codes to DivisionAction
public ActionForward findByPrimaryKey(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)
throws IOException ServletException
ActionErrors errors = new ActionErrors()
DivisionBean divisionBean = (DivisionBean) form
try
int divNo = divisionBeangetDivNo()
DivisionBO divisionBO = new DivisionBO()divisionBean = divisionBOfindByPrimaryKey(divNo)requestsetAttribute(divFormdivisionBean)
return mappingfindForward(editpage)
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
233
catch (FindException e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)
saveErrors(request errors)return mappingfindForward(searchpage)
5 Open the ApplicationResourcesproperties file and add the following entry so thekey we pass to FindException can be matched with a value from this file
errordivisionnotfound=ltfont color=redgtltbgtDivision code not foundltbgtltfontgt
6 We then need to create two (2) jsps to render the search page
Create a file named divSearchContentjsp and save it in the craft folder Place thefollowing code
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gt
ltlogicmessagesPresentgt ltbeanmessage key=errorsheadergt ltulgt lthtmlmessages id=errorgt ltligtltbeanwrite name=error filter=falsegtltligt lthtmlmessagesgt ltulgtlthrgtltlogicmessagesPresentgt
lt-- this form calls the findByPrimaryKey() method of adminDiv --gtlthtmlform action=adminDivdomethod=findByPrimaryKey gtlttable border=1gtlttrgt lttdgtEnter Division Code lttdgt lttdgtlthtmltext name=divForm property=divNo gtlttdgt lttrgtlttablegt
lthtmlsubmit gtlthtmlformgt
234
Create another file named divSearchjsp and save it in the craft folder then place thefollowing code
lt taglib uri=WEB-INFtilestld prefix=tiles gt
lttilesinsert page=TilesTemplatejsp gtlttilesput name=menu value=Menujsp gtlttilesput name=body value=divSearchContentjsp gt
lttilesinsertgt
7 To add this new jsp in our menu open the file menu-configxml in craftWEB-INFand add the following entry (in bold)
ltMenu name=MainMenu title=MainMenu level=1gtltItem name=SkillInv title=Skills Inventory location=Inputjsp gtltItem name=DispAcct title=Display Account location=acctDisplayjsp gtltItem name=DispDivx title=Display Division location=adminDivdomethod=view gtltItem name=SrchDiv title=Search Division location=divSearchjsp gtltMenugt
8 Lastly wersquoll add a new forward in struts-configxml for the new method inDivisionAction so add the entries in bold
ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt
ltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegt
ltactiongt
Deploying the code (Part 1 ndash programmatic exceptionhandling)1 Bring up WTE in VAJ and start the servlet engine2 Start the Persistent Name Server3 Bring up IE 55 (forget NS 45 for now) and type the following url in the address line
httplocalhost8080craftLoginjsp
4 Enter a valid email address and a password then select the link Search Divisionfrom the menu in the welcome page
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
235
Result (Part 1 ndash programmatic exception handling)You should see the following screens
The welcome page showing the new link for the search
236
The search page
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
237
If the user enters a non-existend Division code
238
If the user enters a valid Division code then the edit page will be displayed showing theresult of the search
Coding (Part 2 ndash using declarative exception)
The next part of this lesson will demonstrate a new feature in Struts 11b where wedeclare exceptions to be handled in the struts-configxml file This feature is not yetmature as it only is supported by direct subclasses of the Action class It currently doesnot work with the DispatchAction so our example will be similar to the Part 1 except thatwe will create a new Action class to perform the search and pass the exception to theActionServlet
1 In VAJ in the package comffictraining create an Action class namedFindDivisionAction that extends orgapachestrutsactionAction and place thefollowing code
Import the necessary packages
import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMapping
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
239
import orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOExceptionimport javautil
Define the class
public class FindDivisionAction extends orgapachestrutsactionAction
Implement the execute() method which throws an Exception so the ActionServlet willhandle the exception instead of in this Action class
public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)
throws Exception
The next lines of code are similar to the FindByPrimaryKey() method of DivisionActionexcept that there is no trycatch block to handle application exceptions
ActionErrors errors = new ActionErrors()
DivisionBean divisionBean = (DivisionBean) form
int divNo = divisionBeangetDivNo()
DivisionBO divisionBO = new DivisionBO()divisionBean = divisionBOfindByPrimaryKey(divNo)requestsetAttribute(divFormdivisionBean)
return mappingfindForward(editpage)
Complete code (comffictrainingFindDivisionAction)
import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrors
240
import orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOExceptionimport javautil
Insert the types description here Creation date (12402 23818 PM) author Administrator public class FindDivisionAction extends orgapachestrutsactionAction
Insert the methods description here Creation date (12402 24105 PM) public ActionForward execute(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response)throws Exception
ActionErrors errors = new ActionErrors()
DivisionBean divisionBean = (DivisionBean) form
int divNo = divisionBeangetDivNo()
DivisionBO divisionBO = new DivisionBO()divisionBean = divisionBOfindByPrimaryKey(divNo)requestsetAttribute(divFormdivisionBean)
return mappingfindForward(editpage)
2 As in the previous exercise in this lesson the DAO will throw a FindException if arecord with a particular key is not found in the table Since we did not handle thatexception in the Action class we will declare this exception in the struts-configxmlwhen we create the entry for this new Action class Open the struts-configxml incraftWEB-INF and add the following entry
ltaction path=findDiv
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
241
type=comffictrainingFindDivisionAction scope=request name=divForm input=divsearchpagegtltexception key=errordivisionnotfound type=comffictrainingFindExceptionpath=divsearchpagegt
ltforward name=editpage path=diveditpagegtltactiongt
The ltexceptiongt tag contains three required attributes
key ndash this is the key for the error message that should match an entry in theApplicationResourcesproperties file
type ndash the fully qualified name of the exception class path ndash the forward path for this exception
3 Next is we will revise the divSearchContentjsp to invoke the FindDivisionActionclass to perform the search Open the divSearchContentjsp in craft and makethe following change
Remove the line
lthtmlform action=adminDivdomethod=findByPrimaryKey gt
Replace it with
lthtmlform action=findDivdo gt
Before we deploy the code letrsquos review what the chain of events will be if an exception isdetected
If a user enters a division code that does not exist in the Division table theDivisionDAO will throw a FindException
The DivisionBO will not handle this exception and instead throw it to the higher levelmethod in the FindDivisionAction class
The FindDivisionAction class will also not handle the FindException and insteadthrow it to the ActionServlet
The ActionServlet will detect the exception find out itrsquos type and find a match in theaction-mapping (the one in struts-configxml) and perform the necessary messagesubstitution and forwarding
In case you need to catch more than one exception then you need to add moreltexceptiongt tags to handle them Note that there is a ltglobal-exceptionsgt tag toencapsulate common exceptions that may occur in the entire application
So now letrsquos deploy the code and examine the results
242
Deploying the code (Part 2 ndash using declarative exception)
1 Bring up WTE in VAJ and start the servlet engine2 Start the Persistent Name Server3 Bring up IE 55 (forget NS 45 for now) and type the following url in the address line
httplocalhost8080craftLoginjsp
4 Enter a valid email address and a password then select the link Search Divisionfrom the menu in the welcome page
Result (Part 2 ndash using declarative exception)The result should look the same as Part 1 of this lesson
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
243
Lesson 27 ndash Creating dynamic formsBasicsThere will be times when we want to process transient data that just require a temporaryplace to store them without us having to define a bean Moreover we want that data tobe handled pretty much the same way as ActionForms are handled by Struts( ieautomatic bean population and association with action class) There is an ActionFormsubclass that enables developers to do what we just described This ActionFormsubclass called DynaActionForm can be defined pretty much the same way as a regularActionForm is defined in the struts config file The difference is that since it is created onthe fly we need to provide the properties for the form in the configuration The handlingfor this type of form is also a bit different since the mutatorsaccessors (another term forsettersgetters respectively) are not directly visible to the Action class
Candidates for implementing a DynaActionForm in our example application are the Loginand Division search processes Wersquoll go through the process of converting the pre-defined form beans to dynamic on-the-fly-created form beans The reason why we willcover two examples in this lesson is that the division search will use a regularDynaActionForm while the login process will use a DynaValidatorForm to continue usingthe struts-validator Coding (Part 1 ndash DynaActionForm example)The division search requires a form that provides a way to store the division code andpass the value to the Action class It may not make sense to continue using theDivisionBean bean that we created since we are only using one field The next sectionwill walk you through the creation of a DynaActionForm in place of the DivisionBean andthe necessary changes that need to be done on the different parts of the application
1 The very first thing we need to do is to define the dynamic form in the struts-configxml file
Create the following entry for the form bean
ltform-bean name=srchForm type=orgapachestrutsactionDynaActionFormgtltform-property name=test type=javalangStringgt
ltform-beangt
Change the form for the FindDivisionAction to start using the dynamic form Wersquoll addanother exception handler since we expect an integer for the division code and the usermight enter alphanumeric characters We also used a different key for the new exception
ltaction path=findDiv type=comffictrainingFindDivisionAction name=srchFormscope=request input=diveditpagegt
ltexception key=errordivisionnotfound type=comffictrainingFindExceptionpath=divsearchpagegt
244
ltexception key=errordivisionnotnumber type=javalangNumberFormatExceptionpath=divsearchpagegt
ltforward name=editpage path=diveditpagegtltactiongt
2 Add the new message key in ApplicationResourcesproperties and assign a valueto it
errordivisionnotnumber=ltfont color=redgtltbgtDivision code must be anumberltbgtltfontgt
3 Next is to change divSearchContentjsp to make sure that the dynamic form is used
Change the following line
lttdgtlthtmltext name=divForm property=divNo gtlttdgt
to
lttdgtlthtmltext name=test property=divNo gtlttdgt
Complete code (divSearchContentjsp)
lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gt
ltlogicmessagesPresentgt ltbeanmessage key=errorsheadergt ltulgt lthtmlmessages id=errorgt ltligtltbeanwrite name=error filter=falsegtltligt lthtmlmessagesgt ltulgtlthrgtltlogicmessagesPresentgt
lthtmlform action=findDivdo gtlttable border=1gtlttrgt lttdgtEnter Division Code lttdgt lttdgtlthtmltext property=test gtlttdgt lttrgtlttablegt
lthtmlsubmit gt
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
245
lthtmlformgt
4 Lastly wersquoll make changes to the FindDivisionAction class as follows
Removecomment out the following lines of code
DivisionBean divisionBean = (DivisionBean) form
int divNo = divisionBeangetDivNo()
DivisionBean divisionBean = divisionBOfindByPrimaryKey(divNo)
Add the following lines of code
Place this after the line ldquoActionErrors errors = new ActionErrors()rdquo int divNo = IntegerparseInt((String)((DynaActionForm) form)get(test))
Place this after the line ldquoDivisionBO divisionBO = new DivisionBO()rdquo DivisionBean divisionBean = divisionBOfindByPrimaryKey(divNo)
Complete code (comffictrainingFindDivisionAction)
import orgapachestrutsaction
import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException
import javaioIOExceptionimport javautil
Insert the types description here Creation date (12402 23818 PM) author Administrator public class FindDivisionAction extends orgapachestrutsactionAction
Insert the methods description here Creation date (12402 24105 PM) public ActionForward execute(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response)throws Exception
246
ActionErrors errors = new ActionErrors()
int divNo = IntegerparseInt((String)((DynaActionForm) form)get(test))
DivisionBO divisionBO = new DivisionBO()DivisionBean divisionBean = divisionBOfindByPrimaryKey(divNo)requestsetAttribute(divFormdivisionBean)
return mappingfindForward(editpage)
Notice in the above code that the way the DynaActionForm is used to retrieve itrsquosproperty is different from using a regular bean for the ActionForm
Deploying the code (Part 1 ndash DynaActionForm example)1 Bring up WTE in VAJ and start the servlet engine2 Start the Persistent Name Server3 Bring up IE 55 (forget NS 45 for now) and type the following url in the address line
httplocalhost8080craftLoginjsp
4 Enter a valid email address and a password then select the link Search Divisionfrom the menu in the welcome page
Result (Part 1 ndash DynaActionForm example)The result should be as follows
The search page (the field is now blank instead of 0 since we declared a type of String forthat field in the DynaActionForm)
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
247
If the user submits it with a blank value in the division code field the correct errormessage will be displayed as in the screen below
If the user enters a non-existent division code then the correct error message will bedisplayed
248
If the user enters a valid division code then the result will be displayed in the edit page
PROJECT CORPORATE COLLECTIONS WEBAuthor Raffy Lata Created on 042402 304 PMTitle Web Application Programming using StrutsDescription Discusses basic concepts on web server configuration java technologies andapplication development using the Struts framework and itrsquos extensions
249
Coding (Part 2 ndash DynaValidatorForm example)As discussed in the first part of this lesson we will revise the login process to use asubclass of the DynaActionForm DynaValidatorForm to replace the login form This willallow the login process to continue using the struts-validator to validate the userid andpassword fields
1 To start of define the following entries in the struts-configxml in craftWEB-INF
ltform-bean name=logonForm type=orgapachestrutsvalidatorDynaValidatorFormdynamic=truegt
ltform-property name=userId type=javalangStringgtltform-property name=password type=javalangStringgt
ltform-beangt
2 Change the entry for the login action to use the dynamic form
ltaction path=login type=comffictrainingLoginAction name=logonForm scope=requestinput=Loginjspgt
ltforward name=success path=welcomepagegtltactiongt
3 Open the file WelcomeContentjsp located in craft and change the form name fromloginForm to logonForm in the ltbeanwritegt tag
ltbeanwrite property=userId name=logonForm gt
4 Next is to revise the class LoginAction to use the DynaValidatorForm so make thefollowing changes to this class
Add the following import statement
import orgapachestrutsvalidator
Comment out the following line of code
LoginForm loginForm = (LoginForm) form
Replace the following line
errors = loginFormvalidate(mappingrequest)
with
errors = ((DynaValidatorForm)form)validate(mappingrequest)