PROJECT : Struts Training Raffy Lata Web Application Programming

285
PROJECT : Struts Training Author: Raffy Lata Created 04/24/02 3:04 PM Title : Web Application Programming using Struts Description : Discusses basic concepts on web server configuration, java technologies and application development using the Struts framework and it’s extensions. 1 Lesson 1 - ORION webserver configuration 5 Preparation 5 Installation 5 Configuration 6 Review 8 Lesson 2 - VisualAge for JAVA/WebSphere Test Environment configuration 9 Installation 9 Configuration 9 Usage 11 Lesson 3 - Servlet primer 13 Basics 13 Your first servlet 14 Deploying the code 15 Lesson 4 - Database Connectivity 17 Preparation 17 Coding 17 Deploying the code 20 Lesson 5 - Servlet/Database Connectivity 23 Preparation 23 Coding 25 Deploying the code 28 Lesson 6 - Servlet Redirection 31 Basics 31 Preparation 32 Coding 32 Deploying the code 33 Result 34 Lesson 7 - JavaBeans 36 Basics 36 Coding 36 Deploying the code 39 Result 40 Lesson 8 - Object Scope 42 Basics 42 Coding 42 Deploying the code 45 Result 46 Lesson 9 - Java Server Pages (JSP) 47 Basics 47

Transcript of PROJECT : Struts Training Raffy Lata Web Application Programming

PROJECT Struts TrainingAuthor Raffy Lata Created 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

1

Lesson 1 - ORION webserver configuration 5Preparation 5Installation 5Configuration 6Review 8

Lesson 2 - VisualAge for JAVAWebSphere Test Environment configuration 9Installation 9Configuration 9Usage 11

Lesson 3 - Servlet primer 13Basics 13Your first servlet 14Deploying the code 15

Lesson 4 - Database Connectivity 17Preparation 17Coding 17Deploying the code 20

Lesson 5 - ServletDatabase Connectivity 23Preparation 23Coding 25Deploying the code 28

Lesson 6 - Servlet Redirection 31Basics 31Preparation 32Coding 32Deploying the code 33Result 34

Lesson 7 - JavaBeans 36Basics 36Coding 36Deploying the code 39Result 40

Lesson 8 - Object Scope 42Basics 42Coding 42Deploying the code 45Result 46

Lesson 9 - Java Server Pages (JSP) 47Basics 47

2

Coding 48Deploying the code 51Result 52

Lesson 10 - Custom Tags 53Basics 53Coding 55Deploying the code 57Result 58

Lesson 11 - Model-View-Controller Design Pattern 59Basics 59

Lesson 12 - Introduction to the Struts Framework 62Struts Components 63ldquoI canrsquot find the MVC pattern anywhererdquo 65

Lesson 13 - Installing Struts 11b in VisualAge for Java 40WebSphere TestEnvironment 353 77

Installation and configuration 77Installing the sample application 79Deploying and running the sample application 90Result 90

Lesson 14 - Installing Struts 11b in ORION 92Installation and configuration 92Installing the sample application 93Deploying and running the sample application 96Result 96

Lesson 15 - Struts Components 98Struts Components 98Tag Libraries 106Useful Links 110

Lesson 16 - Building a simple web application using Struts 111Basics 111Coding 111Deploying the code 117Result 118

Lesson 17 ndash Validating form values 120Basics 120Installation 120Coding 121Deploying the code 127Results 128

Lesson 18 ndash Nested Beans 130

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

3

Basics 130Installation 130Coding 130

Lesson 19 ndash Creating reusable screen components 141Basics 141Coding (Part 1) 141Deploying the code (Part 1) 144Results (Part 1) 145Coding (Part 2) 147Deploying the code (Part 2) 150Result (Part 2) 150Coding (Part 3) 150Deploying the code (Part 3) 152Result (Part 3) 152

Lesson 20 ndash Creating reusable menu components 153Basics 153Installation 153Coding 156Deploying the code 160Result 160

Lesson 21 ndash Connection Pooling 163Basics 163Coding 163Deploying the code 169Result 169

Lesson 22 ndash Creating a singleton to maintain the connection pool 171Basics 171Coding 171Deploying the code 183Result 183

Lesson 23 ndash Data Access Objects 186Basics 186Coding 186Deploying the code 192Result 192

Lesson 24 ndash Business Objects 195Coding 195Deploying the code 212Result 212

Lesson 25 ndash Action subclasses 216Coding 217Deploying the code 225

4

Result 225

Lesson 26 ndash Exception handling 229Basics 229Coding (Part 1 ndash programmatic exception handling) 231Deploying the code (Part 1 ndash programmatic exception handling) 234Result (Part 1 ndash programmatic exception handling) 235Coding (Part 2 ndash using declarative exception) 238Deploying the code (Part 2 ndash using declarative exception) 242Result (Part 2 ndash using declarative exception) 242

Lesson 27 ndash Creating dynamic forms 243Basics 243Coding (Part 1 ndash DynaActionForm example) 243Deploying the code (Part 1 ndash DynaActionForm example) 246Result (Part 1 ndash DynaActionForm example) 246Coding (Part 2 ndash DynaValidatorForm example) 249Deploying the code (Part 2 ndash DynaValidatorForm example) 251Result (Part 2 ndash DynaValidatorForm example) 251

Lesson 28 ndash Using tokens 254Basics 254Coding 254Deploying the code 256Result 256

Lesson 29 ndash Implementing security in Struts 260Basics 260Coding (Part 1 ndash protecting do classes) 261Deploying the code (Part 1 ndash protecting do classes) 276Result (Part 1 ndash protecting do classes) 277Coding (Part 2 ndash protecting jsp pages) 280Deploying the code (Part 2 ndash protecting jsp pages) 283Result (Part 2 ndash protecting jsp pages) 283

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

5

Lesson 1 - ORION webserver configurationThis document lists the steps to install the ORION webserver on your workstation (andrun it of course) I picked ORION since Irsquom more familiar with it than Tomcat or Resinetc The entire thing should take about an hour to accomplish I can either walk youthrough the installation or you can just follow these steps yourself and if I didnrsquot missanything have it running in no time Once yoursquore familiar with it I can then walk youthrough the configuration of WebSphere Test Environment in VAJava and we can talkabout the differences between WTE and the rest of the J2EE webappservers

PreparationThe following steps will install the java toolkit in your workstation Yoursquoll need this tocompile andor run stand-alone java programs outside of VAJava

1 Download the java sdk from httpjavasuncomj2se13downloadhtml (selectWindows (all languages) and click the download link under the SDK column)

2 Accept the license and proceed with the download (place it in your favorite folder)3 Run the downloaded executable file j2sdk-1_3_1_03-winexe and unzip it in E (it

should unzip the contents under ejdk131_03)4 Go to your desktop and right-click on My Computer and bring up the properties5 Click on the Environment tab6 Enter the following

Variable JAVA_HOMEValue ejdk131_03

7 Click on OK

Installation1 Download ORION from httpwwworionservercom

on the left-side nav of the screen click on Stable binaries under the Downloadsection

save the file to your favorite local directory

2 Open the downloaded file orion152zip and extract the contents to eorion (thisfolder will be automatically created when you check the ldquoUse foldersrdquo option inWinZip)

3 This is from the orion docscopy toolsjar from ejdk131_03lib into eorion tomake jsprsquos work

6

ConfigurationCreate a J2EE compliant directory structure To do this follow the steps

1 Create the following directory Eservletscraft This will be your applicationrsquos rootdirectory

2 Under the craft folder create the following directory structure

craft|___images|___WEB-INF

|___classes|___libFolder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

3 Create a file named webxml and save it in eservletscraftWEB-INF then pastethe following code

ltxml version=10gtltDOCTYPE web-app PUBLIC -Sun Microsystems IncDTD Web Application22EN httpjavasuncomdtdweb-app_2_2dtdgt

ltweb-appgt

ltweb-appgt

This file contains the applicationrsquos configuration information Right now itrsquos empty but thewebserver still expects to find this file or else it wonrsquot startup the application

4 To let ORION know about your new application (the one you just created above) youneed to enter some stuff in the ORION xml files To do this

go to EORIONCONFIG open applicationxml using a text editor enter the following information (in bold) right after the tag ltweb-module

id=rdquodefaultWebApprdquo path=rdquodefault-web-apprdquo gt

lt-- --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

7

ltweb-module id=rdquoCRAFTrdquo path=rdquoEservletscraftrdquo gtlt-- --gtltpersistence path=rdquopersistencerdquo gt

save and exit the file open default-web-sitexml again using a text editor enter the following information (in bold)

lt-- The default web-app for this site bound to the root --gtltdefault-web-app application=rdquodefaultrdquo name=rdquodefaultWebApprdquo gt

lt-- --gtlt-- get name from applicationxml ltweb-module id=rdquothis will be the namerdquopath=rdquocrdquogt --gtltweb-app application=rdquodefaultrdquo name=rdquoCRAFTrdquo root=rdquocraftrdquo gt

lt-- --gt

saveexit the file

5 Go to the command prompt and go to eorion

6 Start the server by typing java -jar orionjar on the command line

7 If everything was setup properly you should see the message Orion152 initialized

8 Create an html file named pagehtml and save it in Eservletscraft then pastethe following code

lthtmlgtltheadgt ltheadgtltbodygtltdiv align=centergtlth1gtHELLO WORLDlth1gtltdivgtltbodygtlthtmlgt

9 To test your webserver

bring up a browser (IE or NS) type in httplocalhostcraftpagehtml You should see proverbial HELLO

WORLD on your browser

8

(Hint While Windows itself is not case-sensitive unlike AIX the URL should thatyou type in the browserrsquos address line should match the entry in the xml file)

10 Congratulations yoursquore a survivor

ReviewThe following information is worth rememberingDIRECTORY STRUCTURE

craft|___images|___WEB-INF

|___classes|___lib

Folder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

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

9

Lesson 2 - VisualAge for JAVAWebSphere TestEnvironment configurationThis is a minimalist instruction on how to configure your WebSphere Test Environment(WTE) in VAJava to start serving web applications It walks you through the steps increating a CRAFT application and testing the setup to make sure that is runs It shouldtake an hour (or more) to complete this exercise

InstallationInstall VAJava 40 (easy to say huh) You should already have it in your workstationCheck that the WebSphere Test environment is installed in VAJ By selectingWorkspaceToolsWebSphere Test Environment VAJ should tell you if itrsquos there or not If not

Select FileQuick StartSelect FeaturesAdd FeatureSelect WebSphere Test Environment 353 from the list and click OK

Configuration1 Create the following directory structure under eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_host (whew)

craft|_images|_WEB-INF

|_classes

Folder Descriptions

craft - root directorycontains html and jsp filesimages - contains image filesWEB-INF - is not automatically recognized by WebSphere but wersquoll create this so wecan create a pseudo-J2EE directory structureclasses - again not automatically recognized by WebSphere wersquoll create this for thesame reason as the previous folder

2 Create a file craftwebapp and put the following text in the file

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegt

10

ltservletgtltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtinvokerltnamegtltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegt

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

11

ltvaluegtindexhtmlltvaluegtltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

3 To let WTE know about your new application go to the directory eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmentproperties and open the file defaultservlet_engine using a text editorAdd the following text

Look for this tag ltwebsphere-servlet-host name=rdquodefault_hostrdquogt and paste the followingtext right after it

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

UsageThis section will walk you through how to test if your WTE configuration is correctly setup1 Create a file named indexhtml and save it in eappsprogram

filesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft then paste the following code

ltHTMLgtltHEADgtltMETA NAME=GENERATOR Content=NetObjects ScriptBuilder 30gtltTITLEgtWebSphere Test Environment Index PageltTITLEgtltHEADgtltBODYgtlth1gtThis is the index page for the WebSphere Test Environmentlth1gtltBODYgtltHTMLgt

2 Bring up VAJava

3 Select WorkspaceToolsWebSphere Test Environment

4 Click on Start Servlet Engine

12

5 When the message at the lower left says ldquoServlet engine is startedrdquo bring up abrowser

6 Type in this URL httplocalhost8080craft

If the installation is successful yoursquoll get the following message on your browser This is the index page for the WebSphere Test Environmentif not wersquoll take a look at your problem

7 Thatrsquos itnow on to greater 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

13

Lesson 3 - Servlet primerHerersquos the next installment on the web-application development crash-course You willcreate your first servlet which will hopefully give you a basic understanding of whatservlets are and how they work I gave examples on how to deploy the code both in VAJWTE and in Orion so you can continuously compare the two web environments This willgo on for the next few lessons and then when we get to Struts wersquoll just retain theWebSphere Test Environment which is where we should be developing our codes

BasicsServlet

body of java code that extends a java-enabled serverrsquos functionality listens to requests and usually sends back a response to the client Can also pass

processing on to other servlets does not have a main() method so it cannot run outside of the servlet container to create a servlet we generally extend the class HttpServlet which is a subclass of

GenericServlet HttpServlet makes use of the HTTP protocol

Servlet life-cycle

An HttpServlet contains the following methods

init() doGet()doPost() destroy()

When a servlet is first invoked the servlet container calls the servletrsquos init() method thenit calls either the doGet() or doPost() method

For subsequent requests only the doGet() or doPost() method is called A separatethread is created for every doGet()doPost() invocation so different requests will not runinto each other We place the majority of our code in either of these methods

When the servlet container is shutdown it calls the servletrsquos destroy() method

RequestResponse paradigm

Uses HTTP which is a stateless protocol

In itrsquos simplest form

client sends a request and servlet receives request (and response) object which mayhave objects attached to it (parameters or attributes RemoteUser etc)

14

servlet processes the request (access a db contruct an html response forward toanother servlet etc)

client receives some form of response from the servlet and renders the output to the browser

Your first servletIn VAJ

1 Create a project named TRAINING2 Create a package named comffictraining3 Create a class named HelloWorldServlet4 Add these codes to HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

Code Walkthrough

1 To make HelloWorldServlet a servlet it needs to extend HttpServlet

public class HelloWorldServlet extends HttpServlet

2 We will then need to implement one of the following methods

doGet()doPost()

In this example we implemented the doGet() method

public void doGet(HttpServletRequest 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

15

3 Inside the doGet()

we set the content type for the response to texthtml since we intend to send back anhtml response

responsesetContentType(ldquotexthtmlrdquo)

4 We then retrieve the PrintWriter from the response so we can start writing our outputto it

PrintWriter out = responsegetWriter()

5 Lastly we start writing our output

outprintln(ldquolth1gtHello worldlth1gtrdquo)

After executing the last line of code the servlet returns control back to the web containerwhich sends the response back to the client Since we added stuff in the response theclientrsquos browser will attempt to render it

Deploying the codeVAJava (WebSphere Test Environment)

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (this can be the last entry just beforethe

ltwebappgt tag)

ltservletgtltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

Orion

16

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgtltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in ldquoHello Worldrdquo being displayed on your browser

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

17

Lesson 4 - Database ConnectivityBefore we move on to other web components we need to briefly go through the topic onconnecting to a database and retrieving information from the tables This will make thenext few topics a lot more interesting since you will be displaying data on the browser thatwere retrieved straight off of the db instead of flooding your servlet with ldquoset-this set-thatvaluerdquo lines of codes

After going through this exercise it will become more obvious that this is not the real-world way of creating and maintaining connections to a database Creating a connectionfor each sql to be executed is a pretty expensive operation In later exercises we willexplore how to create a pool of connections using DataSource and the methods withwhich this datasource is maintained and accessed (the FFIC way of course)This section discusses the java code required to connect to a database and execute sqlto retrieve data

Preparation1 You should have the IOU database information entered in your UDB-client with the

following details

DB Alias = IOUODBC entry = IOU (not really needed in this exercise but check it anyway)

2 We will be using the DB2 driver to create the connection to our database If youhavenrsquot done so import the db2javazip file into your VAJ ide

create a DB2 DRIVER project import db2javazip from EAPPSSQLLIBjava into your newly created project

using the following option ldquoimport as a Jar filerdquo

3 For ORION copy the file db2javazip to EservletsORIONcraftWEB-INFliband rename it to db2javajar

CodingIn your TRAINING project create a class JDBCSample in the comffictraining packageand paste the following code in it

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcapp

18

import javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(ldquoDivision ldquo + ldquoCoderdquo + ldquo ldquo + ldquoDescriptionrdquo) while (rsnext())

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

19

String s = rsgetString(1)String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

CODE WALKTHROUGH

1 We need to import the following packages so the program can load the necessaryjdbc classesdrivers

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

2 We define variables for the sql to execute and the useridpassword needed to accessthe database Obviously you must change the userpassword if you have a differentone We also specify here the driver that we will use to create a connection to thedatabase (DB2 in this case)

String query = ldquoSELECT FROM IOUDIVISIONrdquoConnection conn = nullStatement stmt = nullString user = ldquoiccw0t00rdquoString password = ldquoiccw0t00rdquoString driver = ldquoCOMibmdb2jdbcappDB2Driverrdquo

3 This trycatch block attempts to load the database driver and create a connection

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)

20

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)

4 When a connection is successfully created the next trycatch block creates aStatement from the connection and executes the sql that we defined earlier

try 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 )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

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 JDBCSample class and select Run

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

21

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 JDBCSample 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

The output should look similar to the following

loading driverconnectingtojdbcdb2IOUconnectedDivision Code Description1 CID Involuntary 2 CID Voluntary 3 PID 4 CID Specialty 10 National Accounts 11 Jefferson Insurance 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

22

END

NEXTLetrsquos try what we just learned using our servlet example

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

23

Lesson 5 - ServletDatabase Connectivity From the last two lessons you learned to a) construct a simple servlet and b) create ajava program that retrieves data from a database Now we will combine the two andcome up with a servlet that accesses the database and displays the result (ResultSet) ona browser

PreparationRemember your two previous programs If not here are the source codes

HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServletpublic void doGet(HttpServletRequest request

HttpServletResponse response)throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

JDBCSample

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

24

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try 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 )

stmtclose()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

25

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

Before you proceed briefly review how each of the programs work so it will be mucheasier to understand the codes belowthatrsquos all

CodingWith a little tweak (additional codes) the code below shows a combined version of thetwo programs we previously created You can cut and paste it in your HelloWorldServletin VAJ

The blue portion is the HelloWorldServlet while the red portion shows theJDBCSample

You will also notice that there are codes in green These lines of codes were added toaccomodate the codes for JDBCSample and to properly display the output to thebrowser

import javaioimport javaxservletimport javaxservlethttp

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

public class HelloWorldServlet extends HttpServletString query = SELECT FROM IOUDIVISIONConnection conn = nullStatement stmt = nullString user = iccw0t00String password = iccw0t00String driver = COMibmdb2jdbcappDB2Driver

HelloWorldServlet constructor comment

26

public HelloWorldServlet()

super()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() outprintln(lth1gtHello worldlth1gt)

try

stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(Division Code + + Description) outprintln(lth2gtDivisionlth2gt) outprintln(lth3gtCode Descriptionlth3gt)

while (rsnext()) String s = rsgetString(1)

String ln = rsgetString(2) Systemoutprintln(s + + ln )

outprintln(lth3gt + s +ampnbspampnbspampnbspampnbspampnbspampnbspampnbsp + ln + lth3gt)

stmtclose()

conclose()

catch(SQLException ex) Systemerrprintln(SQLException + exgetMessage())

Insert the methods description here Creation date (42402 22142 PM) public void init()

try Systemoutprintln(loading driver) ClassforName(driver) String url = jdbcdb2IOU Systemoutprintln(connectingto + url) conn = DriverManagergetConnection(urluserpassword) Systemoutprintln(connected)

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

27

try catch(ClassNotFoundException ex) Systemoutprintln(Couldnt load jdbc driver) Systemoutprintln(ex) catch(SQLException ex) Systemoutprintln(Database Problem) Systemoutprintln(ex) catch(Exception ex) Systemoutprintln(Some other problem) Systemoutprintln(ex)

CODE WALKTHROUGH

Irsquove pretty much gone through the codes line by line in the previous lessons What needs to be mentioned here is that a method called init() was added and the codesthat load the DB2 driver and create the connection were added here

Insert the methodrsquos description hereCreation date (42402 22142 PM) public void init()

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

28

Systemoutprintln(ex)

When a servlet starts up the first thing it looks for is an init() method and it executes thismethod once within itrsquos lifetime It is good practice to place initialization stuff in thismethod especially when we only need to run these once A good example is creating aconnection to the database and this is just what we did with this exampleNote As with the init() method a servlet also has a destroy() method which is calledwhen it shuts down

Deploying the codeDeploying the code to VAJ and ORION is the same as in the servlet lesson I listed ithere again just in case you donrsquot have that lesson anymore

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (can be the last entry just before the ltwebappgt tag)

ltservletgt

ltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

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

29

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in the following output on your browser

30

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

31

Lesson 6 - Servlet RedirectionThis lesson briefly covers one of the more important features of servlets which isforwarding or redirecting In simple terms redirection is passing control to another entitywhich can be a servlet html or jsp at the same logical level It works pretty much like anxctl in CICS with some differences There are two types of redirection client-side andserver-side and these are described in the following section

BasicsClient-side redirection

The redirection happens at the client-side and the URL on the browserrsquos address linechanges to the URL that was sent to it User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and sends a message

(redirect) to the browser containing a URL which the browser will load The browser receives the redirect from the servlet and loads the URL that was sent

to it

Note The URL in the redirect can be another servlet html or a jsp file

To illustrate this process

BROWSER==gtservlet==gtBROWSER==gtresult(jsphtmlservlet)

Client-side redirection is useful when after a servlet processes you want to navigate theuser to another page where even if he reloads that result page will not cause the servletto re-execute In other words the user is navigated to a safe place where he canrsquot hurthimself or the application

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoresponsesendRedirect(url)

if you want to retrieve the original URL to redirect the servlet to itself do this

String url = requestgetRequestURI()responsesendRedirect(url)

Note the getRequestURI() method leaves out the parameters if any that wereincluded in the original URL You can use the requestgetParameter() to retrieve theparameters and attach them to the url

32

Server-side redirection

The redirection happens only at the server-side and the browser does not know anythingabout it The URL on the browserrsquos address line does not change

User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and forwards itrsquos output to

another servlet jsp or html The receiving sevlet jsp or html renders the output to the browser

To illustrate this process

BROWSER==gtservlet==gtresult(jsphtmlservlet)

Server-side redirection is used to combine several operations to make them appear asone without involving the clientrsquos browser This cuts down traffic between the server andthe browser The browser will receive the result only after the last of the processes hasreleased the output to the web container

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

PreparationThis exercise involves server-side redirection The idea is to have one servlet receive therequest from the browser and perform a redirect to another servlet which will retrieve datafrom a db and construct the html output to be rendered on the browserWe will need the HelloWorldServlet servlet for this exercise which will act as the receivingservlet All we need to contruct is the servlet that will forward the processing toHelloWorldServlet

CodingIn VAJ create a new class called ControllerServlet in the package comffictraining andpaste the following code to it

import javaioimport javaxservletimport javaxservlethttp

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

33

public class ControllerServlet extends HttpServletpublic void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionString url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

1 We define ControllerServlet as a servlet by extending HttpServlet

public class ControllerServlet extends HttpServlet

2 These lines construct the URL of the receiving servlet and performs the redirection

String url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtControllerltnamegtltdescriptiongtDB access servletltdescriptiongtltcodegtcomffictrainingControllerServletltcodegtltautostartgttrueltautostartgt

ltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

34

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtControllerltservlet-namegtltservlet-classgt

comffictrainingControllerServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

35

You can verify that the servlet did a server-side redirect if the URL on the browserrsquosaddress line did not change It should still show

httplocalhost8080craftservletController for WTE

or

httplocalhostcraftservletController for ORION

WATCH OUT NEXT FORJAVA BEANS

36

Lesson 7 - JavaBeansUp to this point we have been dealing mostly with webserver configuration andprocedural java codes In this lesson we will start to incorporate object orientation in ourexamples using javabeans

BasicsIn our example programs we created data in our servlet by retrieving information fromthe database and by assigning values to variables There will be times when we want topass this data around and manipulate them before we send them to the browser fordisplay A convenient way of doing this is to encapsulate all these related informationhide them in an object and provide methods to access each value To accomplish thiswe create a java class called javabean or bean that contains only private variables andsettergetter methods for each of these variables For instance we can create a bean called divisionBean and store each row that weretrieve from the database to a divisionBean instance We can then put all these beansinside a collection object that we can pass around and eventually render to the browserSounds confusing Letrsquos do an example then

Coding1 In VAJ create a class called DivisionBean in comffictraining package and paste the

following in it

public class DivisionBean private String divNoprivate String divDesc

public String getDivDesc()return divDescpublic String getdivNo()return divNopublic void setDivDesc(String divDesc)thisdivDesc = divDescpublic void setDivNo(String divNo) thisdivNo = divNo

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

37

2 Open your HelloWorldServlet and make the following changes

Add the following code right after the class declaration

ArrayList divList = new ArrayList()

In the doGet() method

delete the following lines or better yet just comment them out (ie put a beforeeach line)

String s = rsgetString(1)

String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )outprintln(ldquolth3gtrdquo + s + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + ln + ldquolth3gtrdquo)

add the following lines within the while loop

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

after the while loop add the following lines of code

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

Code Walkthrough

DivisionBean

1 We defined the two variables divNo and divDesc as private to prevent them frombeing accessed directly (ie divisionBeandivNo)

private String divNoprivate String divDesc

38

2 We then define getters and setters for the two variables

public String getDivDesc()

return divDesc

public String getdivNo()

return divNo

public void setDivDesc(String divDesc)

thisdivDesc = divDesc

public void setDivNo(String divNo)

thisdivNo = divNo

HelloWorldServlet

1 We defined an Arraylist (called divList) which part of the java collections to containthe instances of the beans that we create

ArrayList divList = new ArrayList()

2 In the while loop we instantiate a new divisionBean and set itrsquos variables to thevalues that we retrieve from the db The we add that instance to divList

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

3 After wersquove gone through the entire resultset we loop through divList and create anhtml output for each instance of the bean in the ArrayList The code provided here ispretty much boiler plate code

retrieve an interator from divList (all collections have an interator)

Iterator iterator = divListiterator()

the interator has methods that loop through the ArrayList object (hasNext()) andto retrieve each item (next())

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

39

while (iteratorhasNext())

when an item is retrieved it has to be cast back to the original object In thiscase we cast the item back to DivisionBean

DivisionBean divbean = (DivisionBean) iteratornext() outprintln(ldquolth3gtrdquo +divbeangetDivNo() + ampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +divbeangetDivDesc() + ldquolth3gtrdquo)

Enhancement idea

You may ask ldquoWhy put more code that does the same thing as the originalrdquo

The answer is that creating beans and storing them in collections (or even if you justhave a single bean) enables you to attach this object to for example the request object(ie requestsetAttribute(ldquodivisionListrdquodivList)) and perform a forward to another servletthat contains code (such as the while loop with the iterator) that performs the creation ofthe output to the browser In this case the components can be further divided into thefollowing

ControllerServlet - receives the request from the browser and forwards it toHelloWorldServlet

HelloWorldServlet - retrieves data from the db stores the results inbeanscollection attaches the collection to the request object then performs aserver-side redirect to another servletjsp which we can call DisplayServletDisplayServlet - retrieves the collection from the request object and builds thehtml output while iterating through the collection

This approach enables you as the programmer to assign specific tasks to eachcomponent and keep them loosely coupled so that you can easily change onecomponent without making massive changes to the rest of your application As anexample you can change HelloWorldServlet to access another database (other thanDB2) without affecting the two other servlets in the chain

Deploying the codeVAJ

1 Bring up WTE and start the servlet engine

2 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

40

ORION

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Start ORION (eORIONjava -jar orionjar)

3 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

41

42

Lesson 8 - Object ScopeThis lesson is a sidetrip to learning the concept of object scope We need to cover thisimportant topic before we head on to JSPrsquos (are we there yet)

BasicsIn the previous lesson we learned to create javabeans and put them in a collection(called divList) to be processed by another set of codes within the same servlet We alsotoyed with the idea of creating another servlet (DisplayServlet) that will construct the htmloutput from this collection Since we want to pass the collection from HelloWorldServletto DisplayServlet we need to somehow associate the collection object with a particularscope When we perform a server-side redirect the request and response objects arepassed as arguments in the forward method Before we actually forward the process toanother servlet we make sure that we associate the collection object to the requestobject so that the receiving servlet can access that collection This is an example of anobject scope and in this instance we defined the collection to be in the request scope

A simple definition of Object Scope is the level of availabilityvisibility of an object withinthe application

It can be any of the following

page - object is visible in the page that created itrequest - object is visible in the request to which is belongssession - object is visible in the same session where it was created application - object is visible within the entire application Any servlet regardless of

what session created them can access the object in this scope

To associate an object to a particular scope we use the setAttribute() method If we want to say make the divList collection available to a userrsquos session we use thefollowing code

HttpSession session = requestgetSession(true)sessionsetAttribute(ldquodivListrdquodivList)

so long as the session still exists we can extract that collection at any point within theapplication with the following code

HttpSession session = requestgetSession(true)ArrayList divList = (ArrayList) sessiongetAttribute(ldquodivListrdquo)

Note We have to cast the collection back to itrsquos original form which is an ArrayList

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

43

Letrsquos create the DisplayServlet that we discussed in the previous lesson

1 Create a class called DisplayServlet in your TRAINING project in the packagecomffictraining and paste the following

import javaioimport javaxservletimport javaxservlethttp

import javautilpublic class DisplayServlet extends HttpServlet

ArrayList divList = new ArrayList()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionresponsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCodeDescriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() +ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

2 Open HelloWorldServlet and make the following changes

comment out the following lines of code in the doGet() method

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCode Descriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +

44

divbeangetDivDesc() + ldquolth3gtrdquo)

add the following lines of code after the stmtclose() line

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

Display Servlet

1 We define DisplayServlet by extending HttpServlet

public class DisplayServlet extends HttpServlet

3 Define an ArrayList to contain the collection that this servlet will receive fromHelloWorldServlet

ArrayList divList = new ArrayList()

4 Set the content type and get the output writer from the response so we can startwriting output data to it

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()

5 Retrieve the divList collection from the request object and cast it back to an ArrayList

divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)

6 Create the html output while iterating through the collection

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

HelloWorldServlet

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

45

1 The lines that we removed from this servlet were transferred to DisplayServlet

2 In the lines that we added we associate the divList collection with the request objectand then do a server-side redirect to DisplayServlet

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquo

RequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtDisplayltnamegtltdescriptiongtDisplay Outputltdescriptiongt

ltcodegtcomffictrainingDisplayServletltcodegtltautostartgttrueltautostartgtltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtDisplayltservlet-namegtltservlet-classgt

comffictrainingDisplayServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

46

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

47

Lesson 9 - Java Server Pages (JSP)BasicsIn the previous lessons we had been constructing our html response within the servletitself It works well with simple html outputs but later on as your webpages get morecomplicated you will find (or you may already have) that this will not work for real-worlddevelopment Java Server Pages (JSP) technology was introduced to make life easier forus programmers and for web designers How If yoursquore familiar with HTML JSP isbasically an html page with little (thatrsquos the plan) java code You get to construct your htmlpage as you normally would and start putting in java logic to a) iterate through acollection of beans b) to include output from another jsp and more To create a jsp filefrom a static html file simply change the filersquos extension from html to jsp and yoursquoreready to go But wait therersquos moreBefore we move on also remember that a jsp is first converted and compiled into aservlet by the web container before it is executed so it will have a similar life cycle as thatof a servlet Inside the jsp file we can put java codes to create dynamic output on thebrowser We accomplish this by using scriptlets expressions declarations and directiveswhich are described below

Scriptlet lt

Scriptlets are regular java codes that are automatically executed by the jsp containerwhen the jsp is invoked so they should be syntactically correct

lt String i = ldquofoordquoSystemoutprintln(i)

gt

Expression lt=

Expressions evaluate to a value that is directly displayed on the browserlt= i gt

The example is converted to outprintln(i) by the jsp container and the value of ldquoirdquo isdisplayed on the browser

Declarations lt

Declarations are java codes that are not automatically executed by the jsp container butmay be invoked if you call it from a scriptlet

lt static printName (String name) Systemoutprintln(name)

gt

48

You can invoke this by writing a scriptlet such as

lt printName(ldquoMyNamerdquo) gt

Directives lt

Directives desribe the necessary components of a jsp

lt page import=rdquojavautilcomffictrainingrdquo gt ==gt imports necessary packageslt taglib uri=rdquobeanrdquo prefix=rdquobeanrdquo gt ==gt declares a taglib referencelt include file=rdquoextraInfojsprdquo gt ==gt includes output from another jsp file

Coding

Suppose the web designer (if there is one) hands you this html file (DisplayDivhtml) lthtmlgtltbodygtlttable border=1gt

lttr align=left gtltthgtDivision IDltthgtltthgtDescriptionltthgtlttrgtlttr align=leftgtlttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgtlttdgt2lttdgtlttdgtCID Voluntarylttdgtlttrgt

lttablegtltbodygtlthtmlgt

The browser output looks like this

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

49

So you the java programmer need to convert this layout to a dynamically generated htmlfile

KNOWN

The data will come from the IOUDIVISION table You already have the servlets (ControllerServlet and HelloWorldServlet) necessary to

perform data retrieval from the db You have a DisplayServlet servlet that creates html output but you want to use a jsp

since you already have the html code and you just need to insert the necessary javacodes to render the dynamic output correctly

HINT We created javabeans (DivisionBean instances) containing Division information and

put them in a collection (divList) that is associated with the request object In our jsp file we can retrieve this collection and iterate through them pretty much the

same way we did with DisplayServlet So most of the codes that we have inDisplayServlet can be reused in the jsp file

Code Walkthrough

1 If you saved the above code in DisplayDivhtml simply rename it to DisplayDivjsp tomake it a jsp file

2 At the topmost portion paste the following code

lt page import=rdquojavautilcomffictrainingrdquo gt

This tells the jsp page that your scriptlets will be looking for necessary classes in thesepackages

3 To display the division code and description we have to insert codes that iteratethrough the collection and render them inside the table

Just after the table header definition (The ones with the ltthgt ltthgt tags) make thefollowing changes

delete the following lines of codes since these are just representations of what thedynamic portion of the page are

lttr align=leftgt

lttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgt

lttdgt2lttdgt

50

lttdgtCID Voluntarylttdgtlttrgt

insert the following codes

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()gt

Notice that this is strikingly similar to the code in DisplayServlet Thatrsquos because we justcut and paste it from there Even though the loop is not yet complete we terminated these lines of code with a ldquogtrdquo because we need to pasteregular html tags or non-java codes right after it

4 Once the above code starts iterating through the collection we need additional codesto render the details so paste the following code right after it

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

Here we used expressions to execute the ldquogetrdquo methods of the DivisionBean instance toretrieve the division code and description

5 Now this is where most beginners get bit We need to properly terminate the ldquowhilerdquoloop that we started in the previous steps To do this paste the following code rightafter the previous step

lt End whilegt

The completed code looks like the following

lt page import=rdquojavautilcomffictrainingrdquo gtlthtmlgtltbodygtlttable border=1gt

lttr align=leftgtltthgtDivision IDltthgtltthgtDescriptionltthgt

lttrgt

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

51

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()

gtlttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End whilegt

lttablegtltbodygtlthtmlgt

HelloWorldServlet

Open HelloWorldServlet and make the following changes

1 Remove the following line of code

String url = ldquoservletDisplayrdquo

2 Replace it with the following line of code to forward the process to DisplayDivjspinstead of DisplayServlet

String url = ldquoDisplayDivjsprdquo

Deploying the codeVAJ

1 Be sure to save DisplayDivjsp in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

52

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Save the DisplayDivjsp file in eservletscraft3 Start ORION (eORIONjava -jar orionjar)4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

53

Lesson 10 - Custom TagsBasicsIn Lesson 9 you learned how to create a JSP to handle content rendition in place of aservlet Wersquove seen how the same codes that we used in the servlet can be re-appliedinside the JSP using scriptlets expressions declarations and directives Again as yourJSPs get more complicated you will want to reduce the amount of java codes in themespecially codes or logic that are candidates for re-use in other JSPs In our exampleprogram if you want the logic that displays the Division information in more than oneJSPs you may want to put that body of code in a central place where you can just call itfrom different JSPs Otherwise you will end up copyingpasting the same codes in everyJSP that needs these codes

Starting with JSP 11 a feature was introduced wherein java codes can be encapsulatedand represented on the JSP using custom tags Custom tags are not unlike HTML tags(ie lthtmlgt ltformgt lttablegt etc) except that we provide the logic that makes the tagswork An example is to replace the scriptlets in your JSP with one tag such asltapplistDivision gt and this will take care of displaying the list of division codes anddescriptions JSP 12 introduced more enhancements to the custom tag feature such asIterationTag but we wonrsquot cover it here since FFIC still uses JSP 11 in WebSphere

Anatomy of a Tag

ltmytaggtvalueltmytaggt

ltmytaggt - opening tagvalue - body of the tagltmytaggt - closing tag

Custom Tag components

1 Developer-provided class that extends the classjavaxservletjsptagextTagSupport TagSupport is a helper class that implementsthe Tag interface When you write your custom tag you will need to implement atleast one of the two most used methods

doStartTag()

triggered when the opening tag is encountered return SKIP_BODY if you donrsquot want to evaluate the body of the tag return EVAL_PAGE_INCLUDE to evaluate the body of the tag

doEndTag()

triggered when the closing tag is encountered return EVAL_PAGE to continue processing the rest of the JSP

54

return SKIP_PAGE to halt processing of the JSP

2 TagLib Descriptor An XML file that describes the custom tag and the class thatimplements the logic

Example

You can save this in a file named apptldltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomfficexamplestrutsDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

3 WEBXML appWEBAPP entry ndash describes the location of your taglib descriptorand assigns a URI to be used in your JSP

Example

lttaglibgtlttaglib-urigtcraftlttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 JSP Directive ltndash tells your JSP that you will be using a custom tag what itrsquos URIis and how you will reference it in your page (using a prefix)

Example

Place this at the top of your JSP

lttaglib uri=WEB-INFapptld prefix=app gt

With these components in place you can start using custom tags in your JSPs

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

55

CodingNow letrsquos create a custom tag out of the scriptlets that we have in DisplayDivjsp

1 In VAJ in the package comffictraining create a class named DivisionTag andpaste the following codes

Insert the typersquos description here Creation date (1802 11910 PM) author Administrator

import javautilimport javaxservletjsptagextTagSupportimport javaxservletjsp

public class DivisionTag extends TagSupportHere we used the doEndTag() method to start evaluating after the body In thiscase there is no bodypublic int doEndTag() throws JspException We retrieve the collection (divList) from the request that is forwarded byHelloWorldServletArrayList divList = (ArrayList)pageContextgetRequest()getAttribute(ldquodivListrdquo)

We then iterate through the collection as we did before and write the output tothe outputstream of the pagetry Iterator iterator = divListiterator()

while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()pageContextgetOut()print(ldquolttr align=leftgtlttdgtrdquo + divbeangetDivNo() +ldquolttdgtlttdgtrdquo + divbeangetDivDesc() + ldquolttdgtlttrgtrdquo)

pageContextgetOut()print(ldquolth3gthelplth3gtrdquo) catch (Exception e) throw new JspException(etoString())

We return eval page to tell the JSP to continue processing the rest of thepage if anyreturn EVAL_PAGE

2 We then need to create a taglib descriptor for this new class Create a file namedapptld and paste the following code

56

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomffictrainingDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

lttaglibgt

3 We then need to tell the webserver about this taglib descriptor In the webxml file(only for Orion) lttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 Copy the DisplayDivjsp to a new JSP file named DisplayDivTagjsp and make thefollowing changes

Remove the following lines of code

lt page import=rdquojavautilcomffictrainingrdquo gt

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext())

DivisionBean divBean = (DivisionBean) inext()gt

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End while(ihasNext())

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

57

gt

At the top of the jsp add the following

lttaglib uri=WEB-INFapptld prefix=app gt

This tells the JSP to use apptld and that we will reference this as app allthroughout the page

Just below the table heading tags add the following line of code

ltapplistDivision gt

This invokes the DivisionTag class and starts writing the output to the page

5 Finally open HelloWorldServlet and make the following changes

In the doGet() method remove the line

String url = ldquoDisplayDivjsprdquo

Replace it with

String url = ldquoDisplayDivTagjsprdquo

Deploying the codeVAJ

1 Save the DisplayDivTagjsp in the Javaideproject resourcesIBM WebSphereTestEnvironmenthostsdefault_hostcraft folder

2 Bring up WebSphere Test Enviroment and start the servlet engine

3 Bring up a browser and type the following in the address line

httplocalhost8080craftservletController

ORION

1 Export HelloWorldServlet and DivisionTag to eservletscraftWEB-INFclasses

2 Save DisplayDivTagjsp in eservletscraft

3 Start Orion (eORIONjava ndashjar orionjar)

4 Bring up a browser and type the following in the address line

httplocalhostcraftservletController

58

Result

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

59

Lesson 11 - Model-View-Controller Design PatternBasicsIf you got this far and have understood the previous lessons then you can pat yourself onthe shoulder and say that yoursquore ready to put things together Actually you already haveWe just need to give what yoursquove been doing these past few lessons a catchy name andthat too is already done Over the years as java technology developed design patternsstarted to emerge As these patterns are recognized the most effective ones enduredand took on lives of their own One of these patterns which according to old-timers wasused to program Smalltalk applications is called Model-View-Controller or MVC for shortMVC is also called JSP Model 2 architecture Is there a Model 1 Yes there is and wersquollbriefly discuss the differences between the two models

JSP Model 1

This architecture puts the responsibility of acting on a user input accessing a db andmaintaining application state solely on a single JSP This may do for small applicationsbut not for complex ones The programmer will end up flooding the JSP with tons andtons of scriptlets and other java codes that should logically reside somewhere elseMoreover it is very difficult to coordinate the actions of all JSPs within the applicationsince they are not designed to communicate with each otherBelow is a ldquoreusedrdquo diagram of a JSP Model 1 architecture

JSP Model 2 (MVC)

This architecture extends the Model 1 concept by separating the content rendition (View)function from the application state (Model) and then adding a Controller that conducts theflow of processes within the application This provides for a clean separation ofresponsibilities between each component which results in a clearer definition of roles forweb designers and java programmers

60

Here is another ldquoreusedrdquo diagram and this time of a JSP Model 2 architecture

MVC is composed of obviously a model a view and a controller each of which havespecific functions which are described as follows

Model - represents the state of the application at any given point in time

View - renders the state of the application to the user It also receives user input andsend it to the controller for proper disposition

Controller - acts on a user input determines what action needs to be done delegatesthe action to the required business logic and invokes the Model to change itrsquos state asnecessary

There is no exercise for this lesson I thought Irsquod give you a break before we proceed withthe next one Think of this as the ldquocalm before the stormrdquoHowever letrsquos go through what yoursquove put together so far and try to match theservletsjsp against the MVC components

ControllerServlet (controller) - this contains the beginnings of a controller servlet Bytyping in the URL for this servlet on the browserrsquos address line we are asking it toperform a service for us Inside itrsquos doGet() method it knows that it needs to delegate thetask to HelloWorldServlet which performs the db access and creation of javabeans

HelloWorldServlet (model) - creates and maintains the Model for this little webapplication by storing the data in javabeanscollection It then notifies the View that theModel has changed and that it needs to render the new state

DisplayDivjsp (view) - this jsp page does not know what is happening inside theapplication All it knows is that it gets a notification from the Model that itrsquos state haschanged and that the View needs to re-render it

There we have a mini-MVC application running in our web container Of course it takesmore than a couple of servlets and a jsp to create a real-world web application and thatrsquos

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

61

what we aim to do in the next lessons Keeping this design pattern in mind we are thenready to make a quantum leap to using a framework called STRUTS that implementsthis design pattern I will save the discussion on STRUTS for the next lesson All youneed to know at this point is that STRUTS solves most of the problems (or I should saychallenges) that you will encounter when you try to build your own MVC applicationframework

6

Lesson 12 - Introduction to the Struts FrameworkApplications are generally composed of two major components business-specificcomponents and application services As an application programmer your focus tends tobe more on coding business components rather than application services since thedevelopment life-cycle is really all about gathering business requirements and creatingsystem solutions for them You will just want to be able to code your applicationrsquosbusiness functions and tie them together to create an entire process

Waawa

T

If yoursquore familiar or had worked on CICS applications then it will be easier to graspthe concept of frameworks and what they do to speed up application developmentWhen putting together a CICS application yoursquoll typically need the followingcomponents

1 Entries for CICS tables such asFile Control Table (FCT) ndash contains file aliases (tied to physical file names) to beaccessed in the CICS region (QSAM VSAM etc)

Program Control Table (PCT) ndash defines the relationships between programs andthe files they use

Program Properties Table (PPT) ndash defines the program names transaction idsand typeTerminal Control Table (TCT) ndash contains terminal definition that canaccess the CICS region

2 The symbolic and physical maps (mapsets) for the screen definitions3 CICS programs that contain the flow of the application and business logic

functions4 In the CICS startup jcl you need to put information such as load libraries (should

be in the correct order) of your programs

Once you correctly define and build these components CICS has the responsibility oftying these components together and making sure that when a user types aTransaction ID it will invoke the correct program for it and assign the correct files tothe program Unless you have too much time on your hands you do not want to findout how CICS performs these underlying processes to run your programs

2

ith application development using java programmers have had to build both businessnd application service layers for every application that they construct Most of thepplication services are so customized to the business that there is no way to reuse themith another application so programmers tend to solve the same problems over and overgain

he solution Enter frameworks

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

63

A couple of years back some genius named Craig McClanahan thought up a java-basedframework (Struts) using the MVC design pattern that is generic reusable andextensible (and of course free) It provides a lot of the application services needed toglue an application together while still giving application developers a lot of control overthe business-specific codes that they write Struts is an open source product available fordownload from wwwjakartaapachecomstruts It has a fairly big and activedeveloperuser community that can help beginners get up to speed in using Struts andanswer Struts-related questions that may not be mentioned in available documentation

Struts provides the following application services among other things

request routing errormessage handling generating client-side scripts tag libraries jdbc connection pooling xml parsing automatic population of java beans internationalization of prompts and messages validation menus page layouts

Struts ComponentsSTRUTS ESSENTIAL CLASSES

Struts employs what is called in J2EE lingo a Front Controller pattern wherein it has asingle servlet that receives all requests from the browser and forwards the processing tothe appropriate class handler In essence we do not need servlets other than the oneStruts provides We may sometimes need to extend the functionality of that servlet but inmost cases the vanilla version will do Below are the frequently used classes in theStruts framework with short descriptions

ActionServlet ndash This is the only servlet in the framework and itrsquos job is to receiverequests populate appropriate javabeans from the request delegate the process toanother class that contains business logic (Action) and forwards the process to the nextcomponent as defined in the mapping

Action ndash a class that performs a specific business function (can also dispatch to abusiness logic bean) and returns control back to the ActionServlet with correspondinginformation as to what to do next

ActionForm ndash a javabean that holds the state of the application Programmers writebeans that extend this class so that the ActionServlet can recognize it and populate itwith data from incoming requests

64

ActionForward ndash contains information that tells the ActionServlet the next componentthat will handle the current request

ActionMapping - contains information on Action classes ActionForms and resource filepaths It is read by the ActionServlet to determine which Action will process a request

ActionErrors ndash contains ActionError objects that may have been created whileprocessing a request The contents can then be rendered on an html page

ActionMessages ndash similar to ActionErrors Contains ActionMessage objects createdwhile processing a request The contents can also be rendered on an html page

JSP AND TAG LIBRARIES

In addition to the Struts classes the content rendition portion of the framework uses JSPand custom tags

Bean Tags ndash used to createcopy beans or render bean properties on the pageHtml Tags ndash used to render html form tagsLogic Tags ndash used to perform logical operations such as comparison andor to check forpresenceabsence of beans in the pageNested Tags ndash used to render nested bean properties on the pageTemplate Tags ndash used to render a composite of several jsp pages by pulling these insidea pre-defined layout

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

65

ldquoI canrsquot find the MVC pattern anywhererdquoOK so herersquos a diagram of the Struts Framework which shows how each of thepreviously discussed components work together

66

In MVC semantics the Controller would be the ActionServlet the Model is handled byAction and ActionForm classes and the View is handled by JSPs and tag librariesDid I mention that Struts works at the Presentation Layer of the application I guess notThis means that it does a swell job of conducting the process flow of programs thatinteract with the user (browser) but developers (thatrsquos you) will still need to come up withthe business objects and the data layer objects So in a bigger picture herersquos a diagramshowing where Struts lies

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

67

Below are UML representations of the different parts of the Struts framework

Action

68

Form

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

69

Message

70

Forward

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

71

Mapping

72

Config

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

73

DynaForm

74

Sequence Diagram for a request

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

75

76

The next lessons will walk you through the installation of the Struts framework in bothVAJavaWebSphere Test Environment and Orion We will also build a sample applicationthat uses most of the Struts features so you can get acquainted on the differentcomponents of Struts and how it fits into you web environment

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

77

Lesson 13 - Installing Struts 11b in VisualAge forJava 40WebSphere Test Environment 353This lesson walks you through the installation of Struts 11b in the WebSphere TestEnvironment in VisualAge for Java 40 It assumes that you already have VAJ 40installed in your workstation and that you have properly configured it using theinstructions in Lesson 2 To make sure that Struts is correctly configured you will need toinstall and run the sample application provided in this lesson

What is missing from this lesson is the explanation for the sample application codes Mygoal here is for the user to quickly setup the environment to run Struts so we can proceedwith the next lessons that discuss the different parts of Struts in greater detail

Installation and configuration1 In VAJ you will need to have the following projects present in your workspace

Servlet API ClassesJava Class LibrariesIBM WebSphere Test EnvironmentIBM Enterprise Extension LibrariesIBM XML Parser for Java

If any of the above is missing

select FileQuick Start from the menu select FeaturesAdd Features from the popup window and select the project

you need to import to your workspace

2 Downloadinstall the following

Note If you have projects in VAJ with the same name as the ones listed below be sureto version them first Then when importing the new packages make sure you selectoption create newscratch editions of versioned projectspackages

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract Xercesjar and import it in VAJava in the project XERCES

Xalan from httpxmlapacheorgxalan-jindexhtml

the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar and import them in VAJava in the project XALAN

78

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip

OPTIONAL

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and import these files to a COMMONS project in VAJava

OR

Recommended

Open the binary distribution of STRUTS and extract all commons jar files and importthem in the COMMONS project in VAJava

Struts 11b source from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1src

link is jakarta-struts-11-b1-srczip import the entire file to a STRUTS project in VAJava

Important

You will need to make some revisions to the Struts source code or you will get the following error Cannotremove Attribute from request scope in your browser I think this problem only occurs in WebSphere

In VAJ go to the orgapachestrutstaglibhtml package and open the FormTag class

Replace the following lines in the doEndTag() method in the FormTag class

pageContextremoveAttribute(ConstantsBEAN_KEY PageContextREQUEST_SCOPE)

pageContextremoveAttribute(ConstantsFORM_KEY PageContextREQUEST_SCOPE)

with the following

pageContextgetRequest()removeAttribute(ConstantsBEAN_KEY)pageContextgetRequest()removeAttribute(ConstantsFORM_KEY)

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

79

3 Open jakarta-struts-11-b1-srczip and extract the following files to eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF

struts-tld dtd xml

Note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 In the directory eappsprogram filesibmVisualAge for JavaideprojectresourcesIBM WebSphere Test Environmenthostsdefault_hostcraftWEB-INF create a file named struts-configxml file and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoISO-8859-1rdquo gtltDOCTYPE struts-config PUBLIC

ldquo-Apache Software FoundationDTD Struts Configuration 11ENrdquoldquohttpjakartaapacheorgstrutsdtdsstruts-config_1_1dtdrdquogt

ltstruts-configgtltform-beansgtltform-bean name=rdquoempFormrdquo type=rdquocomfficexamplestrutsEmployeeFormrdquo gt ltform-beansgtltaction-mappingsgtltaction path=rdquovalidateEmployeerdquo

type=rdquocomfficexamplestrutsValidateEmployeeActionrdquo name=rdquoempFormrdquo scope=rdquorequestrdquo input=rdquoInputContentjsprdquogt

ltforward name=rdquosuccessrdquo path=rdquoOutputContentjsprdquo gt ltactiongtltaction-mappingsgtltstruts-configgt

2 Open the webxml file and replace the contents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquoldquohttpjavasuncomdtdweb-app_2_3dtdrdquogtltweb-appgt

80

ltweb-appgt

Note This file is basically an empty file but we still need to provide this becausethe ActionServlet still looks for it somehow If it canrsquot find the file it throws aMalformedURLException exception

3 In the same directory create a file named apptld and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogtltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library 11ENrdquoldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogtlttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtdepartmentListltnamegtlttagclassgtcomfficexamplestrutsDepartmentTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaggt

ltnamegtskillsListltnamegtlttagclassgtcomfficexamplestrutsSkillsTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaglibgt

4 In VAJ create a project named STRUTS EXAMPLE Create a file namedApplicationResourcesproperties save it in a temporary folder and paste thecodes below in it Add it to the project that you just created (To do this click on theResources tab then right-click on the STRUTS EXAMPLE project and selectAddResource then look for the ApplicationResourceproperties file you just createdand click OK)

errormissingname=ltligtltfont colors ldquoredrdquogtPlease Enter the first nameltfontgtltligterrormissingdepartment=ltligtltfont colors ldquoredrdquogtPlease pick a departmentnameltfontgtltligterrormissingskills=ltligtltfont colors ldquoredrdquogtPlease select the relevant skillsltfontgtltligtpromptemployeename=ltbgtFirst Name ltbgtpromptemployeedepartment=ltbgtDepartment ltbgtpromptemployeeskills=ltbgtSkills ltbgt

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

81

5 Open the craftwebapp file located in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft and replace the contents with the followingcode

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegtltservletgt

ltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegtltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgtltinit-parametergt ltnamegtapplicationltnamegt

ltvaluegtApplicationResourcesltvaluegt ltinit-parametergt ltinit-parametergt

ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdebugltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdetailltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtvalidateltnamegt ltvaluegttrueltvaluegt

ltinit-parametergtltservletgt

ltservletgtltnamegtinvokerltnamegt

82

ltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegtltvaluegtindexhtmlltvaluegt

ltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

6 In VAJ create a project named STRUTS EXAMPLE and in it create a packagenamed comfficexamplestruts then create a class named EmployeeForm andpaste the following code in

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

83

Insert the typersquos description hereCreation date (1802 10946 PM)author Administrator import orgapachestrutsactionActionFormimport orgapachestrutsvalidatorValidatorForm

public class EmployeeForm extends ActionForm

private String name = ldquordquoprivate String department = ldquordquoprivate String[] skills

EmployeeForm constructor comment public EmployeeForm()

super()

public String getDepartment() return department public String getName() return name public String[] getSkills() return skills public void setDepartment(String department) thisdepartment = department public void setName(String name) thisname = name public void setSkills(String[] skills) thisskills = skills

7 In the same package create a class named DepartmentTag and paste the followingcode

84

Insert the typersquos description hereCreation date (1802 11513 PM)author Administrator

import javautilListimport javautilArrayListimport javaxservletjsptagextTagSupport public class DepartmentTag extends TagSupport

DepartmentTag constructor comment public DepartmentTag()

super()

public int doStartTag() List department = new ArrayList()departmentadd(ldquordquo)departmentadd(ldquoClient Serverrdquo)departmentadd(ldquoLegacyrdquo)departmentadd(ldquoEmerging Techrdquo)departmentadd(ldquoTech Supportrdquo)

pageContextsetAttribute(ldquodepartmentListrdquodepartment)return SKIP_BODY

8 Create a class named SkillsTag and paste the following code

Insert the typersquos description hereCreation date (1802 11910 PM)author Administrator import javautilimport javaxservletjsptagextTagSupport

public class SkillsTag extends TagSupport

SkillsTag constructor comment

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

85

public SkillsTag()

super()public int doStartTag()

List skills = new ArrayList()

skillsadd(ldquoEJBrdquo)skillsadd(ldquoJava Mailrdquo)skillsadd(ldquoJSPrdquo)skillsadd(ldquoHTMLrdquo)skillsadd(ldquoCOBOLrdquo)skillsadd(ldquoCICSrdquo)skillsadd(ldquoCrdquo)

pageContextsetAttribute(ldquoskillsListrdquoskills)return SKIP_BODY

9 Create a class named ValidateEmployeeAction and paste the following code

Insert the typersquos description hereCreation date (1802 125818 PM)author Administrator

import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

86

public class ValidateEmployeeAction extends orgapachestrutsactionAction

ValidateEmployeeAction constructor comment public ValidateEmployeeAction()

super()

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException ActionErrors errors = new ActionErrors()EmployeeForm empForm = (EmployeeForm) form

String name = empFormgetName()if(nametrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingnamerdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String department = empFormgetDepartment()if(departmenttrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingdepartmentrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String[] skills = empFormgetSkills()if(skills == null)

ActionError error = new ActionError(ldquoerrormissingskillsrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

if(errorssize() gt 0)

saveErrors(requesterrors)return new ActionForward(mappinggetInput())

return mappingfindForward(ldquosuccessrdquo)

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

87

10 In eappsprogram filesibmVisualAge for Javaideproject resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft create a file namedInputContentjsp and paste the following 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-INFapptld prefix=app gtlthtmlgt

ltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgtlthtmltext property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogtlttdgtlttdgtlthtmlselect property=rdquodepartmentrdquogtlthtmloptions name=rdquodepartmentListrdquogtlthtmlselectgtlttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogtltbeanmessage key=rdquopromptemployeeskillsrdquogtlttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoskillsListrdquogtlthtmlmultibox property=rdquoskillsrdquogtlt= currentSkill gtlthtmlmultiboxgtlt= currentSkill gt

88

ltbr gtltlogiciterategtlttdgtlttrgtlttrgtlttd colspan=rdquo2rdquo align=rdquocenterrdquogtlthtmlsubmit value=rdquoValidaterdquogtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

11 In the same folder create a file named OutputContentjsp and paste the followingcode

lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gtlttaglib uri=WEB-INFapptld prefix=app gt

lthtmlgtltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgt

ltbeanwrite name=rdquoempFormrdquo property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogt

lttdgt

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

89

lttdgt ltbeanwrite name=rdquoempFormrdquo property=rdquodepartmentrdquogt

lttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogt

ltbeanmessage key=rdquopromptemployeeskillsrdquogt

lttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoempFormrdquo property=rdquoskillsrdquogt

lt= currentSkill gtltbrgt

ltlogiciterategtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

12 Just to make sure that you have the craft application correctly configure make surethat the file defaultservlet_engine located in eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere Test Environmentpropertiescontains the following entry

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

13 In the end the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstrutsmdashconfigxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtld

90

struts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd|_ classes

Deploying and running the sample application1 Bring up the WebSphere Test Environment then click on Edit Class Path

click Select All enter the following text in the extra classpath area

EAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INFclassesEAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INF

click OK

2 Start the servlet engine

3 Once the servlet engine is started

bring up a browser enter the following URL httplocalhost8080craftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

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

91

Enter stuff in it and press Validate and

92

Lesson 14 - Installing Struts 11b in ORIONThis lesson walks you through the installation of Struts 11b in the Orion webserver Aswith the WebSphere installation you need to go through Lesson 1 to prepare yourenvironment Installation of the sample application relies heavily on the instructions inLesson 12 so it is assumed that you have already gone through that lesson Otherwisefollow the instructions for Installing the sample application in Lesson 12 to create thenecessary components

Installation and configuration1 Downloadinstall the following

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract the Xercesjar file and save it in EORIONservletscraftWEB-INFlib

Xalan from httpxmlapacheorgxalan-jindexhtml the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar save them in EORIONservletscraftWEB-

INFlib

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip extract Strutsjar and save it in EORIONservletscraftWEB-INFlib

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and save the commons-jar files toEORIONservletscraftWEB-INFlib

OR

Open the binary distribution of STRUTS and extract all commons jar files and save themin

eORIONservletscraftWEB-INFlib

2 Open jakarta-struts-11-b1zip and extract the following files toeORIONservletscraftWEB-INF

struts-tld ndash dtd ndash xml

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

93

note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 Copy the file struts-configxml from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF toeORIONservletscraftWEB-INF

2 Open the webxml file in eORIONservletscraftWEB-INF and replace thecontents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquo

ldquohttpjavasuncomj2eedtdsweb-app_2_3dtdrdquogt

ltweb-appgtltservletgt

ltservlet-namegtactionltservlet-namegtltservlet-classgtorgapachestrutsactionActionServletltservlet-classgtltinit-paramgt

ltparam-namegtapplicationltparam-namegtltparam-valuegtApplicationResourcesltparam-valuegt

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgtltservlet-mappinggt

ltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggtlttaglibgtlttaglib-urigtbeanlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-beantldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigthtmllttaglib-urigt

94

lttaglib-locationgtWEB-INFstruts-htmltldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtformlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-formtldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtlogiclttaglib-urigt

lttaglib-locationgtWEB-INFstruts-logictldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigttemplatelttaglib-urigtlttaglib-locationgtWEB-INFstruts-templatetldlttaglib-locationgtlttaglibgtlttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgt

lttaglibgtltweb-appgt

3 Copy the file apptld from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraftWEB-INF

4 Copy the file ApplicationResourcesproperties from eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftcomfficfincraftresource toeORIONservletscraftWEB-INFclasses

5 From VAJ export the class named EmployeeForm to

eORIONservletscraftWEB-INFclasses

Note the classes will be exported to the corresponding directory structurecomfficexamplestruts

6 From VAJ export the class named DepartmentTag toeORIONservletscraftWEB-INFclasses

7 From VAJ export the class named SkillsTag to eORIONservletscraftWEB-INFclasses

8 From VAJ export the class named ValidateEmployeeAction toeORIONservletscraftWEB-INFclasses

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

95

9 Copy the file InputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

10 Copy the file OutputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

11 Upon completion the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstruts-configxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtldstruts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd

|_ classesApplicationResourcesproperties|_com

|_ffic|_example

|_strutsValidateEmployeeActionclassDepartmentTagclassSkillsTagclassEmployeeFormclass

|_libstrutsjarXercesjarXalanjarxml-apisjartilesjarcommons-validatorjarcommons-servicesjarcommons-pooljar

96

commons-loggingjarcommons-digesterjarcommons-dbcpjarcommons-collectionsjarcommons-beanutilsjar

Deploying and running the sample application1 Start ORION (eorionjava -jar orionjar)

2 Once the ORION is started

bring up a browser enter the following URL

httplocalhostcraftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

Enter stuff in it and press Validate and the output should look something like the nextscreen

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

97

98

Lesson 15 - Struts ComponentsHere is a more detailed discussion on the commonly used classestaglibs in the Strutsframework To learn Struts I strongly suggest that you read this document a number oftimes revisit the example application andor hack it and most important of all ask lots ofquestions It takes more than just this document to help you understand and work withthe struts framework The last part of this document lists some very useful struts-relatedURLs that can supplement what yoursquove learned so far

Struts ComponentsThe classes described below are part of the Struts distribution package which youdownloaded in Lesson 13 In VAJ these are in the STRUTS project They may also befound in the strutsjar file that came with the binary distribution of struts

ActionServlet (orgapachestrutsactionActionServlet)

This class extends HttpServlet and is the only servlet in the Struts framework

Itrsquos main responsibilities are

receive request from the browser automatically populate any associated javabeans (ActionForms) with data from the

browser determine the class (Action) that will process the request receives notice of completion from the Action class to do either a a server-side or

client-side redirect

To configure the ActionServlet we need to enter information about this servlet in theapplication deployment descriptor just like any other servlets

In webxml (ORION)

ltservletgtltservlet-namegtactionltservlet-namegtltservlet-classgt

orgapachestrutsactionActionServletltservlet-classgt

This line tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-paramgtltparam-namegtapplicationltparam-namegtltparam-valuegt

ApplicationResourcesltparam-valuegt

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

99

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-mappinggtltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggt

In craftwebapp (VAJWebSphere Test Environment)

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgt

This tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-parametergt ltnamegtapplicationltnamegt ltvaluegt

ApplicationResourcesltvaluegt ltinit-parametergt

This tells the ActionServlet where to look for mapping information(ActionActionForm definitions)

ltinit-parametergt ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltservletgt

Yoursquoll notice that we sometimes override some initialization parameters for theActionServlet with our own values For a complete list of initialization parameters youcan go the jakartaapachecomstruts website For our purpose of building a simplestruts-based application these initialization parameters will suffice

100

ActionForm (orgapachestrutsactionActionForm)

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

public class DivisionBean extends orgapachestrutsactionActionForm

place your settersgetters etc here

Enter the form information in the struts-configxml file using ltform-beangt tags

ltform-beansgtltform-bean name=rdquoDivisionFormrdquo type=rdquocomffictrainingDivisionBeanrdquo gt

ltform-beansgt

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

ltaction-mappingsgtltaction path=rdquovalidateDivisionrdquo

type=rdquocomfficexamplestrutsValidateDivisionrdquoname=rdquoDivisionFormrdquoscope=rdquorequestrdquoinput=rdquoInputjsprdquogtltforward name=rdquosuccessrdquo path=rdquoDisplayDivisionjsprdquogt

ltactiongtltaction-mappingsgt

Action (orgapachestrutsactionAction)

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)

250

Complete code (comffictrainingLoginAction)

import orgapachestrutsactionimport orgapachestrutsvalidator

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

public class LoginAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws IOExceptionServletException

ActionErrors errors = new ActionErrors()

try

errors = ((DynaValidatorForm)form)validate(mappingrequest)if (errorsempty())

saveErrors(request errors) return new ActionForward(mappinggetInput())

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

251

5 We then need to define new validation rules for the dynamic form Open the filevalidationxml located in craftWEB-INF and add the following entries within theltformsetgt tags

ltform name=logonFormgtltfield property=userId depends=requiredgt

ltarg0 key=promptloginusergtltfieldgtltfield property=password depends=requiredmaskgt

ltarg0 key=promptloginpasswordgtltvargt

ltvar-namegtmaskltvar-namegtltvar-valuegt^[a-zA-Z]$ltvar-valuegt

ltvargtltfieldgt

ltformgt

The rules are the same as the entry for loginForm except that we donrsquot force the user to enter avalid email address in the userId field This tells us that this rule is what gets read when we validatethe login information in the DynaValidatorForm

Deploying the code (Part 2 ndash DynaValidatorForm 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

Result (Part 2 ndash DynaValidatorForm example)The result should look like the following screens below

The login form

252

Submitting the form without any data will result in the following screen

Entering a userid and an alphanumeric password will result in 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

253

Entering a userid and an alpha password will navigate the user to the welcome page

Since the user was not required to enter a valid email address for the userid we can besure that the new process is whatrsquos working behind the scenes to contain form data usingthe DynaValidatorForm and to perform the validation using struts-validator

254

Lesson 28 ndash Using tokensBasics A highly recommended way of keeping our transactions in synch is the use of tokens Atoken is a random number that gets stored in the users session a copy of which issupposed to be stored in the request If the session and request tokens are missing orare different then the transaction is out of synch To illustrate this if we have a processthat adds a record to a database using a jsp and an action class The user aftersubmitting the form and getting the confirmation that the record was successfully addedmay click on the dreaded BACK button and navigate back to the data entry screen andclick the SUBMIT button again to add the same record As a rule of thumb it is not safeto assume that users will follow instructions all the time ndash most will but there are a fewgremlins out there who will want to play around with the application We want to design asystem that deals with this type of situation The simplest way to address this is to use atoken that gets created when the entry form is displayed for the first time and theninvalidatedreset after the successful completion of the operation If the user tries to goback to the data entry screen the token will no longer be valid since it has already beenreset and therefore we can navigate the user to an error page where he canrsquot hurt himselfor the application

CodingInstead of creating a new process we will use the existing edit function to demonstratethe use of tokens in Struts

The flow of the new edit process will be as follows

Displayjsp will display all Division items Clicking on the ldquoeditrdquo link will invoke DivisionActionrsquos edit() method which will bring up

an edit page containing the selected Division item At this point a token will begenerated

The user makes changes to the division descripition (or not) and submits the formThe DivisionActionrsquos update() method will then be invoked In this method the tokenwill be validated and if valid the update will occur Otherwise the user will be thrownto the login page with the corresponding error message

1 In VAJ make the following changes to the edit() and update() methods of theDivisionAction class and the execute() method of the FindDivisionAction class

Add the following line of code within the try block just before returning an ActionForward

saveToken(request)

This code puts the token in the request which will be written in the output jsp as a hiddenfield inside the lthtmlformgt 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

255

2 Next is to make changes to the update() method of the DivisionAction class tovalidate the token and make the necessary decisions

In the try block change the following lines of code

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

to

if (isTokenValid(request))

resetToken(request)

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

else

ActionError error = new ActionError(errorduplicatesubmit)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

3 Since we created a new key for an error message in the previous step we need tomake an entry in the ApplicationResourcesproperties to assign a value to thiskey Add the following line of code in the ApplicationResourcesproperties file

errorduplicatesubmit=ltbgtltfont color=redgtDuplicate page submission session has beeninvalidate Please log in againltfontgtltbgt

4 There is also a new forward named loginpage in the update() method so add aforward named loginpage for the DivisionAction action-mapping entry in struts-configxml that maps to the login jsp

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

256

ltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

We have completed the coding changes at this point so letrsquos 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 Click on the Display Division link

ResultTo test out the use of the token just follow the screen sequence below

The list of division items will be displayed initially

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

257

Select an item to bring up an edit screen

258

After submitting the edit form the items will be redisplayed

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

259

Clickin on the browserrsquos back button will cause the screen to navigate back to the editpage

Since the token was already reset submitting that same form will trigger an exceptionand the screen will navigate to the login page with the corresponding error message

260

Lesson 29 ndash Implementing security in StrutsBasics

First some definitions

Authentication is the process by which a user submits a set of credentials to theapplication which then checks if the submitted credentials match those that are keptinternally

Authorization is the process of determining if a user authenticated or not is able toaccess a protected resource

J2EE standards provide for container-managed authentication and authorization usingentries in the application deployment descriptor (the deployment descriptor would be thecraftwebapp in VAJ and webxml in ORION) If you are not familiar with and want tolearn about configuring container-managed security form-based authentication inparticular go to this url for an overview ==gthttpwwwonjavacompubaonjava20010806webformhtml The implementation ofcontainer-managed security varies from webserver to webserver and we thereforecannot cover this in our lesson We however will be implementing the authenticationpiece using Policy Director (PD) which uses an LDAP to retrieve user infoauthorizationparameters We will then handle the implementation of the authorization piece withinStruts

Lets look at how our application will interact with PD to authenticate users

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

261

From the diagram above we can retrive the information from the HttpRequestrsquos headerusing the following codes

To retrieve the user name

String user = (String)reqgetHeader(IvUserHeaderKey)

To retrieve the groups to which the user is associated

String groups = reqgetHeader(IvGroupsHeaderKey)

Note that groups is defined as a String instead of a collection This is because theinformation retrieved from the header is a comma-delimited string so we need to providea convenience method to parse this information and place them in a collection

Upon successful authentication we need to save the user information off to a sessionobject so we can access this information anywhere within the application We then needto design a security framework around our application that will provide authorizationservices As mentioned before PD will provide the authentication service for ourapplication

Declarative security

Declarative security provides for setting security parameters outside the applicationcodes usually in an xml file the advantage of which is there is no need to recompile anyof the source codes to effect new security rules

Struts does not (yet) provide for declarative security and for good reason The frameworkneeds to be independent of any type of implementation for authenticationauthorizationfor the purpose of portability While it does not provide declarative security it does haveprovisions which enables developers to quickly develop their own mechanism fordeclarative security The next section will walk you through the steps in creating a simplebut effective security framework in Struts

Coding (Part 1 ndash protecting do classes)In this section we will create an abstract action class wersquoll call it BaseAction that willperform the necessary security checks This way we only have one place to make achange in case we need to enhance the code This class will then be extended by allother action classes

262

Below is a diagram that represents how our example application will look like at the endof this section

1 A ltset-propertygt tag can be used to define arbitrary parameters that will be passedto the action class using the ActionMapping object We will take advantage of thisfeature to declare our own security parameter In the struts-configxml file add thefollowing tag to the action classes that need to be protected

ltset-property property=isSecure value=true gt

Add this tag to the entries for the LoginAction DivisionAction and FindDivisionActionclasses

ltaction path=login type=comffictrainingLoginAction name=logonForm scope=requestinput=Loginjspgt

ltset-property property=isSecure value=falsegtltforward name=success path=welcomepagegt

ltactiongt

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

263

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

ltset-property property=secure value=truegt ltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

ltaction path=findDiv type=comffictrainingFindDivisionAction name=srchFormscope=request input=diveditpagegt

ltset-property property=secure value=truegtltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltexception key=errordivisionnotnumber type=javalangNumberFormatException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=loginpage path=Loginjspgt

ltactiongt

Note The parameter we defined above will cause Struts to invoke the setIsSecure() method ofthe ActionMapping object

2 To make sure that Struts reads the parameter we defined in the previous step weneed to define a variable in subclass of the ActionMapping class with thecorresponding accessorsmutators Create a subclass oforgapachestrutsactionActionMapping named FFICActionMapping in thepackage comffictraining

public class FFICActionMapping extends orgapachestrutsactionActionMapping

Declare a private variable for the parameter

private boolean isSecure = false

Define the settergetter that corresponds with the property attribute in the ltset-propertygt tag

public boolean getIsSecure() return isSecure

public void setIsSecure(boolean secure)

264

thisisSecure = isSecure

Complete code (comffictrainingFFICActionMapping)

Insert the types description here Creation date (6302 24414 PM) author Administrator public class FFICActionMapping extends orgapachestrutsactionActionMapping

private boolean secure = false

Construct a new instance of this class with the desired default form bean scope public FFICActionMapping()

super()

Insert the methods description here Creation date (6302 24740 PM) return boolean public boolean getSecure()

return secure Insert the methods description here Creation date (6302 24717 PM) param secure boolean public void setSecure(boolean secure)

thissecure = secureSystemoutprintln(security indicator set)

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

265

3 Now that weve can set security parameters in our config we need to create anaction class that uses this parameter To centralize the code for this create aabstract class named BaseAction which extends orgapachestrutsactionActionThis class will contain the logic that checks if an action class requires a user to belogged-in If so it then checks if the user is already logged in before it runs theexecuteAction() method of its subclass

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

The execute() method receives the FFICActionMapping object and we cast it here

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

Check if this action class requires the user to be logged-in based on the isSecurevariables value

if (requiresLogin(mapping1))

If log-in is required invoke a method that checks for the presence of the userKeyattribute in the session

if (isUserLoggedIn(request))

Execute the subclasss executeAction() method if user is logged-in

return executeAction(mapping1formrequestresponse)

else

If the user has not been authenticated create an ActionError object with thecorresponding error key and forward the user back to the login page

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

266

else

If no authentication is required that is if the isSecure parameter is not coded in theactionmapping invoke the subclass executeAction() method

return executeAction(mapping1formrequestresponse)

Create an unimplemented executeAction() method which will be implemented bysubclasses of BaseAction

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

This method checks if the user is logged-in to the application

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

This method retrieves the actions isSecure parameter to check if log-in is required

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

Complete code (comffictrainingBaseAction)

package comffictraining

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

267

import orgapachestrutsactionActionimport orgapachestrutsactionActionFormimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservlethttpHttpSessionimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

if (requiresLogin(mapping1))

Systemoutprintln(log-in required)

if (isUserLoggedIn(request))

return executeAction(mapping1formrequestresponse)

else

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

268

else

return executeAction(mapping1formrequestresponse)

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

4 Revise all the action classes - extend BaseAction instead of orgapachestrutsactionAction- change the signature of the execute() method

from

public ActionForward execute(ActionMapping mapping ActionFormform

HttpServletRequest requestHttpServletResponse response)

to

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

269

public ActionForward executeAction(FFICActionMapping mappingActionForm form

HttpServletRequest requestHttpServletResponse response)

So far we have the following action classes to change

FindDivisionAction LoginAction

5 The DispatchAction class which we discussed in previous lessons also needs toextend the BaseAction class to be able to implement the security framework

create a copy of orgapachestrutsactionDispatchAction which extendsBaseAction instead of Action in the package comffictraining

change the signature of comffictrainingDispatchActions execute() method

from

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

to

public ActionForward executeAction(FFICActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

6 Change the DivisionAction class that extendsorgapachestrutsactionDispatchAction to extend the newcomffictrainingDispatchAction

public class DivisionAction extends comffictrainingDispatchAction

7 Revise the LoginAction class to save the user information to a session objectnamed userKey This assumes that the user has been successfully authenticatedby PD and that our code has retrieved the user information from the HttpRequestrsquosheader

requestgetSession()setAttribute(userKey((DynaValidatorForm)form)get(userId))

8 Create a new entry in the ApplicationResourcesproperties file for the followingkeyvalue pair

270

errorusernotauthenticated=ltbgtltfont color=redgtYou have not been properlyauthenticatedplease log inltfontgtltbgt

9 Create the class LogoutAction in the package comffictraining so we caninvalidate the session and later on test the security framework

Create a regular action class

public class LogoutAction extends orgapachestrutsactionAction

In the execute() method just invalidate the session and forward the user to the loginpage

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)

throws Exception ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

Complete code (comffictrainingLogoutAction)

import orgapachestrutsaction

import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponse

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

271

import javaxservletServletException

import javaioIOException

import javasqlConnectionimport javasqlSQLException

import javautilCollection

Insert the types description here Creation date (12202 92827 AM) author Administrator public class LogoutAction extends orgapachestrutsactionAction LogoutAction constructor comment public LogoutAction()

super() Insert the methods description here Creation date (12202 94602 AM) return orgapachestrutsactionActionForward public ActionForward execute(ActionMapping mapping ActionForm form

HttpServletRequest request HttpServletResponse response)throws Exception

ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

272

10 Create an entry for the LogoutAction in struts-configxml

ltaction path=logout type=comffictrainingLogoutAction scope=request input=Loginjspgtltforward name=logoutpage path=logoutpagegt

ltactiongt

11 Create LogoutContentjsp in the craft folder

lttable width=100 height=100gtlttrgt lttd valign=center align=centergt lth2gtYou have been logged off lth2gt lttdgtlttrgtlttablegt

12 Open the file tilesDefinitionxml in craftWEB-INF and create a new definition forthe logout page

lt-- Extended definition for account display --gtltdefinition name=logoutpage extends=welcomepagegt

ltput name=body content=LogoutContentjspgtltdefinitiongt

13 Add a line in the menu-configxml for a link to the logout action class (in bold)

ltMenu name=MainMenu title=MainMenu gtltItem 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 gtltItem name=LogOut title=Log Out location=logoutdo gt

ltMenugt

14 Change the TileTemplatejsp in craft to include code that checks for the presence of theuserKey attribute to correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logic 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

273

Encapsulate the menu with logic tags that check for the presence of the userKey session attribute

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

Complete Code (TileTemplatejsp)

lt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFtilestld prefix=tiles gtlt taglib uri=WEB-INFstruts-logictld prefix=logic gt

ltHTMLgtltHEADgtltTITLEgtFiremans Fund Insurance CRAFTltTITLEgt

ltHEADgt

ltBODYgt ltscript language=JavaScript12 src=scriptscoolmenus3jsgtltscriptgtltscript src=scriptscoolmenu-configjsgtltscriptgt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

lttable width=100 border=0gt lttrgt lttd bgcolor=graygtltdiv align=centergtlth1gtMy Applicationlth1gtltdivgt lttdgt lttrgtlttablegt

lttable width=100 height=75 border=0gt

274

lttrgt lttd width=10 align=right valign=top bgcolor=ABABABgt

lttilesinsert attribute=menu gt

lttdgt lttd width=90 valign=center align=centergt

lttilesinsert name=bodygt lttdgt lttrgtlttablegt

lttable width=100 border=0gt lttrgt lttdgtltdiv align=centergt

ltfont size=-1gtCopyright 2002ltfontgtltdivgt

lttdgt lttrgtlttablegt

15 Change the Menujsp to include code that checks for the presence of the userKey attributeto correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logicgt

Encapsulate the menu with logic tags that check for the presence of the userKey sessionattribute

ltlogicpresent name=userKeygt

ltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

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

275

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

Add the following codes that provides a link to the log-in page Encapsulate this code withlogic tags that make the link appear only if the userKey is not present

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

Complete Code (Menujsp)

lt taglib uri=WEB-INFstruts-htmltld prefix=html gtlt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFstruts-logictld prefix=logicgt

lthtmlgtltheadgtltheadgtltbodygt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt

276

ltmenuuseMenuDisplayergt

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

ltbodygtlthtmlgt

Deploying the code (Part 1 ndash protecting do classes)

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

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

277

Result (Part 1 ndash protecting do classes)The login screen

The welcome page now shows a ldquoLog Outrdquo link which invalidates the session

278

Clicking on the ldquoDisplay Divisionrdquo link displays the division items as before No errors atthis point since the user was successfully authenticated during login

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

279

Clicking on the ldquoLog Outrdquo link will navigate the user to the page below It shows the ldquoLogInrdquo link which navigates the user to the login page when clicked

If instead of logging back in the user types a url(httplocalhost8080craftadminDivdomethod=view) on the address line (or uses abookmark) the application will determine that the user has not been authenticated andwill then be navigated to the login page which displays an error message

280

OK now we can prevent those gremlins from bookmarking our applicationrsquos urls Wehave one more thing to do though there are urls that map directly to our jsp pages and atthis point anyone can type a valid url to a particular jsp and can successfully bring up thepage without authenticating to the system There are two recommended ways ofprotecting the jsps

1 Place all jsps under the WEB-INF folder This folder per J2EE standardcan only be accessed from within an application and is not publiclyaccessible via urls typed in the browser

2 Create a custom tag that checks if the user has been authenticated similarto the code we placed in the BaseAction class and perform a redirect to thelogin page if the user has not properly logged in

For option 1 it works well with J2EE compliant application servers but since we are usingWebSphere 353 there is basically no WEB-INF folder to speak off We created a WEB-INF folder in our craft application but this is just to line up our directory structure withJ2EE standards We will therefore cover option 2 in the next section

Coding (Part 2 ndash protecting jsp pages)Unlike the example that we put together in part 1 of this lesson the custom tag that wewill create in this section unconditionally checks if the user has logged-in already Inshort there will be no logic in this custom tag that is equivalent to the code in therequiresLogin() method of BaseAction The MVC patternrsquos basic premise is that usersneed to interact with a controller at all times and not the view It therefore follows thatusers should not be able to bring up jsprsquos (view) directly without going to an action classfirst

1 As previously mentioned we will create a custom tag that checks if a user has loggedin already In the package comffictraining create a class named CheckLoginTag

Create the class by extending TagSupport

public final class CheckLoginTag extends TagSupport

Create an instance variable containing information for the login page

private String page = loginjsp

The doEndTag() is where we check for the presence of the ldquouserKeyrdquo The logic is similarto the BaseActionrsquos isUserLoggedIn() method

public int doEndTag() throws JspException

Is there a valid user logged on

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

281

boolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered

public int doStartTag() throws JspException

return (SKIP_BODY)

Complete Code

import javaioIOExceptionimport javaxservlethttpHttpSessionimport javaxservletjspJspExceptionimport javaxservletjspJspWriterimport javaxservletjspPageContextimport javaxservletjsptagextTagSupportimport orgapachestrutsactionimport orgapachestrutsutilMessageResourcesimport javaxservlethttpHttpServletRequest

Check for a valid User logged on in the current session If there is no such user forward control to the logon page

282

public final class CheckLoginTag extends TagSupport

The page to which we should forward for the user to log on private String page = loginjsp

Perform our logged-in user check by looking for the existence of a session scope bean under the specified name If this bean is not present control is forwarded to the specified logon page exception JspException if a JSP exception has occurred public int doEndTag() throws JspException

Is there a valid user logged onboolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered exception JspException if a JSP exception has occurred public int doStartTag() throws JspException

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

283

return (SKIP_BODY)

2 Open the file apptld in craftWEB-INF and add an entry for the new tag

lttaggtltnamegtcheckLoginltnamegtlttagclassgtcomffictrainingCheckLoginTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggt

3 Make changes to ALL the jsps that wersquove created so far

Add a directive for the apptld

lt taglib uri=WEB-INFapptld prefix=app gt

Place this line of code at the top of each jsp

ltappcheckLogin gt

Deploying the code (Part 2 ndash protecting jsp pages)

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

Result (Part 2 ndash protecting jsp pages)Log into the application then click on the ldquoLog Outrdquo link to make sure that whateversession you have in your browser has been invalidated

284

The screen below makes sure that you have been logged out

In the same page type in the url for the divisionrsquos search pagehttplocalhost8080craftdivSearchjsp

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

285

The checkLogin tag will check to see if the user has logged in or not Since the sessionhas been invalidated the checkLoginTag will perform a forward to the login page

Note Irsquom still working on getting the tag to write an error message similar to what theBaseAction does when it forwards to the login page if the user has not authenticated yet

  • Lesson 1 - ORION webserver configuration
    • Preparation
    • Installation
    • Configuration
    • Review
      • Lesson 2 - VisualAge for JAVAWebSphere Test Environment configuration
        • Installation
        • Configuration
        • Usage
          • Lesson 3 - Servlet primer
            • Basics
            • Your first servlet
            • Deploying the code
              • Lesson 4 - Database Connectivity
                • Preparation
                • Coding
                • Deploying the code
                  • Lesson 5 - ServletDatabase Connectivity
                    • Preparation
                    • Coding
                    • Deploying the code
                      • Lesson 6 - Servlet Redirection
                        • Basics
                        • Preparation
                        • Coding
                        • Deploying the code
                        • Result
                          • Lesson 7 - JavaBeans
                            • Basics
                            • Coding
                            • Deploying the code
                            • Result
                              • Lesson 8 - Object Scope
                                • Basics
                                • Coding
                                • Deploying the code
                                • Result
                                  • Lesson 9 - Java Server Pages (JSP)
                                    • Basics
                                    • Coding
                                    • Deploying the code
                                    • Result
                                      • Lesson 10 - Custom Tags
                                        • Basics
                                          • Anatomy of a Tag
                                          • Custom Tag components
                                            • Coding
                                            • Deploying the code
                                            • Result
                                              • Lesson 11 - Model-View-Controller Design Pattern
                                                • Basics
                                                  • Lesson 12 - Introduction to the Struts Framework
                                                    • Struts Components
                                                    • ldquoI canrsquot find the MVC pattern anywhererdquo
                                                      • Lesson 13 - Installing Struts 11b in VisualAge for Java 40WebSphere Test Environment 353
                                                        • Installation and configuration
                                                        • Installing the sample application
                                                        • Deploying and running the sample application
                                                        • Result
                                                          • Lesson 14 - Installing Struts 11b in ORION
                                                            • Installation and configuration
                                                            • Installing the sample application
                                                            • Deploying and running the sample application
                                                            • Result
                                                              • Lesson 15 - Struts Components
                                                                • Struts Components
                                                                • Tag Libraries
                                                                • Useful Links
                                                                  • Lesson 16 - Building a simple web application using Struts
                                                                    • Basics
                                                                    • Coding
                                                                    • Deploying the code
                                                                    • Result
                                                                      • Lesson 17 ndash Validating form values
                                                                        • Basics
                                                                        • Installation
                                                                        • Coding
                                                                        • Deploying the code
                                                                        • Results
                                                                          • Lesson 18 ndash Nested Beans
                                                                            • Basics
                                                                            • Installation
                                                                            • Coding
                                                                              • CODING PART 1
                                                                              • CODING PART 2
                                                                              • CODING PART 3
                                                                                  • Lesson 19 ndash Creating reusable screen components
                                                                                    • Basics
                                                                                    • Coding (Part 1)
                                                                                    • Deploying the code (Part 1)
                                                                                    • Results (Part 1)
                                                                                    • Coding (Part 2)
                                                                                    • Deploying the code (Part 2)
                                                                                    • Result (Part 2)
                                                                                    • Coding (Part 3)
                                                                                    • Deploying the code (Part 3)
                                                                                    • Result (Part 3)
                                                                                      • Lesson 20 ndash Creating reusable menu components
                                                                                        • Basics
                                                                                        • Installation
                                                                                          • Option 1
                                                                                          • Option 2
                                                                                            • Coding
                                                                                            • Deploying the code
                                                                                            • Result
                                                                                              • Lesson 21 ndash Connection Pooling
                                                                                                • Basics
                                                                                                • Coding
                                                                                                • Deploying the code
                                                                                                • Result
                                                                                                  • Lesson 22 ndash Creating a singleton to maintain the
                                                                                                    • Basics
                                                                                                    • Coding
                                                                                                    • Deploying the code
                                                                                                    • Result
                                                                                                      • Lesson 23 ndash Data Access Objects
                                                                                                        • Basics
                                                                                                        • Coding
                                                                                                        • Deploying the code
                                                                                                        • Result
                                                                                                          • Lesson 24 ndash Business Objects
                                                                                                            • Coding
                                                                                                            • Deploying the code
                                                                                                            • Result
                                                                                                              • Lesson 25 ndash Action subclasses
                                                                                                                • Coding
                                                                                                                • Deploying the code
                                                                                                                • Result
                                                                                                                  • Lesson 26 ndash Exception handling
                                                                                                                    • Basics
                                                                                                                      • Using nested ifrsquos
                                                                                                                      • Using trycatch blocks
                                                                                                                        • Coding (Part 1 ndash programmatic exception handlin
                                                                                                                        • Deploying the code (Part 1 ndash programmatic excep
                                                                                                                        • Result (Part 1 ndash programmatic exception handlin
                                                                                                                        • Coding (Part 2 ndash using declarative exception
                                                                                                                        • Deploying the code (Part 2 ndash using declarative
                                                                                                                        • Result (Part 2 ndash using declarative exception
                                                                                                                          • Lesson 27 ndash Creating dynamic forms
                                                                                                                            • Basics
                                                                                                                            • Coding (Part 1 ndash DynaActionForm example)
                                                                                                                            • Deploying the code (Part 1 ndash DynaActionForm exa
                                                                                                                            • Result (Part 1 ndash DynaActionForm example)
                                                                                                                            • Coding (Part 2 ndash DynaValidatorForm example)
                                                                                                                            • Deploying the code (Part 2 ndash DynaValidatorForm
                                                                                                                            • Result (Part 2 ndash DynaValidatorForm example)
                                                                                                                              • Lesson 28 ndash Using tokens
                                                                                                                                • Basics
                                                                                                                                • Coding
                                                                                                                                • Deploying the code
                                                                                                                                • Result
                                                                                                                                  • Lesson 29 ndash Implementing security in Struts
                                                                                                                                    • Basics
                                                                                                                                    • Coding (Part 1 ndash protecting do classes)
                                                                                                                                    • Deploying the code (Part 1 ndash protecting do cl
                                                                                                                                    • Result (Part 1 ndash protecting do classes)
                                                                                                                                    • Coding (Part 2 ndash protecting jsp pages)
                                                                                                                                    • Deploying the code (Part 2 ndash protecting jsp pag
                                                                                                                                    • Result (Part 2 ndash protecting jsp pages)

2

Coding 48Deploying the code 51Result 52

Lesson 10 - Custom Tags 53Basics 53Coding 55Deploying the code 57Result 58

Lesson 11 - Model-View-Controller Design Pattern 59Basics 59

Lesson 12 - Introduction to the Struts Framework 62Struts Components 63ldquoI canrsquot find the MVC pattern anywhererdquo 65

Lesson 13 - Installing Struts 11b in VisualAge for Java 40WebSphere TestEnvironment 353 77

Installation and configuration 77Installing the sample application 79Deploying and running the sample application 90Result 90

Lesson 14 - Installing Struts 11b in ORION 92Installation and configuration 92Installing the sample application 93Deploying and running the sample application 96Result 96

Lesson 15 - Struts Components 98Struts Components 98Tag Libraries 106Useful Links 110

Lesson 16 - Building a simple web application using Struts 111Basics 111Coding 111Deploying the code 117Result 118

Lesson 17 ndash Validating form values 120Basics 120Installation 120Coding 121Deploying the code 127Results 128

Lesson 18 ndash Nested Beans 130

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

3

Basics 130Installation 130Coding 130

Lesson 19 ndash Creating reusable screen components 141Basics 141Coding (Part 1) 141Deploying the code (Part 1) 144Results (Part 1) 145Coding (Part 2) 147Deploying the code (Part 2) 150Result (Part 2) 150Coding (Part 3) 150Deploying the code (Part 3) 152Result (Part 3) 152

Lesson 20 ndash Creating reusable menu components 153Basics 153Installation 153Coding 156Deploying the code 160Result 160

Lesson 21 ndash Connection Pooling 163Basics 163Coding 163Deploying the code 169Result 169

Lesson 22 ndash Creating a singleton to maintain the connection pool 171Basics 171Coding 171Deploying the code 183Result 183

Lesson 23 ndash Data Access Objects 186Basics 186Coding 186Deploying the code 192Result 192

Lesson 24 ndash Business Objects 195Coding 195Deploying the code 212Result 212

Lesson 25 ndash Action subclasses 216Coding 217Deploying the code 225

4

Result 225

Lesson 26 ndash Exception handling 229Basics 229Coding (Part 1 ndash programmatic exception handling) 231Deploying the code (Part 1 ndash programmatic exception handling) 234Result (Part 1 ndash programmatic exception handling) 235Coding (Part 2 ndash using declarative exception) 238Deploying the code (Part 2 ndash using declarative exception) 242Result (Part 2 ndash using declarative exception) 242

Lesson 27 ndash Creating dynamic forms 243Basics 243Coding (Part 1 ndash DynaActionForm example) 243Deploying the code (Part 1 ndash DynaActionForm example) 246Result (Part 1 ndash DynaActionForm example) 246Coding (Part 2 ndash DynaValidatorForm example) 249Deploying the code (Part 2 ndash DynaValidatorForm example) 251Result (Part 2 ndash DynaValidatorForm example) 251

Lesson 28 ndash Using tokens 254Basics 254Coding 254Deploying the code 256Result 256

Lesson 29 ndash Implementing security in Struts 260Basics 260Coding (Part 1 ndash protecting do classes) 261Deploying the code (Part 1 ndash protecting do classes) 276Result (Part 1 ndash protecting do classes) 277Coding (Part 2 ndash protecting jsp pages) 280Deploying the code (Part 2 ndash protecting jsp pages) 283Result (Part 2 ndash protecting jsp pages) 283

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

5

Lesson 1 - ORION webserver configurationThis document lists the steps to install the ORION webserver on your workstation (andrun it of course) I picked ORION since Irsquom more familiar with it than Tomcat or Resinetc The entire thing should take about an hour to accomplish I can either walk youthrough the installation or you can just follow these steps yourself and if I didnrsquot missanything have it running in no time Once yoursquore familiar with it I can then walk youthrough the configuration of WebSphere Test Environment in VAJava and we can talkabout the differences between WTE and the rest of the J2EE webappservers

PreparationThe following steps will install the java toolkit in your workstation Yoursquoll need this tocompile andor run stand-alone java programs outside of VAJava

1 Download the java sdk from httpjavasuncomj2se13downloadhtml (selectWindows (all languages) and click the download link under the SDK column)

2 Accept the license and proceed with the download (place it in your favorite folder)3 Run the downloaded executable file j2sdk-1_3_1_03-winexe and unzip it in E (it

should unzip the contents under ejdk131_03)4 Go to your desktop and right-click on My Computer and bring up the properties5 Click on the Environment tab6 Enter the following

Variable JAVA_HOMEValue ejdk131_03

7 Click on OK

Installation1 Download ORION from httpwwworionservercom

on the left-side nav of the screen click on Stable binaries under the Downloadsection

save the file to your favorite local directory

2 Open the downloaded file orion152zip and extract the contents to eorion (thisfolder will be automatically created when you check the ldquoUse foldersrdquo option inWinZip)

3 This is from the orion docscopy toolsjar from ejdk131_03lib into eorion tomake jsprsquos work

6

ConfigurationCreate a J2EE compliant directory structure To do this follow the steps

1 Create the following directory Eservletscraft This will be your applicationrsquos rootdirectory

2 Under the craft folder create the following directory structure

craft|___images|___WEB-INF

|___classes|___libFolder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

3 Create a file named webxml and save it in eservletscraftWEB-INF then pastethe following code

ltxml version=10gtltDOCTYPE web-app PUBLIC -Sun Microsystems IncDTD Web Application22EN httpjavasuncomdtdweb-app_2_2dtdgt

ltweb-appgt

ltweb-appgt

This file contains the applicationrsquos configuration information Right now itrsquos empty but thewebserver still expects to find this file or else it wonrsquot startup the application

4 To let ORION know about your new application (the one you just created above) youneed to enter some stuff in the ORION xml files To do this

go to EORIONCONFIG open applicationxml using a text editor enter the following information (in bold) right after the tag ltweb-module

id=rdquodefaultWebApprdquo path=rdquodefault-web-apprdquo gt

lt-- --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

7

ltweb-module id=rdquoCRAFTrdquo path=rdquoEservletscraftrdquo gtlt-- --gtltpersistence path=rdquopersistencerdquo gt

save and exit the file open default-web-sitexml again using a text editor enter the following information (in bold)

lt-- The default web-app for this site bound to the root --gtltdefault-web-app application=rdquodefaultrdquo name=rdquodefaultWebApprdquo gt

lt-- --gtlt-- get name from applicationxml ltweb-module id=rdquothis will be the namerdquopath=rdquocrdquogt --gtltweb-app application=rdquodefaultrdquo name=rdquoCRAFTrdquo root=rdquocraftrdquo gt

lt-- --gt

saveexit the file

5 Go to the command prompt and go to eorion

6 Start the server by typing java -jar orionjar on the command line

7 If everything was setup properly you should see the message Orion152 initialized

8 Create an html file named pagehtml and save it in Eservletscraft then pastethe following code

lthtmlgtltheadgt ltheadgtltbodygtltdiv align=centergtlth1gtHELLO WORLDlth1gtltdivgtltbodygtlthtmlgt

9 To test your webserver

bring up a browser (IE or NS) type in httplocalhostcraftpagehtml You should see proverbial HELLO

WORLD on your browser

8

(Hint While Windows itself is not case-sensitive unlike AIX the URL should thatyou type in the browserrsquos address line should match the entry in the xml file)

10 Congratulations yoursquore a survivor

ReviewThe following information is worth rememberingDIRECTORY STRUCTURE

craft|___images|___WEB-INF

|___classes|___lib

Folder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

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

9

Lesson 2 - VisualAge for JAVAWebSphere TestEnvironment configurationThis is a minimalist instruction on how to configure your WebSphere Test Environment(WTE) in VAJava to start serving web applications It walks you through the steps increating a CRAFT application and testing the setup to make sure that is runs It shouldtake an hour (or more) to complete this exercise

InstallationInstall VAJava 40 (easy to say huh) You should already have it in your workstationCheck that the WebSphere Test environment is installed in VAJ By selectingWorkspaceToolsWebSphere Test Environment VAJ should tell you if itrsquos there or not If not

Select FileQuick StartSelect FeaturesAdd FeatureSelect WebSphere Test Environment 353 from the list and click OK

Configuration1 Create the following directory structure under eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_host (whew)

craft|_images|_WEB-INF

|_classes

Folder Descriptions

craft - root directorycontains html and jsp filesimages - contains image filesWEB-INF - is not automatically recognized by WebSphere but wersquoll create this so wecan create a pseudo-J2EE directory structureclasses - again not automatically recognized by WebSphere wersquoll create this for thesame reason as the previous folder

2 Create a file craftwebapp and put the following text in the file

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegt

10

ltservletgtltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtinvokerltnamegtltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegt

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

11

ltvaluegtindexhtmlltvaluegtltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

3 To let WTE know about your new application go to the directory eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmentproperties and open the file defaultservlet_engine using a text editorAdd the following text

Look for this tag ltwebsphere-servlet-host name=rdquodefault_hostrdquogt and paste the followingtext right after it

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

UsageThis section will walk you through how to test if your WTE configuration is correctly setup1 Create a file named indexhtml and save it in eappsprogram

filesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft then paste the following code

ltHTMLgtltHEADgtltMETA NAME=GENERATOR Content=NetObjects ScriptBuilder 30gtltTITLEgtWebSphere Test Environment Index PageltTITLEgtltHEADgtltBODYgtlth1gtThis is the index page for the WebSphere Test Environmentlth1gtltBODYgtltHTMLgt

2 Bring up VAJava

3 Select WorkspaceToolsWebSphere Test Environment

4 Click on Start Servlet Engine

12

5 When the message at the lower left says ldquoServlet engine is startedrdquo bring up abrowser

6 Type in this URL httplocalhost8080craft

If the installation is successful yoursquoll get the following message on your browser This is the index page for the WebSphere Test Environmentif not wersquoll take a look at your problem

7 Thatrsquos itnow on to greater 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

13

Lesson 3 - Servlet primerHerersquos the next installment on the web-application development crash-course You willcreate your first servlet which will hopefully give you a basic understanding of whatservlets are and how they work I gave examples on how to deploy the code both in VAJWTE and in Orion so you can continuously compare the two web environments This willgo on for the next few lessons and then when we get to Struts wersquoll just retain theWebSphere Test Environment which is where we should be developing our codes

BasicsServlet

body of java code that extends a java-enabled serverrsquos functionality listens to requests and usually sends back a response to the client Can also pass

processing on to other servlets does not have a main() method so it cannot run outside of the servlet container to create a servlet we generally extend the class HttpServlet which is a subclass of

GenericServlet HttpServlet makes use of the HTTP protocol

Servlet life-cycle

An HttpServlet contains the following methods

init() doGet()doPost() destroy()

When a servlet is first invoked the servlet container calls the servletrsquos init() method thenit calls either the doGet() or doPost() method

For subsequent requests only the doGet() or doPost() method is called A separatethread is created for every doGet()doPost() invocation so different requests will not runinto each other We place the majority of our code in either of these methods

When the servlet container is shutdown it calls the servletrsquos destroy() method

RequestResponse paradigm

Uses HTTP which is a stateless protocol

In itrsquos simplest form

client sends a request and servlet receives request (and response) object which mayhave objects attached to it (parameters or attributes RemoteUser etc)

14

servlet processes the request (access a db contruct an html response forward toanother servlet etc)

client receives some form of response from the servlet and renders the output to the browser

Your first servletIn VAJ

1 Create a project named TRAINING2 Create a package named comffictraining3 Create a class named HelloWorldServlet4 Add these codes to HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

Code Walkthrough

1 To make HelloWorldServlet a servlet it needs to extend HttpServlet

public class HelloWorldServlet extends HttpServlet

2 We will then need to implement one of the following methods

doGet()doPost()

In this example we implemented the doGet() method

public void doGet(HttpServletRequest 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

15

3 Inside the doGet()

we set the content type for the response to texthtml since we intend to send back anhtml response

responsesetContentType(ldquotexthtmlrdquo)

4 We then retrieve the PrintWriter from the response so we can start writing our outputto it

PrintWriter out = responsegetWriter()

5 Lastly we start writing our output

outprintln(ldquolth1gtHello worldlth1gtrdquo)

After executing the last line of code the servlet returns control back to the web containerwhich sends the response back to the client Since we added stuff in the response theclientrsquos browser will attempt to render it

Deploying the codeVAJava (WebSphere Test Environment)

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (this can be the last entry just beforethe

ltwebappgt tag)

ltservletgtltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

Orion

16

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgtltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in ldquoHello Worldrdquo being displayed on your browser

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

17

Lesson 4 - Database ConnectivityBefore we move on to other web components we need to briefly go through the topic onconnecting to a database and retrieving information from the tables This will make thenext few topics a lot more interesting since you will be displaying data on the browser thatwere retrieved straight off of the db instead of flooding your servlet with ldquoset-this set-thatvaluerdquo lines of codes

After going through this exercise it will become more obvious that this is not the real-world way of creating and maintaining connections to a database Creating a connectionfor each sql to be executed is a pretty expensive operation In later exercises we willexplore how to create a pool of connections using DataSource and the methods withwhich this datasource is maintained and accessed (the FFIC way of course)This section discusses the java code required to connect to a database and execute sqlto retrieve data

Preparation1 You should have the IOU database information entered in your UDB-client with the

following details

DB Alias = IOUODBC entry = IOU (not really needed in this exercise but check it anyway)

2 We will be using the DB2 driver to create the connection to our database If youhavenrsquot done so import the db2javazip file into your VAJ ide

create a DB2 DRIVER project import db2javazip from EAPPSSQLLIBjava into your newly created project

using the following option ldquoimport as a Jar filerdquo

3 For ORION copy the file db2javazip to EservletsORIONcraftWEB-INFliband rename it to db2javajar

CodingIn your TRAINING project create a class JDBCSample in the comffictraining packageand paste the following code in it

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcapp

18

import javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(ldquoDivision ldquo + ldquoCoderdquo + ldquo ldquo + ldquoDescriptionrdquo) while (rsnext())

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

19

String s = rsgetString(1)String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

CODE WALKTHROUGH

1 We need to import the following packages so the program can load the necessaryjdbc classesdrivers

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

2 We define variables for the sql to execute and the useridpassword needed to accessthe database Obviously you must change the userpassword if you have a differentone We also specify here the driver that we will use to create a connection to thedatabase (DB2 in this case)

String query = ldquoSELECT FROM IOUDIVISIONrdquoConnection conn = nullStatement stmt = nullString user = ldquoiccw0t00rdquoString password = ldquoiccw0t00rdquoString driver = ldquoCOMibmdb2jdbcappDB2Driverrdquo

3 This trycatch block attempts to load the database driver and create a connection

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)

20

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)

4 When a connection is successfully created the next trycatch block creates aStatement from the connection and executes the sql that we defined earlier

try 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 )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

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 JDBCSample class and select Run

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

21

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 JDBCSample 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

The output should look similar to the following

loading driverconnectingtojdbcdb2IOUconnectedDivision Code Description1 CID Involuntary 2 CID Voluntary 3 PID 4 CID Specialty 10 National Accounts 11 Jefferson Insurance 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

22

END

NEXTLetrsquos try what we just learned using our servlet example

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

23

Lesson 5 - ServletDatabase Connectivity From the last two lessons you learned to a) construct a simple servlet and b) create ajava program that retrieves data from a database Now we will combine the two andcome up with a servlet that accesses the database and displays the result (ResultSet) ona browser

PreparationRemember your two previous programs If not here are the source codes

HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServletpublic void doGet(HttpServletRequest request

HttpServletResponse response)throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

JDBCSample

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

24

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try 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 )

stmtclose()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

25

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

Before you proceed briefly review how each of the programs work so it will be mucheasier to understand the codes belowthatrsquos all

CodingWith a little tweak (additional codes) the code below shows a combined version of thetwo programs we previously created You can cut and paste it in your HelloWorldServletin VAJ

The blue portion is the HelloWorldServlet while the red portion shows theJDBCSample

You will also notice that there are codes in green These lines of codes were added toaccomodate the codes for JDBCSample and to properly display the output to thebrowser

import javaioimport javaxservletimport javaxservlethttp

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

public class HelloWorldServlet extends HttpServletString query = SELECT FROM IOUDIVISIONConnection conn = nullStatement stmt = nullString user = iccw0t00String password = iccw0t00String driver = COMibmdb2jdbcappDB2Driver

HelloWorldServlet constructor comment

26

public HelloWorldServlet()

super()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() outprintln(lth1gtHello worldlth1gt)

try

stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(Division Code + + Description) outprintln(lth2gtDivisionlth2gt) outprintln(lth3gtCode Descriptionlth3gt)

while (rsnext()) String s = rsgetString(1)

String ln = rsgetString(2) Systemoutprintln(s + + ln )

outprintln(lth3gt + s +ampnbspampnbspampnbspampnbspampnbspampnbspampnbsp + ln + lth3gt)

stmtclose()

conclose()

catch(SQLException ex) Systemerrprintln(SQLException + exgetMessage())

Insert the methods description here Creation date (42402 22142 PM) public void init()

try Systemoutprintln(loading driver) ClassforName(driver) String url = jdbcdb2IOU Systemoutprintln(connectingto + url) conn = DriverManagergetConnection(urluserpassword) Systemoutprintln(connected)

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

27

try catch(ClassNotFoundException ex) Systemoutprintln(Couldnt load jdbc driver) Systemoutprintln(ex) catch(SQLException ex) Systemoutprintln(Database Problem) Systemoutprintln(ex) catch(Exception ex) Systemoutprintln(Some other problem) Systemoutprintln(ex)

CODE WALKTHROUGH

Irsquove pretty much gone through the codes line by line in the previous lessons What needs to be mentioned here is that a method called init() was added and the codesthat load the DB2 driver and create the connection were added here

Insert the methodrsquos description hereCreation date (42402 22142 PM) public void init()

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

28

Systemoutprintln(ex)

When a servlet starts up the first thing it looks for is an init() method and it executes thismethod once within itrsquos lifetime It is good practice to place initialization stuff in thismethod especially when we only need to run these once A good example is creating aconnection to the database and this is just what we did with this exampleNote As with the init() method a servlet also has a destroy() method which is calledwhen it shuts down

Deploying the codeDeploying the code to VAJ and ORION is the same as in the servlet lesson I listed ithere again just in case you donrsquot have that lesson anymore

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (can be the last entry just before the ltwebappgt tag)

ltservletgt

ltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

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

29

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in the following output on your browser

30

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

31

Lesson 6 - Servlet RedirectionThis lesson briefly covers one of the more important features of servlets which isforwarding or redirecting In simple terms redirection is passing control to another entitywhich can be a servlet html or jsp at the same logical level It works pretty much like anxctl in CICS with some differences There are two types of redirection client-side andserver-side and these are described in the following section

BasicsClient-side redirection

The redirection happens at the client-side and the URL on the browserrsquos address linechanges to the URL that was sent to it User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and sends a message

(redirect) to the browser containing a URL which the browser will load The browser receives the redirect from the servlet and loads the URL that was sent

to it

Note The URL in the redirect can be another servlet html or a jsp file

To illustrate this process

BROWSER==gtservlet==gtBROWSER==gtresult(jsphtmlservlet)

Client-side redirection is useful when after a servlet processes you want to navigate theuser to another page where even if he reloads that result page will not cause the servletto re-execute In other words the user is navigated to a safe place where he canrsquot hurthimself or the application

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoresponsesendRedirect(url)

if you want to retrieve the original URL to redirect the servlet to itself do this

String url = requestgetRequestURI()responsesendRedirect(url)

Note the getRequestURI() method leaves out the parameters if any that wereincluded in the original URL You can use the requestgetParameter() to retrieve theparameters and attach them to the url

32

Server-side redirection

The redirection happens only at the server-side and the browser does not know anythingabout it The URL on the browserrsquos address line does not change

User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and forwards itrsquos output to

another servlet jsp or html The receiving sevlet jsp or html renders the output to the browser

To illustrate this process

BROWSER==gtservlet==gtresult(jsphtmlservlet)

Server-side redirection is used to combine several operations to make them appear asone without involving the clientrsquos browser This cuts down traffic between the server andthe browser The browser will receive the result only after the last of the processes hasreleased the output to the web container

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

PreparationThis exercise involves server-side redirection The idea is to have one servlet receive therequest from the browser and perform a redirect to another servlet which will retrieve datafrom a db and construct the html output to be rendered on the browserWe will need the HelloWorldServlet servlet for this exercise which will act as the receivingservlet All we need to contruct is the servlet that will forward the processing toHelloWorldServlet

CodingIn VAJ create a new class called ControllerServlet in the package comffictraining andpaste the following code to it

import javaioimport javaxservletimport javaxservlethttp

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

33

public class ControllerServlet extends HttpServletpublic void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionString url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

1 We define ControllerServlet as a servlet by extending HttpServlet

public class ControllerServlet extends HttpServlet

2 These lines construct the URL of the receiving servlet and performs the redirection

String url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtControllerltnamegtltdescriptiongtDB access servletltdescriptiongtltcodegtcomffictrainingControllerServletltcodegtltautostartgttrueltautostartgt

ltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

34

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtControllerltservlet-namegtltservlet-classgt

comffictrainingControllerServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

35

You can verify that the servlet did a server-side redirect if the URL on the browserrsquosaddress line did not change It should still show

httplocalhost8080craftservletController for WTE

or

httplocalhostcraftservletController for ORION

WATCH OUT NEXT FORJAVA BEANS

36

Lesson 7 - JavaBeansUp to this point we have been dealing mostly with webserver configuration andprocedural java codes In this lesson we will start to incorporate object orientation in ourexamples using javabeans

BasicsIn our example programs we created data in our servlet by retrieving information fromthe database and by assigning values to variables There will be times when we want topass this data around and manipulate them before we send them to the browser fordisplay A convenient way of doing this is to encapsulate all these related informationhide them in an object and provide methods to access each value To accomplish thiswe create a java class called javabean or bean that contains only private variables andsettergetter methods for each of these variables For instance we can create a bean called divisionBean and store each row that weretrieve from the database to a divisionBean instance We can then put all these beansinside a collection object that we can pass around and eventually render to the browserSounds confusing Letrsquos do an example then

Coding1 In VAJ create a class called DivisionBean in comffictraining package and paste the

following in it

public class DivisionBean private String divNoprivate String divDesc

public String getDivDesc()return divDescpublic String getdivNo()return divNopublic void setDivDesc(String divDesc)thisdivDesc = divDescpublic void setDivNo(String divNo) thisdivNo = divNo

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

37

2 Open your HelloWorldServlet and make the following changes

Add the following code right after the class declaration

ArrayList divList = new ArrayList()

In the doGet() method

delete the following lines or better yet just comment them out (ie put a beforeeach line)

String s = rsgetString(1)

String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )outprintln(ldquolth3gtrdquo + s + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + ln + ldquolth3gtrdquo)

add the following lines within the while loop

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

after the while loop add the following lines of code

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

Code Walkthrough

DivisionBean

1 We defined the two variables divNo and divDesc as private to prevent them frombeing accessed directly (ie divisionBeandivNo)

private String divNoprivate String divDesc

38

2 We then define getters and setters for the two variables

public String getDivDesc()

return divDesc

public String getdivNo()

return divNo

public void setDivDesc(String divDesc)

thisdivDesc = divDesc

public void setDivNo(String divNo)

thisdivNo = divNo

HelloWorldServlet

1 We defined an Arraylist (called divList) which part of the java collections to containthe instances of the beans that we create

ArrayList divList = new ArrayList()

2 In the while loop we instantiate a new divisionBean and set itrsquos variables to thevalues that we retrieve from the db The we add that instance to divList

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

3 After wersquove gone through the entire resultset we loop through divList and create anhtml output for each instance of the bean in the ArrayList The code provided here ispretty much boiler plate code

retrieve an interator from divList (all collections have an interator)

Iterator iterator = divListiterator()

the interator has methods that loop through the ArrayList object (hasNext()) andto retrieve each item (next())

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

39

while (iteratorhasNext())

when an item is retrieved it has to be cast back to the original object In thiscase we cast the item back to DivisionBean

DivisionBean divbean = (DivisionBean) iteratornext() outprintln(ldquolth3gtrdquo +divbeangetDivNo() + ampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +divbeangetDivDesc() + ldquolth3gtrdquo)

Enhancement idea

You may ask ldquoWhy put more code that does the same thing as the originalrdquo

The answer is that creating beans and storing them in collections (or even if you justhave a single bean) enables you to attach this object to for example the request object(ie requestsetAttribute(ldquodivisionListrdquodivList)) and perform a forward to another servletthat contains code (such as the while loop with the iterator) that performs the creation ofthe output to the browser In this case the components can be further divided into thefollowing

ControllerServlet - receives the request from the browser and forwards it toHelloWorldServlet

HelloWorldServlet - retrieves data from the db stores the results inbeanscollection attaches the collection to the request object then performs aserver-side redirect to another servletjsp which we can call DisplayServletDisplayServlet - retrieves the collection from the request object and builds thehtml output while iterating through the collection

This approach enables you as the programmer to assign specific tasks to eachcomponent and keep them loosely coupled so that you can easily change onecomponent without making massive changes to the rest of your application As anexample you can change HelloWorldServlet to access another database (other thanDB2) without affecting the two other servlets in the chain

Deploying the codeVAJ

1 Bring up WTE and start the servlet engine

2 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

40

ORION

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Start ORION (eORIONjava -jar orionjar)

3 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

41

42

Lesson 8 - Object ScopeThis lesson is a sidetrip to learning the concept of object scope We need to cover thisimportant topic before we head on to JSPrsquos (are we there yet)

BasicsIn the previous lesson we learned to create javabeans and put them in a collection(called divList) to be processed by another set of codes within the same servlet We alsotoyed with the idea of creating another servlet (DisplayServlet) that will construct the htmloutput from this collection Since we want to pass the collection from HelloWorldServletto DisplayServlet we need to somehow associate the collection object with a particularscope When we perform a server-side redirect the request and response objects arepassed as arguments in the forward method Before we actually forward the process toanother servlet we make sure that we associate the collection object to the requestobject so that the receiving servlet can access that collection This is an example of anobject scope and in this instance we defined the collection to be in the request scope

A simple definition of Object Scope is the level of availabilityvisibility of an object withinthe application

It can be any of the following

page - object is visible in the page that created itrequest - object is visible in the request to which is belongssession - object is visible in the same session where it was created application - object is visible within the entire application Any servlet regardless of

what session created them can access the object in this scope

To associate an object to a particular scope we use the setAttribute() method If we want to say make the divList collection available to a userrsquos session we use thefollowing code

HttpSession session = requestgetSession(true)sessionsetAttribute(ldquodivListrdquodivList)

so long as the session still exists we can extract that collection at any point within theapplication with the following code

HttpSession session = requestgetSession(true)ArrayList divList = (ArrayList) sessiongetAttribute(ldquodivListrdquo)

Note We have to cast the collection back to itrsquos original form which is an ArrayList

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

43

Letrsquos create the DisplayServlet that we discussed in the previous lesson

1 Create a class called DisplayServlet in your TRAINING project in the packagecomffictraining and paste the following

import javaioimport javaxservletimport javaxservlethttp

import javautilpublic class DisplayServlet extends HttpServlet

ArrayList divList = new ArrayList()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionresponsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCodeDescriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() +ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

2 Open HelloWorldServlet and make the following changes

comment out the following lines of code in the doGet() method

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCode Descriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +

44

divbeangetDivDesc() + ldquolth3gtrdquo)

add the following lines of code after the stmtclose() line

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

Display Servlet

1 We define DisplayServlet by extending HttpServlet

public class DisplayServlet extends HttpServlet

3 Define an ArrayList to contain the collection that this servlet will receive fromHelloWorldServlet

ArrayList divList = new ArrayList()

4 Set the content type and get the output writer from the response so we can startwriting output data to it

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()

5 Retrieve the divList collection from the request object and cast it back to an ArrayList

divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)

6 Create the html output while iterating through the collection

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

HelloWorldServlet

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

45

1 The lines that we removed from this servlet were transferred to DisplayServlet

2 In the lines that we added we associate the divList collection with the request objectand then do a server-side redirect to DisplayServlet

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquo

RequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtDisplayltnamegtltdescriptiongtDisplay Outputltdescriptiongt

ltcodegtcomffictrainingDisplayServletltcodegtltautostartgttrueltautostartgtltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtDisplayltservlet-namegtltservlet-classgt

comffictrainingDisplayServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

46

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

47

Lesson 9 - Java Server Pages (JSP)BasicsIn the previous lessons we had been constructing our html response within the servletitself It works well with simple html outputs but later on as your webpages get morecomplicated you will find (or you may already have) that this will not work for real-worlddevelopment Java Server Pages (JSP) technology was introduced to make life easier forus programmers and for web designers How If yoursquore familiar with HTML JSP isbasically an html page with little (thatrsquos the plan) java code You get to construct your htmlpage as you normally would and start putting in java logic to a) iterate through acollection of beans b) to include output from another jsp and more To create a jsp filefrom a static html file simply change the filersquos extension from html to jsp and yoursquoreready to go But wait therersquos moreBefore we move on also remember that a jsp is first converted and compiled into aservlet by the web container before it is executed so it will have a similar life cycle as thatof a servlet Inside the jsp file we can put java codes to create dynamic output on thebrowser We accomplish this by using scriptlets expressions declarations and directiveswhich are described below

Scriptlet lt

Scriptlets are regular java codes that are automatically executed by the jsp containerwhen the jsp is invoked so they should be syntactically correct

lt String i = ldquofoordquoSystemoutprintln(i)

gt

Expression lt=

Expressions evaluate to a value that is directly displayed on the browserlt= i gt

The example is converted to outprintln(i) by the jsp container and the value of ldquoirdquo isdisplayed on the browser

Declarations lt

Declarations are java codes that are not automatically executed by the jsp container butmay be invoked if you call it from a scriptlet

lt static printName (String name) Systemoutprintln(name)

gt

48

You can invoke this by writing a scriptlet such as

lt printName(ldquoMyNamerdquo) gt

Directives lt

Directives desribe the necessary components of a jsp

lt page import=rdquojavautilcomffictrainingrdquo gt ==gt imports necessary packageslt taglib uri=rdquobeanrdquo prefix=rdquobeanrdquo gt ==gt declares a taglib referencelt include file=rdquoextraInfojsprdquo gt ==gt includes output from another jsp file

Coding

Suppose the web designer (if there is one) hands you this html file (DisplayDivhtml) lthtmlgtltbodygtlttable border=1gt

lttr align=left gtltthgtDivision IDltthgtltthgtDescriptionltthgtlttrgtlttr align=leftgtlttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgtlttdgt2lttdgtlttdgtCID Voluntarylttdgtlttrgt

lttablegtltbodygtlthtmlgt

The browser output looks like this

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

49

So you the java programmer need to convert this layout to a dynamically generated htmlfile

KNOWN

The data will come from the IOUDIVISION table You already have the servlets (ControllerServlet and HelloWorldServlet) necessary to

perform data retrieval from the db You have a DisplayServlet servlet that creates html output but you want to use a jsp

since you already have the html code and you just need to insert the necessary javacodes to render the dynamic output correctly

HINT We created javabeans (DivisionBean instances) containing Division information and

put them in a collection (divList) that is associated with the request object In our jsp file we can retrieve this collection and iterate through them pretty much the

same way we did with DisplayServlet So most of the codes that we have inDisplayServlet can be reused in the jsp file

Code Walkthrough

1 If you saved the above code in DisplayDivhtml simply rename it to DisplayDivjsp tomake it a jsp file

2 At the topmost portion paste the following code

lt page import=rdquojavautilcomffictrainingrdquo gt

This tells the jsp page that your scriptlets will be looking for necessary classes in thesepackages

3 To display the division code and description we have to insert codes that iteratethrough the collection and render them inside the table

Just after the table header definition (The ones with the ltthgt ltthgt tags) make thefollowing changes

delete the following lines of codes since these are just representations of what thedynamic portion of the page are

lttr align=leftgt

lttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgt

lttdgt2lttdgt

50

lttdgtCID Voluntarylttdgtlttrgt

insert the following codes

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()gt

Notice that this is strikingly similar to the code in DisplayServlet Thatrsquos because we justcut and paste it from there Even though the loop is not yet complete we terminated these lines of code with a ldquogtrdquo because we need to pasteregular html tags or non-java codes right after it

4 Once the above code starts iterating through the collection we need additional codesto render the details so paste the following code right after it

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

Here we used expressions to execute the ldquogetrdquo methods of the DivisionBean instance toretrieve the division code and description

5 Now this is where most beginners get bit We need to properly terminate the ldquowhilerdquoloop that we started in the previous steps To do this paste the following code rightafter the previous step

lt End whilegt

The completed code looks like the following

lt page import=rdquojavautilcomffictrainingrdquo gtlthtmlgtltbodygtlttable border=1gt

lttr align=leftgtltthgtDivision IDltthgtltthgtDescriptionltthgt

lttrgt

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

51

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()

gtlttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End whilegt

lttablegtltbodygtlthtmlgt

HelloWorldServlet

Open HelloWorldServlet and make the following changes

1 Remove the following line of code

String url = ldquoservletDisplayrdquo

2 Replace it with the following line of code to forward the process to DisplayDivjspinstead of DisplayServlet

String url = ldquoDisplayDivjsprdquo

Deploying the codeVAJ

1 Be sure to save DisplayDivjsp in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

52

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Save the DisplayDivjsp file in eservletscraft3 Start ORION (eORIONjava -jar orionjar)4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

53

Lesson 10 - Custom TagsBasicsIn Lesson 9 you learned how to create a JSP to handle content rendition in place of aservlet Wersquove seen how the same codes that we used in the servlet can be re-appliedinside the JSP using scriptlets expressions declarations and directives Again as yourJSPs get more complicated you will want to reduce the amount of java codes in themespecially codes or logic that are candidates for re-use in other JSPs In our exampleprogram if you want the logic that displays the Division information in more than oneJSPs you may want to put that body of code in a central place where you can just call itfrom different JSPs Otherwise you will end up copyingpasting the same codes in everyJSP that needs these codes

Starting with JSP 11 a feature was introduced wherein java codes can be encapsulatedand represented on the JSP using custom tags Custom tags are not unlike HTML tags(ie lthtmlgt ltformgt lttablegt etc) except that we provide the logic that makes the tagswork An example is to replace the scriptlets in your JSP with one tag such asltapplistDivision gt and this will take care of displaying the list of division codes anddescriptions JSP 12 introduced more enhancements to the custom tag feature such asIterationTag but we wonrsquot cover it here since FFIC still uses JSP 11 in WebSphere

Anatomy of a Tag

ltmytaggtvalueltmytaggt

ltmytaggt - opening tagvalue - body of the tagltmytaggt - closing tag

Custom Tag components

1 Developer-provided class that extends the classjavaxservletjsptagextTagSupport TagSupport is a helper class that implementsthe Tag interface When you write your custom tag you will need to implement atleast one of the two most used methods

doStartTag()

triggered when the opening tag is encountered return SKIP_BODY if you donrsquot want to evaluate the body of the tag return EVAL_PAGE_INCLUDE to evaluate the body of the tag

doEndTag()

triggered when the closing tag is encountered return EVAL_PAGE to continue processing the rest of the JSP

54

return SKIP_PAGE to halt processing of the JSP

2 TagLib Descriptor An XML file that describes the custom tag and the class thatimplements the logic

Example

You can save this in a file named apptldltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomfficexamplestrutsDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

3 WEBXML appWEBAPP entry ndash describes the location of your taglib descriptorand assigns a URI to be used in your JSP

Example

lttaglibgtlttaglib-urigtcraftlttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 JSP Directive ltndash tells your JSP that you will be using a custom tag what itrsquos URIis and how you will reference it in your page (using a prefix)

Example

Place this at the top of your JSP

lttaglib uri=WEB-INFapptld prefix=app gt

With these components in place you can start using custom tags in your JSPs

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

55

CodingNow letrsquos create a custom tag out of the scriptlets that we have in DisplayDivjsp

1 In VAJ in the package comffictraining create a class named DivisionTag andpaste the following codes

Insert the typersquos description here Creation date (1802 11910 PM) author Administrator

import javautilimport javaxservletjsptagextTagSupportimport javaxservletjsp

public class DivisionTag extends TagSupportHere we used the doEndTag() method to start evaluating after the body In thiscase there is no bodypublic int doEndTag() throws JspException We retrieve the collection (divList) from the request that is forwarded byHelloWorldServletArrayList divList = (ArrayList)pageContextgetRequest()getAttribute(ldquodivListrdquo)

We then iterate through the collection as we did before and write the output tothe outputstream of the pagetry Iterator iterator = divListiterator()

while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()pageContextgetOut()print(ldquolttr align=leftgtlttdgtrdquo + divbeangetDivNo() +ldquolttdgtlttdgtrdquo + divbeangetDivDesc() + ldquolttdgtlttrgtrdquo)

pageContextgetOut()print(ldquolth3gthelplth3gtrdquo) catch (Exception e) throw new JspException(etoString())

We return eval page to tell the JSP to continue processing the rest of thepage if anyreturn EVAL_PAGE

2 We then need to create a taglib descriptor for this new class Create a file namedapptld and paste the following code

56

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomffictrainingDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

lttaglibgt

3 We then need to tell the webserver about this taglib descriptor In the webxml file(only for Orion) lttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 Copy the DisplayDivjsp to a new JSP file named DisplayDivTagjsp and make thefollowing changes

Remove the following lines of code

lt page import=rdquojavautilcomffictrainingrdquo gt

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext())

DivisionBean divBean = (DivisionBean) inext()gt

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End while(ihasNext())

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

57

gt

At the top of the jsp add the following

lttaglib uri=WEB-INFapptld prefix=app gt

This tells the JSP to use apptld and that we will reference this as app allthroughout the page

Just below the table heading tags add the following line of code

ltapplistDivision gt

This invokes the DivisionTag class and starts writing the output to the page

5 Finally open HelloWorldServlet and make the following changes

In the doGet() method remove the line

String url = ldquoDisplayDivjsprdquo

Replace it with

String url = ldquoDisplayDivTagjsprdquo

Deploying the codeVAJ

1 Save the DisplayDivTagjsp in the Javaideproject resourcesIBM WebSphereTestEnvironmenthostsdefault_hostcraft folder

2 Bring up WebSphere Test Enviroment and start the servlet engine

3 Bring up a browser and type the following in the address line

httplocalhost8080craftservletController

ORION

1 Export HelloWorldServlet and DivisionTag to eservletscraftWEB-INFclasses

2 Save DisplayDivTagjsp in eservletscraft

3 Start Orion (eORIONjava ndashjar orionjar)

4 Bring up a browser and type the following in the address line

httplocalhostcraftservletController

58

Result

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

59

Lesson 11 - Model-View-Controller Design PatternBasicsIf you got this far and have understood the previous lessons then you can pat yourself onthe shoulder and say that yoursquore ready to put things together Actually you already haveWe just need to give what yoursquove been doing these past few lessons a catchy name andthat too is already done Over the years as java technology developed design patternsstarted to emerge As these patterns are recognized the most effective ones enduredand took on lives of their own One of these patterns which according to old-timers wasused to program Smalltalk applications is called Model-View-Controller or MVC for shortMVC is also called JSP Model 2 architecture Is there a Model 1 Yes there is and wersquollbriefly discuss the differences between the two models

JSP Model 1

This architecture puts the responsibility of acting on a user input accessing a db andmaintaining application state solely on a single JSP This may do for small applicationsbut not for complex ones The programmer will end up flooding the JSP with tons andtons of scriptlets and other java codes that should logically reside somewhere elseMoreover it is very difficult to coordinate the actions of all JSPs within the applicationsince they are not designed to communicate with each otherBelow is a ldquoreusedrdquo diagram of a JSP Model 1 architecture

JSP Model 2 (MVC)

This architecture extends the Model 1 concept by separating the content rendition (View)function from the application state (Model) and then adding a Controller that conducts theflow of processes within the application This provides for a clean separation ofresponsibilities between each component which results in a clearer definition of roles forweb designers and java programmers

60

Here is another ldquoreusedrdquo diagram and this time of a JSP Model 2 architecture

MVC is composed of obviously a model a view and a controller each of which havespecific functions which are described as follows

Model - represents the state of the application at any given point in time

View - renders the state of the application to the user It also receives user input andsend it to the controller for proper disposition

Controller - acts on a user input determines what action needs to be done delegatesthe action to the required business logic and invokes the Model to change itrsquos state asnecessary

There is no exercise for this lesson I thought Irsquod give you a break before we proceed withthe next one Think of this as the ldquocalm before the stormrdquoHowever letrsquos go through what yoursquove put together so far and try to match theservletsjsp against the MVC components

ControllerServlet (controller) - this contains the beginnings of a controller servlet Bytyping in the URL for this servlet on the browserrsquos address line we are asking it toperform a service for us Inside itrsquos doGet() method it knows that it needs to delegate thetask to HelloWorldServlet which performs the db access and creation of javabeans

HelloWorldServlet (model) - creates and maintains the Model for this little webapplication by storing the data in javabeanscollection It then notifies the View that theModel has changed and that it needs to render the new state

DisplayDivjsp (view) - this jsp page does not know what is happening inside theapplication All it knows is that it gets a notification from the Model that itrsquos state haschanged and that the View needs to re-render it

There we have a mini-MVC application running in our web container Of course it takesmore than a couple of servlets and a jsp to create a real-world web application and thatrsquos

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

61

what we aim to do in the next lessons Keeping this design pattern in mind we are thenready to make a quantum leap to using a framework called STRUTS that implementsthis design pattern I will save the discussion on STRUTS for the next lesson All youneed to know at this point is that STRUTS solves most of the problems (or I should saychallenges) that you will encounter when you try to build your own MVC applicationframework

6

Lesson 12 - Introduction to the Struts FrameworkApplications are generally composed of two major components business-specificcomponents and application services As an application programmer your focus tends tobe more on coding business components rather than application services since thedevelopment life-cycle is really all about gathering business requirements and creatingsystem solutions for them You will just want to be able to code your applicationrsquosbusiness functions and tie them together to create an entire process

Waawa

T

If yoursquore familiar or had worked on CICS applications then it will be easier to graspthe concept of frameworks and what they do to speed up application developmentWhen putting together a CICS application yoursquoll typically need the followingcomponents

1 Entries for CICS tables such asFile Control Table (FCT) ndash contains file aliases (tied to physical file names) to beaccessed in the CICS region (QSAM VSAM etc)

Program Control Table (PCT) ndash defines the relationships between programs andthe files they use

Program Properties Table (PPT) ndash defines the program names transaction idsand typeTerminal Control Table (TCT) ndash contains terminal definition that canaccess the CICS region

2 The symbolic and physical maps (mapsets) for the screen definitions3 CICS programs that contain the flow of the application and business logic

functions4 In the CICS startup jcl you need to put information such as load libraries (should

be in the correct order) of your programs

Once you correctly define and build these components CICS has the responsibility oftying these components together and making sure that when a user types aTransaction ID it will invoke the correct program for it and assign the correct files tothe program Unless you have too much time on your hands you do not want to findout how CICS performs these underlying processes to run your programs

2

ith application development using java programmers have had to build both businessnd application service layers for every application that they construct Most of thepplication services are so customized to the business that there is no way to reuse themith another application so programmers tend to solve the same problems over and overgain

he solution Enter frameworks

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

63

A couple of years back some genius named Craig McClanahan thought up a java-basedframework (Struts) using the MVC design pattern that is generic reusable andextensible (and of course free) It provides a lot of the application services needed toglue an application together while still giving application developers a lot of control overthe business-specific codes that they write Struts is an open source product available fordownload from wwwjakartaapachecomstruts It has a fairly big and activedeveloperuser community that can help beginners get up to speed in using Struts andanswer Struts-related questions that may not be mentioned in available documentation

Struts provides the following application services among other things

request routing errormessage handling generating client-side scripts tag libraries jdbc connection pooling xml parsing automatic population of java beans internationalization of prompts and messages validation menus page layouts

Struts ComponentsSTRUTS ESSENTIAL CLASSES

Struts employs what is called in J2EE lingo a Front Controller pattern wherein it has asingle servlet that receives all requests from the browser and forwards the processing tothe appropriate class handler In essence we do not need servlets other than the oneStruts provides We may sometimes need to extend the functionality of that servlet but inmost cases the vanilla version will do Below are the frequently used classes in theStruts framework with short descriptions

ActionServlet ndash This is the only servlet in the framework and itrsquos job is to receiverequests populate appropriate javabeans from the request delegate the process toanother class that contains business logic (Action) and forwards the process to the nextcomponent as defined in the mapping

Action ndash a class that performs a specific business function (can also dispatch to abusiness logic bean) and returns control back to the ActionServlet with correspondinginformation as to what to do next

ActionForm ndash a javabean that holds the state of the application Programmers writebeans that extend this class so that the ActionServlet can recognize it and populate itwith data from incoming requests

64

ActionForward ndash contains information that tells the ActionServlet the next componentthat will handle the current request

ActionMapping - contains information on Action classes ActionForms and resource filepaths It is read by the ActionServlet to determine which Action will process a request

ActionErrors ndash contains ActionError objects that may have been created whileprocessing a request The contents can then be rendered on an html page

ActionMessages ndash similar to ActionErrors Contains ActionMessage objects createdwhile processing a request The contents can also be rendered on an html page

JSP AND TAG LIBRARIES

In addition to the Struts classes the content rendition portion of the framework uses JSPand custom tags

Bean Tags ndash used to createcopy beans or render bean properties on the pageHtml Tags ndash used to render html form tagsLogic Tags ndash used to perform logical operations such as comparison andor to check forpresenceabsence of beans in the pageNested Tags ndash used to render nested bean properties on the pageTemplate Tags ndash used to render a composite of several jsp pages by pulling these insidea pre-defined layout

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

65

ldquoI canrsquot find the MVC pattern anywhererdquoOK so herersquos a diagram of the Struts Framework which shows how each of thepreviously discussed components work together

66

In MVC semantics the Controller would be the ActionServlet the Model is handled byAction and ActionForm classes and the View is handled by JSPs and tag librariesDid I mention that Struts works at the Presentation Layer of the application I guess notThis means that it does a swell job of conducting the process flow of programs thatinteract with the user (browser) but developers (thatrsquos you) will still need to come up withthe business objects and the data layer objects So in a bigger picture herersquos a diagramshowing where Struts lies

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

67

Below are UML representations of the different parts of the Struts framework

Action

68

Form

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

69

Message

70

Forward

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

71

Mapping

72

Config

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

73

DynaForm

74

Sequence Diagram for a request

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

75

76

The next lessons will walk you through the installation of the Struts framework in bothVAJavaWebSphere Test Environment and Orion We will also build a sample applicationthat uses most of the Struts features so you can get acquainted on the differentcomponents of Struts and how it fits into you web environment

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

77

Lesson 13 - Installing Struts 11b in VisualAge forJava 40WebSphere Test Environment 353This lesson walks you through the installation of Struts 11b in the WebSphere TestEnvironment in VisualAge for Java 40 It assumes that you already have VAJ 40installed in your workstation and that you have properly configured it using theinstructions in Lesson 2 To make sure that Struts is correctly configured you will need toinstall and run the sample application provided in this lesson

What is missing from this lesson is the explanation for the sample application codes Mygoal here is for the user to quickly setup the environment to run Struts so we can proceedwith the next lessons that discuss the different parts of Struts in greater detail

Installation and configuration1 In VAJ you will need to have the following projects present in your workspace

Servlet API ClassesJava Class LibrariesIBM WebSphere Test EnvironmentIBM Enterprise Extension LibrariesIBM XML Parser for Java

If any of the above is missing

select FileQuick Start from the menu select FeaturesAdd Features from the popup window and select the project

you need to import to your workspace

2 Downloadinstall the following

Note If you have projects in VAJ with the same name as the ones listed below be sureto version them first Then when importing the new packages make sure you selectoption create newscratch editions of versioned projectspackages

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract Xercesjar and import it in VAJava in the project XERCES

Xalan from httpxmlapacheorgxalan-jindexhtml

the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar and import them in VAJava in the project XALAN

78

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip

OPTIONAL

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and import these files to a COMMONS project in VAJava

OR

Recommended

Open the binary distribution of STRUTS and extract all commons jar files and importthem in the COMMONS project in VAJava

Struts 11b source from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1src

link is jakarta-struts-11-b1-srczip import the entire file to a STRUTS project in VAJava

Important

You will need to make some revisions to the Struts source code or you will get the following error Cannotremove Attribute from request scope in your browser I think this problem only occurs in WebSphere

In VAJ go to the orgapachestrutstaglibhtml package and open the FormTag class

Replace the following lines in the doEndTag() method in the FormTag class

pageContextremoveAttribute(ConstantsBEAN_KEY PageContextREQUEST_SCOPE)

pageContextremoveAttribute(ConstantsFORM_KEY PageContextREQUEST_SCOPE)

with the following

pageContextgetRequest()removeAttribute(ConstantsBEAN_KEY)pageContextgetRequest()removeAttribute(ConstantsFORM_KEY)

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

79

3 Open jakarta-struts-11-b1-srczip and extract the following files to eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF

struts-tld dtd xml

Note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 In the directory eappsprogram filesibmVisualAge for JavaideprojectresourcesIBM WebSphere Test Environmenthostsdefault_hostcraftWEB-INF create a file named struts-configxml file and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoISO-8859-1rdquo gtltDOCTYPE struts-config PUBLIC

ldquo-Apache Software FoundationDTD Struts Configuration 11ENrdquoldquohttpjakartaapacheorgstrutsdtdsstruts-config_1_1dtdrdquogt

ltstruts-configgtltform-beansgtltform-bean name=rdquoempFormrdquo type=rdquocomfficexamplestrutsEmployeeFormrdquo gt ltform-beansgtltaction-mappingsgtltaction path=rdquovalidateEmployeerdquo

type=rdquocomfficexamplestrutsValidateEmployeeActionrdquo name=rdquoempFormrdquo scope=rdquorequestrdquo input=rdquoInputContentjsprdquogt

ltforward name=rdquosuccessrdquo path=rdquoOutputContentjsprdquo gt ltactiongtltaction-mappingsgtltstruts-configgt

2 Open the webxml file and replace the contents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquoldquohttpjavasuncomdtdweb-app_2_3dtdrdquogtltweb-appgt

80

ltweb-appgt

Note This file is basically an empty file but we still need to provide this becausethe ActionServlet still looks for it somehow If it canrsquot find the file it throws aMalformedURLException exception

3 In the same directory create a file named apptld and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogtltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library 11ENrdquoldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogtlttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtdepartmentListltnamegtlttagclassgtcomfficexamplestrutsDepartmentTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaggt

ltnamegtskillsListltnamegtlttagclassgtcomfficexamplestrutsSkillsTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaglibgt

4 In VAJ create a project named STRUTS EXAMPLE Create a file namedApplicationResourcesproperties save it in a temporary folder and paste thecodes below in it Add it to the project that you just created (To do this click on theResources tab then right-click on the STRUTS EXAMPLE project and selectAddResource then look for the ApplicationResourceproperties file you just createdand click OK)

errormissingname=ltligtltfont colors ldquoredrdquogtPlease Enter the first nameltfontgtltligterrormissingdepartment=ltligtltfont colors ldquoredrdquogtPlease pick a departmentnameltfontgtltligterrormissingskills=ltligtltfont colors ldquoredrdquogtPlease select the relevant skillsltfontgtltligtpromptemployeename=ltbgtFirst Name ltbgtpromptemployeedepartment=ltbgtDepartment ltbgtpromptemployeeskills=ltbgtSkills ltbgt

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

81

5 Open the craftwebapp file located in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft and replace the contents with the followingcode

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegtltservletgt

ltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegtltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgtltinit-parametergt ltnamegtapplicationltnamegt

ltvaluegtApplicationResourcesltvaluegt ltinit-parametergt ltinit-parametergt

ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdebugltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdetailltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtvalidateltnamegt ltvaluegttrueltvaluegt

ltinit-parametergtltservletgt

ltservletgtltnamegtinvokerltnamegt

82

ltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegtltvaluegtindexhtmlltvaluegt

ltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

6 In VAJ create a project named STRUTS EXAMPLE and in it create a packagenamed comfficexamplestruts then create a class named EmployeeForm andpaste the following code in

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

83

Insert the typersquos description hereCreation date (1802 10946 PM)author Administrator import orgapachestrutsactionActionFormimport orgapachestrutsvalidatorValidatorForm

public class EmployeeForm extends ActionForm

private String name = ldquordquoprivate String department = ldquordquoprivate String[] skills

EmployeeForm constructor comment public EmployeeForm()

super()

public String getDepartment() return department public String getName() return name public String[] getSkills() return skills public void setDepartment(String department) thisdepartment = department public void setName(String name) thisname = name public void setSkills(String[] skills) thisskills = skills

7 In the same package create a class named DepartmentTag and paste the followingcode

84

Insert the typersquos description hereCreation date (1802 11513 PM)author Administrator

import javautilListimport javautilArrayListimport javaxservletjsptagextTagSupport public class DepartmentTag extends TagSupport

DepartmentTag constructor comment public DepartmentTag()

super()

public int doStartTag() List department = new ArrayList()departmentadd(ldquordquo)departmentadd(ldquoClient Serverrdquo)departmentadd(ldquoLegacyrdquo)departmentadd(ldquoEmerging Techrdquo)departmentadd(ldquoTech Supportrdquo)

pageContextsetAttribute(ldquodepartmentListrdquodepartment)return SKIP_BODY

8 Create a class named SkillsTag and paste the following code

Insert the typersquos description hereCreation date (1802 11910 PM)author Administrator import javautilimport javaxservletjsptagextTagSupport

public class SkillsTag extends TagSupport

SkillsTag constructor comment

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

85

public SkillsTag()

super()public int doStartTag()

List skills = new ArrayList()

skillsadd(ldquoEJBrdquo)skillsadd(ldquoJava Mailrdquo)skillsadd(ldquoJSPrdquo)skillsadd(ldquoHTMLrdquo)skillsadd(ldquoCOBOLrdquo)skillsadd(ldquoCICSrdquo)skillsadd(ldquoCrdquo)

pageContextsetAttribute(ldquoskillsListrdquoskills)return SKIP_BODY

9 Create a class named ValidateEmployeeAction and paste the following code

Insert the typersquos description hereCreation date (1802 125818 PM)author Administrator

import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

86

public class ValidateEmployeeAction extends orgapachestrutsactionAction

ValidateEmployeeAction constructor comment public ValidateEmployeeAction()

super()

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException ActionErrors errors = new ActionErrors()EmployeeForm empForm = (EmployeeForm) form

String name = empFormgetName()if(nametrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingnamerdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String department = empFormgetDepartment()if(departmenttrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingdepartmentrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String[] skills = empFormgetSkills()if(skills == null)

ActionError error = new ActionError(ldquoerrormissingskillsrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

if(errorssize() gt 0)

saveErrors(requesterrors)return new ActionForward(mappinggetInput())

return mappingfindForward(ldquosuccessrdquo)

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

87

10 In eappsprogram filesibmVisualAge for Javaideproject resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft create a file namedInputContentjsp and paste the following 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-INFapptld prefix=app gtlthtmlgt

ltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgtlthtmltext property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogtlttdgtlttdgtlthtmlselect property=rdquodepartmentrdquogtlthtmloptions name=rdquodepartmentListrdquogtlthtmlselectgtlttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogtltbeanmessage key=rdquopromptemployeeskillsrdquogtlttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoskillsListrdquogtlthtmlmultibox property=rdquoskillsrdquogtlt= currentSkill gtlthtmlmultiboxgtlt= currentSkill gt

88

ltbr gtltlogiciterategtlttdgtlttrgtlttrgtlttd colspan=rdquo2rdquo align=rdquocenterrdquogtlthtmlsubmit value=rdquoValidaterdquogtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

11 In the same folder create a file named OutputContentjsp and paste the followingcode

lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gtlttaglib uri=WEB-INFapptld prefix=app gt

lthtmlgtltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgt

ltbeanwrite name=rdquoempFormrdquo property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogt

lttdgt

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

89

lttdgt ltbeanwrite name=rdquoempFormrdquo property=rdquodepartmentrdquogt

lttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogt

ltbeanmessage key=rdquopromptemployeeskillsrdquogt

lttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoempFormrdquo property=rdquoskillsrdquogt

lt= currentSkill gtltbrgt

ltlogiciterategtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

12 Just to make sure that you have the craft application correctly configure make surethat the file defaultservlet_engine located in eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere Test Environmentpropertiescontains the following entry

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

13 In the end the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstrutsmdashconfigxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtld

90

struts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd|_ classes

Deploying and running the sample application1 Bring up the WebSphere Test Environment then click on Edit Class Path

click Select All enter the following text in the extra classpath area

EAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INFclassesEAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INF

click OK

2 Start the servlet engine

3 Once the servlet engine is started

bring up a browser enter the following URL httplocalhost8080craftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

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

91

Enter stuff in it and press Validate and

92

Lesson 14 - Installing Struts 11b in ORIONThis lesson walks you through the installation of Struts 11b in the Orion webserver Aswith the WebSphere installation you need to go through Lesson 1 to prepare yourenvironment Installation of the sample application relies heavily on the instructions inLesson 12 so it is assumed that you have already gone through that lesson Otherwisefollow the instructions for Installing the sample application in Lesson 12 to create thenecessary components

Installation and configuration1 Downloadinstall the following

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract the Xercesjar file and save it in EORIONservletscraftWEB-INFlib

Xalan from httpxmlapacheorgxalan-jindexhtml the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar save them in EORIONservletscraftWEB-

INFlib

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip extract Strutsjar and save it in EORIONservletscraftWEB-INFlib

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and save the commons-jar files toEORIONservletscraftWEB-INFlib

OR

Open the binary distribution of STRUTS and extract all commons jar files and save themin

eORIONservletscraftWEB-INFlib

2 Open jakarta-struts-11-b1zip and extract the following files toeORIONservletscraftWEB-INF

struts-tld ndash dtd ndash xml

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

93

note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 Copy the file struts-configxml from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF toeORIONservletscraftWEB-INF

2 Open the webxml file in eORIONservletscraftWEB-INF and replace thecontents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquo

ldquohttpjavasuncomj2eedtdsweb-app_2_3dtdrdquogt

ltweb-appgtltservletgt

ltservlet-namegtactionltservlet-namegtltservlet-classgtorgapachestrutsactionActionServletltservlet-classgtltinit-paramgt

ltparam-namegtapplicationltparam-namegtltparam-valuegtApplicationResourcesltparam-valuegt

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgtltservlet-mappinggt

ltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggtlttaglibgtlttaglib-urigtbeanlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-beantldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigthtmllttaglib-urigt

94

lttaglib-locationgtWEB-INFstruts-htmltldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtformlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-formtldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtlogiclttaglib-urigt

lttaglib-locationgtWEB-INFstruts-logictldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigttemplatelttaglib-urigtlttaglib-locationgtWEB-INFstruts-templatetldlttaglib-locationgtlttaglibgtlttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgt

lttaglibgtltweb-appgt

3 Copy the file apptld from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraftWEB-INF

4 Copy the file ApplicationResourcesproperties from eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftcomfficfincraftresource toeORIONservletscraftWEB-INFclasses

5 From VAJ export the class named EmployeeForm to

eORIONservletscraftWEB-INFclasses

Note the classes will be exported to the corresponding directory structurecomfficexamplestruts

6 From VAJ export the class named DepartmentTag toeORIONservletscraftWEB-INFclasses

7 From VAJ export the class named SkillsTag to eORIONservletscraftWEB-INFclasses

8 From VAJ export the class named ValidateEmployeeAction toeORIONservletscraftWEB-INFclasses

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

95

9 Copy the file InputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

10 Copy the file OutputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

11 Upon completion the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstruts-configxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtldstruts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd

|_ classesApplicationResourcesproperties|_com

|_ffic|_example

|_strutsValidateEmployeeActionclassDepartmentTagclassSkillsTagclassEmployeeFormclass

|_libstrutsjarXercesjarXalanjarxml-apisjartilesjarcommons-validatorjarcommons-servicesjarcommons-pooljar

96

commons-loggingjarcommons-digesterjarcommons-dbcpjarcommons-collectionsjarcommons-beanutilsjar

Deploying and running the sample application1 Start ORION (eorionjava -jar orionjar)

2 Once the ORION is started

bring up a browser enter the following URL

httplocalhostcraftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

Enter stuff in it and press Validate and the output should look something like the nextscreen

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

97

98

Lesson 15 - Struts ComponentsHere is a more detailed discussion on the commonly used classestaglibs in the Strutsframework To learn Struts I strongly suggest that you read this document a number oftimes revisit the example application andor hack it and most important of all ask lots ofquestions It takes more than just this document to help you understand and work withthe struts framework The last part of this document lists some very useful struts-relatedURLs that can supplement what yoursquove learned so far

Struts ComponentsThe classes described below are part of the Struts distribution package which youdownloaded in Lesson 13 In VAJ these are in the STRUTS project They may also befound in the strutsjar file that came with the binary distribution of struts

ActionServlet (orgapachestrutsactionActionServlet)

This class extends HttpServlet and is the only servlet in the Struts framework

Itrsquos main responsibilities are

receive request from the browser automatically populate any associated javabeans (ActionForms) with data from the

browser determine the class (Action) that will process the request receives notice of completion from the Action class to do either a a server-side or

client-side redirect

To configure the ActionServlet we need to enter information about this servlet in theapplication deployment descriptor just like any other servlets

In webxml (ORION)

ltservletgtltservlet-namegtactionltservlet-namegtltservlet-classgt

orgapachestrutsactionActionServletltservlet-classgt

This line tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-paramgtltparam-namegtapplicationltparam-namegtltparam-valuegt

ApplicationResourcesltparam-valuegt

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

99

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-mappinggtltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggt

In craftwebapp (VAJWebSphere Test Environment)

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgt

This tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-parametergt ltnamegtapplicationltnamegt ltvaluegt

ApplicationResourcesltvaluegt ltinit-parametergt

This tells the ActionServlet where to look for mapping information(ActionActionForm definitions)

ltinit-parametergt ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltservletgt

Yoursquoll notice that we sometimes override some initialization parameters for theActionServlet with our own values For a complete list of initialization parameters youcan go the jakartaapachecomstruts website For our purpose of building a simplestruts-based application these initialization parameters will suffice

100

ActionForm (orgapachestrutsactionActionForm)

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

public class DivisionBean extends orgapachestrutsactionActionForm

place your settersgetters etc here

Enter the form information in the struts-configxml file using ltform-beangt tags

ltform-beansgtltform-bean name=rdquoDivisionFormrdquo type=rdquocomffictrainingDivisionBeanrdquo gt

ltform-beansgt

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

ltaction-mappingsgtltaction path=rdquovalidateDivisionrdquo

type=rdquocomfficexamplestrutsValidateDivisionrdquoname=rdquoDivisionFormrdquoscope=rdquorequestrdquoinput=rdquoInputjsprdquogtltforward name=rdquosuccessrdquo path=rdquoDisplayDivisionjsprdquogt

ltactiongtltaction-mappingsgt

Action (orgapachestrutsactionAction)

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)

250

Complete code (comffictrainingLoginAction)

import orgapachestrutsactionimport orgapachestrutsvalidator

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

public class LoginAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws IOExceptionServletException

ActionErrors errors = new ActionErrors()

try

errors = ((DynaValidatorForm)form)validate(mappingrequest)if (errorsempty())

saveErrors(request errors) return new ActionForward(mappinggetInput())

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

251

5 We then need to define new validation rules for the dynamic form Open the filevalidationxml located in craftWEB-INF and add the following entries within theltformsetgt tags

ltform name=logonFormgtltfield property=userId depends=requiredgt

ltarg0 key=promptloginusergtltfieldgtltfield property=password depends=requiredmaskgt

ltarg0 key=promptloginpasswordgtltvargt

ltvar-namegtmaskltvar-namegtltvar-valuegt^[a-zA-Z]$ltvar-valuegt

ltvargtltfieldgt

ltformgt

The rules are the same as the entry for loginForm except that we donrsquot force the user to enter avalid email address in the userId field This tells us that this rule is what gets read when we validatethe login information in the DynaValidatorForm

Deploying the code (Part 2 ndash DynaValidatorForm 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

Result (Part 2 ndash DynaValidatorForm example)The result should look like the following screens below

The login form

252

Submitting the form without any data will result in the following screen

Entering a userid and an alphanumeric password will result in 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

253

Entering a userid and an alpha password will navigate the user to the welcome page

Since the user was not required to enter a valid email address for the userid we can besure that the new process is whatrsquos working behind the scenes to contain form data usingthe DynaValidatorForm and to perform the validation using struts-validator

254

Lesson 28 ndash Using tokensBasics A highly recommended way of keeping our transactions in synch is the use of tokens Atoken is a random number that gets stored in the users session a copy of which issupposed to be stored in the request If the session and request tokens are missing orare different then the transaction is out of synch To illustrate this if we have a processthat adds a record to a database using a jsp and an action class The user aftersubmitting the form and getting the confirmation that the record was successfully addedmay click on the dreaded BACK button and navigate back to the data entry screen andclick the SUBMIT button again to add the same record As a rule of thumb it is not safeto assume that users will follow instructions all the time ndash most will but there are a fewgremlins out there who will want to play around with the application We want to design asystem that deals with this type of situation The simplest way to address this is to use atoken that gets created when the entry form is displayed for the first time and theninvalidatedreset after the successful completion of the operation If the user tries to goback to the data entry screen the token will no longer be valid since it has already beenreset and therefore we can navigate the user to an error page where he canrsquot hurt himselfor the application

CodingInstead of creating a new process we will use the existing edit function to demonstratethe use of tokens in Struts

The flow of the new edit process will be as follows

Displayjsp will display all Division items Clicking on the ldquoeditrdquo link will invoke DivisionActionrsquos edit() method which will bring up

an edit page containing the selected Division item At this point a token will begenerated

The user makes changes to the division descripition (or not) and submits the formThe DivisionActionrsquos update() method will then be invoked In this method the tokenwill be validated and if valid the update will occur Otherwise the user will be thrownto the login page with the corresponding error message

1 In VAJ make the following changes to the edit() and update() methods of theDivisionAction class and the execute() method of the FindDivisionAction class

Add the following line of code within the try block just before returning an ActionForward

saveToken(request)

This code puts the token in the request which will be written in the output jsp as a hiddenfield inside the lthtmlformgt 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

255

2 Next is to make changes to the update() method of the DivisionAction class tovalidate the token and make the necessary decisions

In the try block change the following lines of code

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

to

if (isTokenValid(request))

resetToken(request)

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

else

ActionError error = new ActionError(errorduplicatesubmit)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

3 Since we created a new key for an error message in the previous step we need tomake an entry in the ApplicationResourcesproperties to assign a value to thiskey Add the following line of code in the ApplicationResourcesproperties file

errorduplicatesubmit=ltbgtltfont color=redgtDuplicate page submission session has beeninvalidate Please log in againltfontgtltbgt

4 There is also a new forward named loginpage in the update() method so add aforward named loginpage for the DivisionAction action-mapping entry in struts-configxml that maps to the login jsp

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

256

ltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

We have completed the coding changes at this point so letrsquos 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 Click on the Display Division link

ResultTo test out the use of the token just follow the screen sequence below

The list of division items will be displayed initially

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

257

Select an item to bring up an edit screen

258

After submitting the edit form the items will be redisplayed

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

259

Clickin on the browserrsquos back button will cause the screen to navigate back to the editpage

Since the token was already reset submitting that same form will trigger an exceptionand the screen will navigate to the login page with the corresponding error message

260

Lesson 29 ndash Implementing security in StrutsBasics

First some definitions

Authentication is the process by which a user submits a set of credentials to theapplication which then checks if the submitted credentials match those that are keptinternally

Authorization is the process of determining if a user authenticated or not is able toaccess a protected resource

J2EE standards provide for container-managed authentication and authorization usingentries in the application deployment descriptor (the deployment descriptor would be thecraftwebapp in VAJ and webxml in ORION) If you are not familiar with and want tolearn about configuring container-managed security form-based authentication inparticular go to this url for an overview ==gthttpwwwonjavacompubaonjava20010806webformhtml The implementation ofcontainer-managed security varies from webserver to webserver and we thereforecannot cover this in our lesson We however will be implementing the authenticationpiece using Policy Director (PD) which uses an LDAP to retrieve user infoauthorizationparameters We will then handle the implementation of the authorization piece withinStruts

Lets look at how our application will interact with PD to authenticate users

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

261

From the diagram above we can retrive the information from the HttpRequestrsquos headerusing the following codes

To retrieve the user name

String user = (String)reqgetHeader(IvUserHeaderKey)

To retrieve the groups to which the user is associated

String groups = reqgetHeader(IvGroupsHeaderKey)

Note that groups is defined as a String instead of a collection This is because theinformation retrieved from the header is a comma-delimited string so we need to providea convenience method to parse this information and place them in a collection

Upon successful authentication we need to save the user information off to a sessionobject so we can access this information anywhere within the application We then needto design a security framework around our application that will provide authorizationservices As mentioned before PD will provide the authentication service for ourapplication

Declarative security

Declarative security provides for setting security parameters outside the applicationcodes usually in an xml file the advantage of which is there is no need to recompile anyof the source codes to effect new security rules

Struts does not (yet) provide for declarative security and for good reason The frameworkneeds to be independent of any type of implementation for authenticationauthorizationfor the purpose of portability While it does not provide declarative security it does haveprovisions which enables developers to quickly develop their own mechanism fordeclarative security The next section will walk you through the steps in creating a simplebut effective security framework in Struts

Coding (Part 1 ndash protecting do classes)In this section we will create an abstract action class wersquoll call it BaseAction that willperform the necessary security checks This way we only have one place to make achange in case we need to enhance the code This class will then be extended by allother action classes

262

Below is a diagram that represents how our example application will look like at the endof this section

1 A ltset-propertygt tag can be used to define arbitrary parameters that will be passedto the action class using the ActionMapping object We will take advantage of thisfeature to declare our own security parameter In the struts-configxml file add thefollowing tag to the action classes that need to be protected

ltset-property property=isSecure value=true gt

Add this tag to the entries for the LoginAction DivisionAction and FindDivisionActionclasses

ltaction path=login type=comffictrainingLoginAction name=logonForm scope=requestinput=Loginjspgt

ltset-property property=isSecure value=falsegtltforward name=success path=welcomepagegt

ltactiongt

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

263

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

ltset-property property=secure value=truegt ltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

ltaction path=findDiv type=comffictrainingFindDivisionAction name=srchFormscope=request input=diveditpagegt

ltset-property property=secure value=truegtltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltexception key=errordivisionnotnumber type=javalangNumberFormatException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=loginpage path=Loginjspgt

ltactiongt

Note The parameter we defined above will cause Struts to invoke the setIsSecure() method ofthe ActionMapping object

2 To make sure that Struts reads the parameter we defined in the previous step weneed to define a variable in subclass of the ActionMapping class with thecorresponding accessorsmutators Create a subclass oforgapachestrutsactionActionMapping named FFICActionMapping in thepackage comffictraining

public class FFICActionMapping extends orgapachestrutsactionActionMapping

Declare a private variable for the parameter

private boolean isSecure = false

Define the settergetter that corresponds with the property attribute in the ltset-propertygt tag

public boolean getIsSecure() return isSecure

public void setIsSecure(boolean secure)

264

thisisSecure = isSecure

Complete code (comffictrainingFFICActionMapping)

Insert the types description here Creation date (6302 24414 PM) author Administrator public class FFICActionMapping extends orgapachestrutsactionActionMapping

private boolean secure = false

Construct a new instance of this class with the desired default form bean scope public FFICActionMapping()

super()

Insert the methods description here Creation date (6302 24740 PM) return boolean public boolean getSecure()

return secure Insert the methods description here Creation date (6302 24717 PM) param secure boolean public void setSecure(boolean secure)

thissecure = secureSystemoutprintln(security indicator set)

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

265

3 Now that weve can set security parameters in our config we need to create anaction class that uses this parameter To centralize the code for this create aabstract class named BaseAction which extends orgapachestrutsactionActionThis class will contain the logic that checks if an action class requires a user to belogged-in If so it then checks if the user is already logged in before it runs theexecuteAction() method of its subclass

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

The execute() method receives the FFICActionMapping object and we cast it here

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

Check if this action class requires the user to be logged-in based on the isSecurevariables value

if (requiresLogin(mapping1))

If log-in is required invoke a method that checks for the presence of the userKeyattribute in the session

if (isUserLoggedIn(request))

Execute the subclasss executeAction() method if user is logged-in

return executeAction(mapping1formrequestresponse)

else

If the user has not been authenticated create an ActionError object with thecorresponding error key and forward the user back to the login page

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

266

else

If no authentication is required that is if the isSecure parameter is not coded in theactionmapping invoke the subclass executeAction() method

return executeAction(mapping1formrequestresponse)

Create an unimplemented executeAction() method which will be implemented bysubclasses of BaseAction

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

This method checks if the user is logged-in to the application

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

This method retrieves the actions isSecure parameter to check if log-in is required

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

Complete code (comffictrainingBaseAction)

package comffictraining

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

267

import orgapachestrutsactionActionimport orgapachestrutsactionActionFormimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservlethttpHttpSessionimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

if (requiresLogin(mapping1))

Systemoutprintln(log-in required)

if (isUserLoggedIn(request))

return executeAction(mapping1formrequestresponse)

else

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

268

else

return executeAction(mapping1formrequestresponse)

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

4 Revise all the action classes - extend BaseAction instead of orgapachestrutsactionAction- change the signature of the execute() method

from

public ActionForward execute(ActionMapping mapping ActionFormform

HttpServletRequest requestHttpServletResponse response)

to

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

269

public ActionForward executeAction(FFICActionMapping mappingActionForm form

HttpServletRequest requestHttpServletResponse response)

So far we have the following action classes to change

FindDivisionAction LoginAction

5 The DispatchAction class which we discussed in previous lessons also needs toextend the BaseAction class to be able to implement the security framework

create a copy of orgapachestrutsactionDispatchAction which extendsBaseAction instead of Action in the package comffictraining

change the signature of comffictrainingDispatchActions execute() method

from

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

to

public ActionForward executeAction(FFICActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

6 Change the DivisionAction class that extendsorgapachestrutsactionDispatchAction to extend the newcomffictrainingDispatchAction

public class DivisionAction extends comffictrainingDispatchAction

7 Revise the LoginAction class to save the user information to a session objectnamed userKey This assumes that the user has been successfully authenticatedby PD and that our code has retrieved the user information from the HttpRequestrsquosheader

requestgetSession()setAttribute(userKey((DynaValidatorForm)form)get(userId))

8 Create a new entry in the ApplicationResourcesproperties file for the followingkeyvalue pair

270

errorusernotauthenticated=ltbgtltfont color=redgtYou have not been properlyauthenticatedplease log inltfontgtltbgt

9 Create the class LogoutAction in the package comffictraining so we caninvalidate the session and later on test the security framework

Create a regular action class

public class LogoutAction extends orgapachestrutsactionAction

In the execute() method just invalidate the session and forward the user to the loginpage

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)

throws Exception ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

Complete code (comffictrainingLogoutAction)

import orgapachestrutsaction

import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponse

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

271

import javaxservletServletException

import javaioIOException

import javasqlConnectionimport javasqlSQLException

import javautilCollection

Insert the types description here Creation date (12202 92827 AM) author Administrator public class LogoutAction extends orgapachestrutsactionAction LogoutAction constructor comment public LogoutAction()

super() Insert the methods description here Creation date (12202 94602 AM) return orgapachestrutsactionActionForward public ActionForward execute(ActionMapping mapping ActionForm form

HttpServletRequest request HttpServletResponse response)throws Exception

ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

272

10 Create an entry for the LogoutAction in struts-configxml

ltaction path=logout type=comffictrainingLogoutAction scope=request input=Loginjspgtltforward name=logoutpage path=logoutpagegt

ltactiongt

11 Create LogoutContentjsp in the craft folder

lttable width=100 height=100gtlttrgt lttd valign=center align=centergt lth2gtYou have been logged off lth2gt lttdgtlttrgtlttablegt

12 Open the file tilesDefinitionxml in craftWEB-INF and create a new definition forthe logout page

lt-- Extended definition for account display --gtltdefinition name=logoutpage extends=welcomepagegt

ltput name=body content=LogoutContentjspgtltdefinitiongt

13 Add a line in the menu-configxml for a link to the logout action class (in bold)

ltMenu name=MainMenu title=MainMenu gtltItem 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 gtltItem name=LogOut title=Log Out location=logoutdo gt

ltMenugt

14 Change the TileTemplatejsp in craft to include code that checks for the presence of theuserKey attribute to correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logic 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

273

Encapsulate the menu with logic tags that check for the presence of the userKey session attribute

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

Complete Code (TileTemplatejsp)

lt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFtilestld prefix=tiles gtlt taglib uri=WEB-INFstruts-logictld prefix=logic gt

ltHTMLgtltHEADgtltTITLEgtFiremans Fund Insurance CRAFTltTITLEgt

ltHEADgt

ltBODYgt ltscript language=JavaScript12 src=scriptscoolmenus3jsgtltscriptgtltscript src=scriptscoolmenu-configjsgtltscriptgt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

lttable width=100 border=0gt lttrgt lttd bgcolor=graygtltdiv align=centergtlth1gtMy Applicationlth1gtltdivgt lttdgt lttrgtlttablegt

lttable width=100 height=75 border=0gt

274

lttrgt lttd width=10 align=right valign=top bgcolor=ABABABgt

lttilesinsert attribute=menu gt

lttdgt lttd width=90 valign=center align=centergt

lttilesinsert name=bodygt lttdgt lttrgtlttablegt

lttable width=100 border=0gt lttrgt lttdgtltdiv align=centergt

ltfont size=-1gtCopyright 2002ltfontgtltdivgt

lttdgt lttrgtlttablegt

15 Change the Menujsp to include code that checks for the presence of the userKey attributeto correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logicgt

Encapsulate the menu with logic tags that check for the presence of the userKey sessionattribute

ltlogicpresent name=userKeygt

ltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

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

275

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

Add the following codes that provides a link to the log-in page Encapsulate this code withlogic tags that make the link appear only if the userKey is not present

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

Complete Code (Menujsp)

lt taglib uri=WEB-INFstruts-htmltld prefix=html gtlt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFstruts-logictld prefix=logicgt

lthtmlgtltheadgtltheadgtltbodygt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt

276

ltmenuuseMenuDisplayergt

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

ltbodygtlthtmlgt

Deploying the code (Part 1 ndash protecting do classes)

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

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

277

Result (Part 1 ndash protecting do classes)The login screen

The welcome page now shows a ldquoLog Outrdquo link which invalidates the session

278

Clicking on the ldquoDisplay Divisionrdquo link displays the division items as before No errors atthis point since the user was successfully authenticated during login

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

279

Clicking on the ldquoLog Outrdquo link will navigate the user to the page below It shows the ldquoLogInrdquo link which navigates the user to the login page when clicked

If instead of logging back in the user types a url(httplocalhost8080craftadminDivdomethod=view) on the address line (or uses abookmark) the application will determine that the user has not been authenticated andwill then be navigated to the login page which displays an error message

280

OK now we can prevent those gremlins from bookmarking our applicationrsquos urls Wehave one more thing to do though there are urls that map directly to our jsp pages and atthis point anyone can type a valid url to a particular jsp and can successfully bring up thepage without authenticating to the system There are two recommended ways ofprotecting the jsps

1 Place all jsps under the WEB-INF folder This folder per J2EE standardcan only be accessed from within an application and is not publiclyaccessible via urls typed in the browser

2 Create a custom tag that checks if the user has been authenticated similarto the code we placed in the BaseAction class and perform a redirect to thelogin page if the user has not properly logged in

For option 1 it works well with J2EE compliant application servers but since we are usingWebSphere 353 there is basically no WEB-INF folder to speak off We created a WEB-INF folder in our craft application but this is just to line up our directory structure withJ2EE standards We will therefore cover option 2 in the next section

Coding (Part 2 ndash protecting jsp pages)Unlike the example that we put together in part 1 of this lesson the custom tag that wewill create in this section unconditionally checks if the user has logged-in already Inshort there will be no logic in this custom tag that is equivalent to the code in therequiresLogin() method of BaseAction The MVC patternrsquos basic premise is that usersneed to interact with a controller at all times and not the view It therefore follows thatusers should not be able to bring up jsprsquos (view) directly without going to an action classfirst

1 As previously mentioned we will create a custom tag that checks if a user has loggedin already In the package comffictraining create a class named CheckLoginTag

Create the class by extending TagSupport

public final class CheckLoginTag extends TagSupport

Create an instance variable containing information for the login page

private String page = loginjsp

The doEndTag() is where we check for the presence of the ldquouserKeyrdquo The logic is similarto the BaseActionrsquos isUserLoggedIn() method

public int doEndTag() throws JspException

Is there a valid user logged on

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

281

boolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered

public int doStartTag() throws JspException

return (SKIP_BODY)

Complete Code

import javaioIOExceptionimport javaxservlethttpHttpSessionimport javaxservletjspJspExceptionimport javaxservletjspJspWriterimport javaxservletjspPageContextimport javaxservletjsptagextTagSupportimport orgapachestrutsactionimport orgapachestrutsutilMessageResourcesimport javaxservlethttpHttpServletRequest

Check for a valid User logged on in the current session If there is no such user forward control to the logon page

282

public final class CheckLoginTag extends TagSupport

The page to which we should forward for the user to log on private String page = loginjsp

Perform our logged-in user check by looking for the existence of a session scope bean under the specified name If this bean is not present control is forwarded to the specified logon page exception JspException if a JSP exception has occurred public int doEndTag() throws JspException

Is there a valid user logged onboolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered exception JspException if a JSP exception has occurred public int doStartTag() throws JspException

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

283

return (SKIP_BODY)

2 Open the file apptld in craftWEB-INF and add an entry for the new tag

lttaggtltnamegtcheckLoginltnamegtlttagclassgtcomffictrainingCheckLoginTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggt

3 Make changes to ALL the jsps that wersquove created so far

Add a directive for the apptld

lt taglib uri=WEB-INFapptld prefix=app gt

Place this line of code at the top of each jsp

ltappcheckLogin gt

Deploying the code (Part 2 ndash protecting jsp pages)

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

Result (Part 2 ndash protecting jsp pages)Log into the application then click on the ldquoLog Outrdquo link to make sure that whateversession you have in your browser has been invalidated

284

The screen below makes sure that you have been logged out

In the same page type in the url for the divisionrsquos search pagehttplocalhost8080craftdivSearchjsp

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

285

The checkLogin tag will check to see if the user has logged in or not Since the sessionhas been invalidated the checkLoginTag will perform a forward to the login page

Note Irsquom still working on getting the tag to write an error message similar to what theBaseAction does when it forwards to the login page if the user has not authenticated yet

  • Lesson 1 - ORION webserver configuration
    • Preparation
    • Installation
    • Configuration
    • Review
      • Lesson 2 - VisualAge for JAVAWebSphere Test Environment configuration
        • Installation
        • Configuration
        • Usage
          • Lesson 3 - Servlet primer
            • Basics
            • Your first servlet
            • Deploying the code
              • Lesson 4 - Database Connectivity
                • Preparation
                • Coding
                • Deploying the code
                  • Lesson 5 - ServletDatabase Connectivity
                    • Preparation
                    • Coding
                    • Deploying the code
                      • Lesson 6 - Servlet Redirection
                        • Basics
                        • Preparation
                        • Coding
                        • Deploying the code
                        • Result
                          • Lesson 7 - JavaBeans
                            • Basics
                            • Coding
                            • Deploying the code
                            • Result
                              • Lesson 8 - Object Scope
                                • Basics
                                • Coding
                                • Deploying the code
                                • Result
                                  • Lesson 9 - Java Server Pages (JSP)
                                    • Basics
                                    • Coding
                                    • Deploying the code
                                    • Result
                                      • Lesson 10 - Custom Tags
                                        • Basics
                                          • Anatomy of a Tag
                                          • Custom Tag components
                                            • Coding
                                            • Deploying the code
                                            • Result
                                              • Lesson 11 - Model-View-Controller Design Pattern
                                                • Basics
                                                  • Lesson 12 - Introduction to the Struts Framework
                                                    • Struts Components
                                                    • ldquoI canrsquot find the MVC pattern anywhererdquo
                                                      • Lesson 13 - Installing Struts 11b in VisualAge for Java 40WebSphere Test Environment 353
                                                        • Installation and configuration
                                                        • Installing the sample application
                                                        • Deploying and running the sample application
                                                        • Result
                                                          • Lesson 14 - Installing Struts 11b in ORION
                                                            • Installation and configuration
                                                            • Installing the sample application
                                                            • Deploying and running the sample application
                                                            • Result
                                                              • Lesson 15 - Struts Components
                                                                • Struts Components
                                                                • Tag Libraries
                                                                • Useful Links
                                                                  • Lesson 16 - Building a simple web application using Struts
                                                                    • Basics
                                                                    • Coding
                                                                    • Deploying the code
                                                                    • Result
                                                                      • Lesson 17 ndash Validating form values
                                                                        • Basics
                                                                        • Installation
                                                                        • Coding
                                                                        • Deploying the code
                                                                        • Results
                                                                          • Lesson 18 ndash Nested Beans
                                                                            • Basics
                                                                            • Installation
                                                                            • Coding
                                                                              • CODING PART 1
                                                                              • CODING PART 2
                                                                              • CODING PART 3
                                                                                  • Lesson 19 ndash Creating reusable screen components
                                                                                    • Basics
                                                                                    • Coding (Part 1)
                                                                                    • Deploying the code (Part 1)
                                                                                    • Results (Part 1)
                                                                                    • Coding (Part 2)
                                                                                    • Deploying the code (Part 2)
                                                                                    • Result (Part 2)
                                                                                    • Coding (Part 3)
                                                                                    • Deploying the code (Part 3)
                                                                                    • Result (Part 3)
                                                                                      • Lesson 20 ndash Creating reusable menu components
                                                                                        • Basics
                                                                                        • Installation
                                                                                          • Option 1
                                                                                          • Option 2
                                                                                            • Coding
                                                                                            • Deploying the code
                                                                                            • Result
                                                                                              • Lesson 21 ndash Connection Pooling
                                                                                                • Basics
                                                                                                • Coding
                                                                                                • Deploying the code
                                                                                                • Result
                                                                                                  • Lesson 22 ndash Creating a singleton to maintain the
                                                                                                    • Basics
                                                                                                    • Coding
                                                                                                    • Deploying the code
                                                                                                    • Result
                                                                                                      • Lesson 23 ndash Data Access Objects
                                                                                                        • Basics
                                                                                                        • Coding
                                                                                                        • Deploying the code
                                                                                                        • Result
                                                                                                          • Lesson 24 ndash Business Objects
                                                                                                            • Coding
                                                                                                            • Deploying the code
                                                                                                            • Result
                                                                                                              • Lesson 25 ndash Action subclasses
                                                                                                                • Coding
                                                                                                                • Deploying the code
                                                                                                                • Result
                                                                                                                  • Lesson 26 ndash Exception handling
                                                                                                                    • Basics
                                                                                                                      • Using nested ifrsquos
                                                                                                                      • Using trycatch blocks
                                                                                                                        • Coding (Part 1 ndash programmatic exception handlin
                                                                                                                        • Deploying the code (Part 1 ndash programmatic excep
                                                                                                                        • Result (Part 1 ndash programmatic exception handlin
                                                                                                                        • Coding (Part 2 ndash using declarative exception
                                                                                                                        • Deploying the code (Part 2 ndash using declarative
                                                                                                                        • Result (Part 2 ndash using declarative exception
                                                                                                                          • Lesson 27 ndash Creating dynamic forms
                                                                                                                            • Basics
                                                                                                                            • Coding (Part 1 ndash DynaActionForm example)
                                                                                                                            • Deploying the code (Part 1 ndash DynaActionForm exa
                                                                                                                            • Result (Part 1 ndash DynaActionForm example)
                                                                                                                            • Coding (Part 2 ndash DynaValidatorForm example)
                                                                                                                            • Deploying the code (Part 2 ndash DynaValidatorForm
                                                                                                                            • Result (Part 2 ndash DynaValidatorForm example)
                                                                                                                              • Lesson 28 ndash Using tokens
                                                                                                                                • Basics
                                                                                                                                • Coding
                                                                                                                                • Deploying the code
                                                                                                                                • Result
                                                                                                                                  • Lesson 29 ndash Implementing security in Struts
                                                                                                                                    • Basics
                                                                                                                                    • Coding (Part 1 ndash protecting do classes)
                                                                                                                                    • Deploying the code (Part 1 ndash protecting do cl
                                                                                                                                    • Result (Part 1 ndash protecting do classes)
                                                                                                                                    • Coding (Part 2 ndash protecting jsp pages)
                                                                                                                                    • Deploying the code (Part 2 ndash protecting jsp pag
                                                                                                                                    • Result (Part 2 ndash protecting jsp pages)

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

3

Basics 130Installation 130Coding 130

Lesson 19 ndash Creating reusable screen components 141Basics 141Coding (Part 1) 141Deploying the code (Part 1) 144Results (Part 1) 145Coding (Part 2) 147Deploying the code (Part 2) 150Result (Part 2) 150Coding (Part 3) 150Deploying the code (Part 3) 152Result (Part 3) 152

Lesson 20 ndash Creating reusable menu components 153Basics 153Installation 153Coding 156Deploying the code 160Result 160

Lesson 21 ndash Connection Pooling 163Basics 163Coding 163Deploying the code 169Result 169

Lesson 22 ndash Creating a singleton to maintain the connection pool 171Basics 171Coding 171Deploying the code 183Result 183

Lesson 23 ndash Data Access Objects 186Basics 186Coding 186Deploying the code 192Result 192

Lesson 24 ndash Business Objects 195Coding 195Deploying the code 212Result 212

Lesson 25 ndash Action subclasses 216Coding 217Deploying the code 225

4

Result 225

Lesson 26 ndash Exception handling 229Basics 229Coding (Part 1 ndash programmatic exception handling) 231Deploying the code (Part 1 ndash programmatic exception handling) 234Result (Part 1 ndash programmatic exception handling) 235Coding (Part 2 ndash using declarative exception) 238Deploying the code (Part 2 ndash using declarative exception) 242Result (Part 2 ndash using declarative exception) 242

Lesson 27 ndash Creating dynamic forms 243Basics 243Coding (Part 1 ndash DynaActionForm example) 243Deploying the code (Part 1 ndash DynaActionForm example) 246Result (Part 1 ndash DynaActionForm example) 246Coding (Part 2 ndash DynaValidatorForm example) 249Deploying the code (Part 2 ndash DynaValidatorForm example) 251Result (Part 2 ndash DynaValidatorForm example) 251

Lesson 28 ndash Using tokens 254Basics 254Coding 254Deploying the code 256Result 256

Lesson 29 ndash Implementing security in Struts 260Basics 260Coding (Part 1 ndash protecting do classes) 261Deploying the code (Part 1 ndash protecting do classes) 276Result (Part 1 ndash protecting do classes) 277Coding (Part 2 ndash protecting jsp pages) 280Deploying the code (Part 2 ndash protecting jsp pages) 283Result (Part 2 ndash protecting jsp pages) 283

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

5

Lesson 1 - ORION webserver configurationThis document lists the steps to install the ORION webserver on your workstation (andrun it of course) I picked ORION since Irsquom more familiar with it than Tomcat or Resinetc The entire thing should take about an hour to accomplish I can either walk youthrough the installation or you can just follow these steps yourself and if I didnrsquot missanything have it running in no time Once yoursquore familiar with it I can then walk youthrough the configuration of WebSphere Test Environment in VAJava and we can talkabout the differences between WTE and the rest of the J2EE webappservers

PreparationThe following steps will install the java toolkit in your workstation Yoursquoll need this tocompile andor run stand-alone java programs outside of VAJava

1 Download the java sdk from httpjavasuncomj2se13downloadhtml (selectWindows (all languages) and click the download link under the SDK column)

2 Accept the license and proceed with the download (place it in your favorite folder)3 Run the downloaded executable file j2sdk-1_3_1_03-winexe and unzip it in E (it

should unzip the contents under ejdk131_03)4 Go to your desktop and right-click on My Computer and bring up the properties5 Click on the Environment tab6 Enter the following

Variable JAVA_HOMEValue ejdk131_03

7 Click on OK

Installation1 Download ORION from httpwwworionservercom

on the left-side nav of the screen click on Stable binaries under the Downloadsection

save the file to your favorite local directory

2 Open the downloaded file orion152zip and extract the contents to eorion (thisfolder will be automatically created when you check the ldquoUse foldersrdquo option inWinZip)

3 This is from the orion docscopy toolsjar from ejdk131_03lib into eorion tomake jsprsquos work

6

ConfigurationCreate a J2EE compliant directory structure To do this follow the steps

1 Create the following directory Eservletscraft This will be your applicationrsquos rootdirectory

2 Under the craft folder create the following directory structure

craft|___images|___WEB-INF

|___classes|___libFolder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

3 Create a file named webxml and save it in eservletscraftWEB-INF then pastethe following code

ltxml version=10gtltDOCTYPE web-app PUBLIC -Sun Microsystems IncDTD Web Application22EN httpjavasuncomdtdweb-app_2_2dtdgt

ltweb-appgt

ltweb-appgt

This file contains the applicationrsquos configuration information Right now itrsquos empty but thewebserver still expects to find this file or else it wonrsquot startup the application

4 To let ORION know about your new application (the one you just created above) youneed to enter some stuff in the ORION xml files To do this

go to EORIONCONFIG open applicationxml using a text editor enter the following information (in bold) right after the tag ltweb-module

id=rdquodefaultWebApprdquo path=rdquodefault-web-apprdquo gt

lt-- --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

7

ltweb-module id=rdquoCRAFTrdquo path=rdquoEservletscraftrdquo gtlt-- --gtltpersistence path=rdquopersistencerdquo gt

save and exit the file open default-web-sitexml again using a text editor enter the following information (in bold)

lt-- The default web-app for this site bound to the root --gtltdefault-web-app application=rdquodefaultrdquo name=rdquodefaultWebApprdquo gt

lt-- --gtlt-- get name from applicationxml ltweb-module id=rdquothis will be the namerdquopath=rdquocrdquogt --gtltweb-app application=rdquodefaultrdquo name=rdquoCRAFTrdquo root=rdquocraftrdquo gt

lt-- --gt

saveexit the file

5 Go to the command prompt and go to eorion

6 Start the server by typing java -jar orionjar on the command line

7 If everything was setup properly you should see the message Orion152 initialized

8 Create an html file named pagehtml and save it in Eservletscraft then pastethe following code

lthtmlgtltheadgt ltheadgtltbodygtltdiv align=centergtlth1gtHELLO WORLDlth1gtltdivgtltbodygtlthtmlgt

9 To test your webserver

bring up a browser (IE or NS) type in httplocalhostcraftpagehtml You should see proverbial HELLO

WORLD on your browser

8

(Hint While Windows itself is not case-sensitive unlike AIX the URL should thatyou type in the browserrsquos address line should match the entry in the xml file)

10 Congratulations yoursquore a survivor

ReviewThe following information is worth rememberingDIRECTORY STRUCTURE

craft|___images|___WEB-INF

|___classes|___lib

Folder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

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

9

Lesson 2 - VisualAge for JAVAWebSphere TestEnvironment configurationThis is a minimalist instruction on how to configure your WebSphere Test Environment(WTE) in VAJava to start serving web applications It walks you through the steps increating a CRAFT application and testing the setup to make sure that is runs It shouldtake an hour (or more) to complete this exercise

InstallationInstall VAJava 40 (easy to say huh) You should already have it in your workstationCheck that the WebSphere Test environment is installed in VAJ By selectingWorkspaceToolsWebSphere Test Environment VAJ should tell you if itrsquos there or not If not

Select FileQuick StartSelect FeaturesAdd FeatureSelect WebSphere Test Environment 353 from the list and click OK

Configuration1 Create the following directory structure under eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_host (whew)

craft|_images|_WEB-INF

|_classes

Folder Descriptions

craft - root directorycontains html and jsp filesimages - contains image filesWEB-INF - is not automatically recognized by WebSphere but wersquoll create this so wecan create a pseudo-J2EE directory structureclasses - again not automatically recognized by WebSphere wersquoll create this for thesame reason as the previous folder

2 Create a file craftwebapp and put the following text in the file

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegt

10

ltservletgtltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtinvokerltnamegtltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegt

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

11

ltvaluegtindexhtmlltvaluegtltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

3 To let WTE know about your new application go to the directory eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmentproperties and open the file defaultservlet_engine using a text editorAdd the following text

Look for this tag ltwebsphere-servlet-host name=rdquodefault_hostrdquogt and paste the followingtext right after it

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

UsageThis section will walk you through how to test if your WTE configuration is correctly setup1 Create a file named indexhtml and save it in eappsprogram

filesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft then paste the following code

ltHTMLgtltHEADgtltMETA NAME=GENERATOR Content=NetObjects ScriptBuilder 30gtltTITLEgtWebSphere Test Environment Index PageltTITLEgtltHEADgtltBODYgtlth1gtThis is the index page for the WebSphere Test Environmentlth1gtltBODYgtltHTMLgt

2 Bring up VAJava

3 Select WorkspaceToolsWebSphere Test Environment

4 Click on Start Servlet Engine

12

5 When the message at the lower left says ldquoServlet engine is startedrdquo bring up abrowser

6 Type in this URL httplocalhost8080craft

If the installation is successful yoursquoll get the following message on your browser This is the index page for the WebSphere Test Environmentif not wersquoll take a look at your problem

7 Thatrsquos itnow on to greater 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

13

Lesson 3 - Servlet primerHerersquos the next installment on the web-application development crash-course You willcreate your first servlet which will hopefully give you a basic understanding of whatservlets are and how they work I gave examples on how to deploy the code both in VAJWTE and in Orion so you can continuously compare the two web environments This willgo on for the next few lessons and then when we get to Struts wersquoll just retain theWebSphere Test Environment which is where we should be developing our codes

BasicsServlet

body of java code that extends a java-enabled serverrsquos functionality listens to requests and usually sends back a response to the client Can also pass

processing on to other servlets does not have a main() method so it cannot run outside of the servlet container to create a servlet we generally extend the class HttpServlet which is a subclass of

GenericServlet HttpServlet makes use of the HTTP protocol

Servlet life-cycle

An HttpServlet contains the following methods

init() doGet()doPost() destroy()

When a servlet is first invoked the servlet container calls the servletrsquos init() method thenit calls either the doGet() or doPost() method

For subsequent requests only the doGet() or doPost() method is called A separatethread is created for every doGet()doPost() invocation so different requests will not runinto each other We place the majority of our code in either of these methods

When the servlet container is shutdown it calls the servletrsquos destroy() method

RequestResponse paradigm

Uses HTTP which is a stateless protocol

In itrsquos simplest form

client sends a request and servlet receives request (and response) object which mayhave objects attached to it (parameters or attributes RemoteUser etc)

14

servlet processes the request (access a db contruct an html response forward toanother servlet etc)

client receives some form of response from the servlet and renders the output to the browser

Your first servletIn VAJ

1 Create a project named TRAINING2 Create a package named comffictraining3 Create a class named HelloWorldServlet4 Add these codes to HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

Code Walkthrough

1 To make HelloWorldServlet a servlet it needs to extend HttpServlet

public class HelloWorldServlet extends HttpServlet

2 We will then need to implement one of the following methods

doGet()doPost()

In this example we implemented the doGet() method

public void doGet(HttpServletRequest 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

15

3 Inside the doGet()

we set the content type for the response to texthtml since we intend to send back anhtml response

responsesetContentType(ldquotexthtmlrdquo)

4 We then retrieve the PrintWriter from the response so we can start writing our outputto it

PrintWriter out = responsegetWriter()

5 Lastly we start writing our output

outprintln(ldquolth1gtHello worldlth1gtrdquo)

After executing the last line of code the servlet returns control back to the web containerwhich sends the response back to the client Since we added stuff in the response theclientrsquos browser will attempt to render it

Deploying the codeVAJava (WebSphere Test Environment)

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (this can be the last entry just beforethe

ltwebappgt tag)

ltservletgtltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

Orion

16

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgtltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in ldquoHello Worldrdquo being displayed on your browser

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

17

Lesson 4 - Database ConnectivityBefore we move on to other web components we need to briefly go through the topic onconnecting to a database and retrieving information from the tables This will make thenext few topics a lot more interesting since you will be displaying data on the browser thatwere retrieved straight off of the db instead of flooding your servlet with ldquoset-this set-thatvaluerdquo lines of codes

After going through this exercise it will become more obvious that this is not the real-world way of creating and maintaining connections to a database Creating a connectionfor each sql to be executed is a pretty expensive operation In later exercises we willexplore how to create a pool of connections using DataSource and the methods withwhich this datasource is maintained and accessed (the FFIC way of course)This section discusses the java code required to connect to a database and execute sqlto retrieve data

Preparation1 You should have the IOU database information entered in your UDB-client with the

following details

DB Alias = IOUODBC entry = IOU (not really needed in this exercise but check it anyway)

2 We will be using the DB2 driver to create the connection to our database If youhavenrsquot done so import the db2javazip file into your VAJ ide

create a DB2 DRIVER project import db2javazip from EAPPSSQLLIBjava into your newly created project

using the following option ldquoimport as a Jar filerdquo

3 For ORION copy the file db2javazip to EservletsORIONcraftWEB-INFliband rename it to db2javajar

CodingIn your TRAINING project create a class JDBCSample in the comffictraining packageand paste the following code in it

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcapp

18

import javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(ldquoDivision ldquo + ldquoCoderdquo + ldquo ldquo + ldquoDescriptionrdquo) while (rsnext())

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

19

String s = rsgetString(1)String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

CODE WALKTHROUGH

1 We need to import the following packages so the program can load the necessaryjdbc classesdrivers

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

2 We define variables for the sql to execute and the useridpassword needed to accessthe database Obviously you must change the userpassword if you have a differentone We also specify here the driver that we will use to create a connection to thedatabase (DB2 in this case)

String query = ldquoSELECT FROM IOUDIVISIONrdquoConnection conn = nullStatement stmt = nullString user = ldquoiccw0t00rdquoString password = ldquoiccw0t00rdquoString driver = ldquoCOMibmdb2jdbcappDB2Driverrdquo

3 This trycatch block attempts to load the database driver and create a connection

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)

20

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)

4 When a connection is successfully created the next trycatch block creates aStatement from the connection and executes the sql that we defined earlier

try 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 )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

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 JDBCSample class and select Run

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

21

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 JDBCSample 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

The output should look similar to the following

loading driverconnectingtojdbcdb2IOUconnectedDivision Code Description1 CID Involuntary 2 CID Voluntary 3 PID 4 CID Specialty 10 National Accounts 11 Jefferson Insurance 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

22

END

NEXTLetrsquos try what we just learned using our servlet example

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

23

Lesson 5 - ServletDatabase Connectivity From the last two lessons you learned to a) construct a simple servlet and b) create ajava program that retrieves data from a database Now we will combine the two andcome up with a servlet that accesses the database and displays the result (ResultSet) ona browser

PreparationRemember your two previous programs If not here are the source codes

HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServletpublic void doGet(HttpServletRequest request

HttpServletResponse response)throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

JDBCSample

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

24

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try 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 )

stmtclose()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

25

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

Before you proceed briefly review how each of the programs work so it will be mucheasier to understand the codes belowthatrsquos all

CodingWith a little tweak (additional codes) the code below shows a combined version of thetwo programs we previously created You can cut and paste it in your HelloWorldServletin VAJ

The blue portion is the HelloWorldServlet while the red portion shows theJDBCSample

You will also notice that there are codes in green These lines of codes were added toaccomodate the codes for JDBCSample and to properly display the output to thebrowser

import javaioimport javaxservletimport javaxservlethttp

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

public class HelloWorldServlet extends HttpServletString query = SELECT FROM IOUDIVISIONConnection conn = nullStatement stmt = nullString user = iccw0t00String password = iccw0t00String driver = COMibmdb2jdbcappDB2Driver

HelloWorldServlet constructor comment

26

public HelloWorldServlet()

super()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() outprintln(lth1gtHello worldlth1gt)

try

stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(Division Code + + Description) outprintln(lth2gtDivisionlth2gt) outprintln(lth3gtCode Descriptionlth3gt)

while (rsnext()) String s = rsgetString(1)

String ln = rsgetString(2) Systemoutprintln(s + + ln )

outprintln(lth3gt + s +ampnbspampnbspampnbspampnbspampnbspampnbspampnbsp + ln + lth3gt)

stmtclose()

conclose()

catch(SQLException ex) Systemerrprintln(SQLException + exgetMessage())

Insert the methods description here Creation date (42402 22142 PM) public void init()

try Systemoutprintln(loading driver) ClassforName(driver) String url = jdbcdb2IOU Systemoutprintln(connectingto + url) conn = DriverManagergetConnection(urluserpassword) Systemoutprintln(connected)

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

27

try catch(ClassNotFoundException ex) Systemoutprintln(Couldnt load jdbc driver) Systemoutprintln(ex) catch(SQLException ex) Systemoutprintln(Database Problem) Systemoutprintln(ex) catch(Exception ex) Systemoutprintln(Some other problem) Systemoutprintln(ex)

CODE WALKTHROUGH

Irsquove pretty much gone through the codes line by line in the previous lessons What needs to be mentioned here is that a method called init() was added and the codesthat load the DB2 driver and create the connection were added here

Insert the methodrsquos description hereCreation date (42402 22142 PM) public void init()

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

28

Systemoutprintln(ex)

When a servlet starts up the first thing it looks for is an init() method and it executes thismethod once within itrsquos lifetime It is good practice to place initialization stuff in thismethod especially when we only need to run these once A good example is creating aconnection to the database and this is just what we did with this exampleNote As with the init() method a servlet also has a destroy() method which is calledwhen it shuts down

Deploying the codeDeploying the code to VAJ and ORION is the same as in the servlet lesson I listed ithere again just in case you donrsquot have that lesson anymore

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (can be the last entry just before the ltwebappgt tag)

ltservletgt

ltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

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

29

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in the following output on your browser

30

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

31

Lesson 6 - Servlet RedirectionThis lesson briefly covers one of the more important features of servlets which isforwarding or redirecting In simple terms redirection is passing control to another entitywhich can be a servlet html or jsp at the same logical level It works pretty much like anxctl in CICS with some differences There are two types of redirection client-side andserver-side and these are described in the following section

BasicsClient-side redirection

The redirection happens at the client-side and the URL on the browserrsquos address linechanges to the URL that was sent to it User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and sends a message

(redirect) to the browser containing a URL which the browser will load The browser receives the redirect from the servlet and loads the URL that was sent

to it

Note The URL in the redirect can be another servlet html or a jsp file

To illustrate this process

BROWSER==gtservlet==gtBROWSER==gtresult(jsphtmlservlet)

Client-side redirection is useful when after a servlet processes you want to navigate theuser to another page where even if he reloads that result page will not cause the servletto re-execute In other words the user is navigated to a safe place where he canrsquot hurthimself or the application

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoresponsesendRedirect(url)

if you want to retrieve the original URL to redirect the servlet to itself do this

String url = requestgetRequestURI()responsesendRedirect(url)

Note the getRequestURI() method leaves out the parameters if any that wereincluded in the original URL You can use the requestgetParameter() to retrieve theparameters and attach them to the url

32

Server-side redirection

The redirection happens only at the server-side and the browser does not know anythingabout it The URL on the browserrsquos address line does not change

User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and forwards itrsquos output to

another servlet jsp or html The receiving sevlet jsp or html renders the output to the browser

To illustrate this process

BROWSER==gtservlet==gtresult(jsphtmlservlet)

Server-side redirection is used to combine several operations to make them appear asone without involving the clientrsquos browser This cuts down traffic between the server andthe browser The browser will receive the result only after the last of the processes hasreleased the output to the web container

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

PreparationThis exercise involves server-side redirection The idea is to have one servlet receive therequest from the browser and perform a redirect to another servlet which will retrieve datafrom a db and construct the html output to be rendered on the browserWe will need the HelloWorldServlet servlet for this exercise which will act as the receivingservlet All we need to contruct is the servlet that will forward the processing toHelloWorldServlet

CodingIn VAJ create a new class called ControllerServlet in the package comffictraining andpaste the following code to it

import javaioimport javaxservletimport javaxservlethttp

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

33

public class ControllerServlet extends HttpServletpublic void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionString url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

1 We define ControllerServlet as a servlet by extending HttpServlet

public class ControllerServlet extends HttpServlet

2 These lines construct the URL of the receiving servlet and performs the redirection

String url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtControllerltnamegtltdescriptiongtDB access servletltdescriptiongtltcodegtcomffictrainingControllerServletltcodegtltautostartgttrueltautostartgt

ltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

34

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtControllerltservlet-namegtltservlet-classgt

comffictrainingControllerServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

35

You can verify that the servlet did a server-side redirect if the URL on the browserrsquosaddress line did not change It should still show

httplocalhost8080craftservletController for WTE

or

httplocalhostcraftservletController for ORION

WATCH OUT NEXT FORJAVA BEANS

36

Lesson 7 - JavaBeansUp to this point we have been dealing mostly with webserver configuration andprocedural java codes In this lesson we will start to incorporate object orientation in ourexamples using javabeans

BasicsIn our example programs we created data in our servlet by retrieving information fromthe database and by assigning values to variables There will be times when we want topass this data around and manipulate them before we send them to the browser fordisplay A convenient way of doing this is to encapsulate all these related informationhide them in an object and provide methods to access each value To accomplish thiswe create a java class called javabean or bean that contains only private variables andsettergetter methods for each of these variables For instance we can create a bean called divisionBean and store each row that weretrieve from the database to a divisionBean instance We can then put all these beansinside a collection object that we can pass around and eventually render to the browserSounds confusing Letrsquos do an example then

Coding1 In VAJ create a class called DivisionBean in comffictraining package and paste the

following in it

public class DivisionBean private String divNoprivate String divDesc

public String getDivDesc()return divDescpublic String getdivNo()return divNopublic void setDivDesc(String divDesc)thisdivDesc = divDescpublic void setDivNo(String divNo) thisdivNo = divNo

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

37

2 Open your HelloWorldServlet and make the following changes

Add the following code right after the class declaration

ArrayList divList = new ArrayList()

In the doGet() method

delete the following lines or better yet just comment them out (ie put a beforeeach line)

String s = rsgetString(1)

String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )outprintln(ldquolth3gtrdquo + s + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + ln + ldquolth3gtrdquo)

add the following lines within the while loop

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

after the while loop add the following lines of code

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

Code Walkthrough

DivisionBean

1 We defined the two variables divNo and divDesc as private to prevent them frombeing accessed directly (ie divisionBeandivNo)

private String divNoprivate String divDesc

38

2 We then define getters and setters for the two variables

public String getDivDesc()

return divDesc

public String getdivNo()

return divNo

public void setDivDesc(String divDesc)

thisdivDesc = divDesc

public void setDivNo(String divNo)

thisdivNo = divNo

HelloWorldServlet

1 We defined an Arraylist (called divList) which part of the java collections to containthe instances of the beans that we create

ArrayList divList = new ArrayList()

2 In the while loop we instantiate a new divisionBean and set itrsquos variables to thevalues that we retrieve from the db The we add that instance to divList

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

3 After wersquove gone through the entire resultset we loop through divList and create anhtml output for each instance of the bean in the ArrayList The code provided here ispretty much boiler plate code

retrieve an interator from divList (all collections have an interator)

Iterator iterator = divListiterator()

the interator has methods that loop through the ArrayList object (hasNext()) andto retrieve each item (next())

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

39

while (iteratorhasNext())

when an item is retrieved it has to be cast back to the original object In thiscase we cast the item back to DivisionBean

DivisionBean divbean = (DivisionBean) iteratornext() outprintln(ldquolth3gtrdquo +divbeangetDivNo() + ampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +divbeangetDivDesc() + ldquolth3gtrdquo)

Enhancement idea

You may ask ldquoWhy put more code that does the same thing as the originalrdquo

The answer is that creating beans and storing them in collections (or even if you justhave a single bean) enables you to attach this object to for example the request object(ie requestsetAttribute(ldquodivisionListrdquodivList)) and perform a forward to another servletthat contains code (such as the while loop with the iterator) that performs the creation ofthe output to the browser In this case the components can be further divided into thefollowing

ControllerServlet - receives the request from the browser and forwards it toHelloWorldServlet

HelloWorldServlet - retrieves data from the db stores the results inbeanscollection attaches the collection to the request object then performs aserver-side redirect to another servletjsp which we can call DisplayServletDisplayServlet - retrieves the collection from the request object and builds thehtml output while iterating through the collection

This approach enables you as the programmer to assign specific tasks to eachcomponent and keep them loosely coupled so that you can easily change onecomponent without making massive changes to the rest of your application As anexample you can change HelloWorldServlet to access another database (other thanDB2) without affecting the two other servlets in the chain

Deploying the codeVAJ

1 Bring up WTE and start the servlet engine

2 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

40

ORION

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Start ORION (eORIONjava -jar orionjar)

3 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

41

42

Lesson 8 - Object ScopeThis lesson is a sidetrip to learning the concept of object scope We need to cover thisimportant topic before we head on to JSPrsquos (are we there yet)

BasicsIn the previous lesson we learned to create javabeans and put them in a collection(called divList) to be processed by another set of codes within the same servlet We alsotoyed with the idea of creating another servlet (DisplayServlet) that will construct the htmloutput from this collection Since we want to pass the collection from HelloWorldServletto DisplayServlet we need to somehow associate the collection object with a particularscope When we perform a server-side redirect the request and response objects arepassed as arguments in the forward method Before we actually forward the process toanother servlet we make sure that we associate the collection object to the requestobject so that the receiving servlet can access that collection This is an example of anobject scope and in this instance we defined the collection to be in the request scope

A simple definition of Object Scope is the level of availabilityvisibility of an object withinthe application

It can be any of the following

page - object is visible in the page that created itrequest - object is visible in the request to which is belongssession - object is visible in the same session where it was created application - object is visible within the entire application Any servlet regardless of

what session created them can access the object in this scope

To associate an object to a particular scope we use the setAttribute() method If we want to say make the divList collection available to a userrsquos session we use thefollowing code

HttpSession session = requestgetSession(true)sessionsetAttribute(ldquodivListrdquodivList)

so long as the session still exists we can extract that collection at any point within theapplication with the following code

HttpSession session = requestgetSession(true)ArrayList divList = (ArrayList) sessiongetAttribute(ldquodivListrdquo)

Note We have to cast the collection back to itrsquos original form which is an ArrayList

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

43

Letrsquos create the DisplayServlet that we discussed in the previous lesson

1 Create a class called DisplayServlet in your TRAINING project in the packagecomffictraining and paste the following

import javaioimport javaxservletimport javaxservlethttp

import javautilpublic class DisplayServlet extends HttpServlet

ArrayList divList = new ArrayList()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionresponsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCodeDescriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() +ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

2 Open HelloWorldServlet and make the following changes

comment out the following lines of code in the doGet() method

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCode Descriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +

44

divbeangetDivDesc() + ldquolth3gtrdquo)

add the following lines of code after the stmtclose() line

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

Display Servlet

1 We define DisplayServlet by extending HttpServlet

public class DisplayServlet extends HttpServlet

3 Define an ArrayList to contain the collection that this servlet will receive fromHelloWorldServlet

ArrayList divList = new ArrayList()

4 Set the content type and get the output writer from the response so we can startwriting output data to it

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()

5 Retrieve the divList collection from the request object and cast it back to an ArrayList

divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)

6 Create the html output while iterating through the collection

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

HelloWorldServlet

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

45

1 The lines that we removed from this servlet were transferred to DisplayServlet

2 In the lines that we added we associate the divList collection with the request objectand then do a server-side redirect to DisplayServlet

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquo

RequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtDisplayltnamegtltdescriptiongtDisplay Outputltdescriptiongt

ltcodegtcomffictrainingDisplayServletltcodegtltautostartgttrueltautostartgtltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtDisplayltservlet-namegtltservlet-classgt

comffictrainingDisplayServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

46

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

47

Lesson 9 - Java Server Pages (JSP)BasicsIn the previous lessons we had been constructing our html response within the servletitself It works well with simple html outputs but later on as your webpages get morecomplicated you will find (or you may already have) that this will not work for real-worlddevelopment Java Server Pages (JSP) technology was introduced to make life easier forus programmers and for web designers How If yoursquore familiar with HTML JSP isbasically an html page with little (thatrsquos the plan) java code You get to construct your htmlpage as you normally would and start putting in java logic to a) iterate through acollection of beans b) to include output from another jsp and more To create a jsp filefrom a static html file simply change the filersquos extension from html to jsp and yoursquoreready to go But wait therersquos moreBefore we move on also remember that a jsp is first converted and compiled into aservlet by the web container before it is executed so it will have a similar life cycle as thatof a servlet Inside the jsp file we can put java codes to create dynamic output on thebrowser We accomplish this by using scriptlets expressions declarations and directiveswhich are described below

Scriptlet lt

Scriptlets are regular java codes that are automatically executed by the jsp containerwhen the jsp is invoked so they should be syntactically correct

lt String i = ldquofoordquoSystemoutprintln(i)

gt

Expression lt=

Expressions evaluate to a value that is directly displayed on the browserlt= i gt

The example is converted to outprintln(i) by the jsp container and the value of ldquoirdquo isdisplayed on the browser

Declarations lt

Declarations are java codes that are not automatically executed by the jsp container butmay be invoked if you call it from a scriptlet

lt static printName (String name) Systemoutprintln(name)

gt

48

You can invoke this by writing a scriptlet such as

lt printName(ldquoMyNamerdquo) gt

Directives lt

Directives desribe the necessary components of a jsp

lt page import=rdquojavautilcomffictrainingrdquo gt ==gt imports necessary packageslt taglib uri=rdquobeanrdquo prefix=rdquobeanrdquo gt ==gt declares a taglib referencelt include file=rdquoextraInfojsprdquo gt ==gt includes output from another jsp file

Coding

Suppose the web designer (if there is one) hands you this html file (DisplayDivhtml) lthtmlgtltbodygtlttable border=1gt

lttr align=left gtltthgtDivision IDltthgtltthgtDescriptionltthgtlttrgtlttr align=leftgtlttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgtlttdgt2lttdgtlttdgtCID Voluntarylttdgtlttrgt

lttablegtltbodygtlthtmlgt

The browser output looks like this

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

49

So you the java programmer need to convert this layout to a dynamically generated htmlfile

KNOWN

The data will come from the IOUDIVISION table You already have the servlets (ControllerServlet and HelloWorldServlet) necessary to

perform data retrieval from the db You have a DisplayServlet servlet that creates html output but you want to use a jsp

since you already have the html code and you just need to insert the necessary javacodes to render the dynamic output correctly

HINT We created javabeans (DivisionBean instances) containing Division information and

put them in a collection (divList) that is associated with the request object In our jsp file we can retrieve this collection and iterate through them pretty much the

same way we did with DisplayServlet So most of the codes that we have inDisplayServlet can be reused in the jsp file

Code Walkthrough

1 If you saved the above code in DisplayDivhtml simply rename it to DisplayDivjsp tomake it a jsp file

2 At the topmost portion paste the following code

lt page import=rdquojavautilcomffictrainingrdquo gt

This tells the jsp page that your scriptlets will be looking for necessary classes in thesepackages

3 To display the division code and description we have to insert codes that iteratethrough the collection and render them inside the table

Just after the table header definition (The ones with the ltthgt ltthgt tags) make thefollowing changes

delete the following lines of codes since these are just representations of what thedynamic portion of the page are

lttr align=leftgt

lttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgt

lttdgt2lttdgt

50

lttdgtCID Voluntarylttdgtlttrgt

insert the following codes

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()gt

Notice that this is strikingly similar to the code in DisplayServlet Thatrsquos because we justcut and paste it from there Even though the loop is not yet complete we terminated these lines of code with a ldquogtrdquo because we need to pasteregular html tags or non-java codes right after it

4 Once the above code starts iterating through the collection we need additional codesto render the details so paste the following code right after it

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

Here we used expressions to execute the ldquogetrdquo methods of the DivisionBean instance toretrieve the division code and description

5 Now this is where most beginners get bit We need to properly terminate the ldquowhilerdquoloop that we started in the previous steps To do this paste the following code rightafter the previous step

lt End whilegt

The completed code looks like the following

lt page import=rdquojavautilcomffictrainingrdquo gtlthtmlgtltbodygtlttable border=1gt

lttr align=leftgtltthgtDivision IDltthgtltthgtDescriptionltthgt

lttrgt

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

51

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()

gtlttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End whilegt

lttablegtltbodygtlthtmlgt

HelloWorldServlet

Open HelloWorldServlet and make the following changes

1 Remove the following line of code

String url = ldquoservletDisplayrdquo

2 Replace it with the following line of code to forward the process to DisplayDivjspinstead of DisplayServlet

String url = ldquoDisplayDivjsprdquo

Deploying the codeVAJ

1 Be sure to save DisplayDivjsp in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

52

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Save the DisplayDivjsp file in eservletscraft3 Start ORION (eORIONjava -jar orionjar)4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

53

Lesson 10 - Custom TagsBasicsIn Lesson 9 you learned how to create a JSP to handle content rendition in place of aservlet Wersquove seen how the same codes that we used in the servlet can be re-appliedinside the JSP using scriptlets expressions declarations and directives Again as yourJSPs get more complicated you will want to reduce the amount of java codes in themespecially codes or logic that are candidates for re-use in other JSPs In our exampleprogram if you want the logic that displays the Division information in more than oneJSPs you may want to put that body of code in a central place where you can just call itfrom different JSPs Otherwise you will end up copyingpasting the same codes in everyJSP that needs these codes

Starting with JSP 11 a feature was introduced wherein java codes can be encapsulatedand represented on the JSP using custom tags Custom tags are not unlike HTML tags(ie lthtmlgt ltformgt lttablegt etc) except that we provide the logic that makes the tagswork An example is to replace the scriptlets in your JSP with one tag such asltapplistDivision gt and this will take care of displaying the list of division codes anddescriptions JSP 12 introduced more enhancements to the custom tag feature such asIterationTag but we wonrsquot cover it here since FFIC still uses JSP 11 in WebSphere

Anatomy of a Tag

ltmytaggtvalueltmytaggt

ltmytaggt - opening tagvalue - body of the tagltmytaggt - closing tag

Custom Tag components

1 Developer-provided class that extends the classjavaxservletjsptagextTagSupport TagSupport is a helper class that implementsthe Tag interface When you write your custom tag you will need to implement atleast one of the two most used methods

doStartTag()

triggered when the opening tag is encountered return SKIP_BODY if you donrsquot want to evaluate the body of the tag return EVAL_PAGE_INCLUDE to evaluate the body of the tag

doEndTag()

triggered when the closing tag is encountered return EVAL_PAGE to continue processing the rest of the JSP

54

return SKIP_PAGE to halt processing of the JSP

2 TagLib Descriptor An XML file that describes the custom tag and the class thatimplements the logic

Example

You can save this in a file named apptldltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomfficexamplestrutsDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

3 WEBXML appWEBAPP entry ndash describes the location of your taglib descriptorand assigns a URI to be used in your JSP

Example

lttaglibgtlttaglib-urigtcraftlttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 JSP Directive ltndash tells your JSP that you will be using a custom tag what itrsquos URIis and how you will reference it in your page (using a prefix)

Example

Place this at the top of your JSP

lttaglib uri=WEB-INFapptld prefix=app gt

With these components in place you can start using custom tags in your JSPs

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

55

CodingNow letrsquos create a custom tag out of the scriptlets that we have in DisplayDivjsp

1 In VAJ in the package comffictraining create a class named DivisionTag andpaste the following codes

Insert the typersquos description here Creation date (1802 11910 PM) author Administrator

import javautilimport javaxservletjsptagextTagSupportimport javaxservletjsp

public class DivisionTag extends TagSupportHere we used the doEndTag() method to start evaluating after the body In thiscase there is no bodypublic int doEndTag() throws JspException We retrieve the collection (divList) from the request that is forwarded byHelloWorldServletArrayList divList = (ArrayList)pageContextgetRequest()getAttribute(ldquodivListrdquo)

We then iterate through the collection as we did before and write the output tothe outputstream of the pagetry Iterator iterator = divListiterator()

while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()pageContextgetOut()print(ldquolttr align=leftgtlttdgtrdquo + divbeangetDivNo() +ldquolttdgtlttdgtrdquo + divbeangetDivDesc() + ldquolttdgtlttrgtrdquo)

pageContextgetOut()print(ldquolth3gthelplth3gtrdquo) catch (Exception e) throw new JspException(etoString())

We return eval page to tell the JSP to continue processing the rest of thepage if anyreturn EVAL_PAGE

2 We then need to create a taglib descriptor for this new class Create a file namedapptld and paste the following code

56

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomffictrainingDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

lttaglibgt

3 We then need to tell the webserver about this taglib descriptor In the webxml file(only for Orion) lttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 Copy the DisplayDivjsp to a new JSP file named DisplayDivTagjsp and make thefollowing changes

Remove the following lines of code

lt page import=rdquojavautilcomffictrainingrdquo gt

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext())

DivisionBean divBean = (DivisionBean) inext()gt

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End while(ihasNext())

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

57

gt

At the top of the jsp add the following

lttaglib uri=WEB-INFapptld prefix=app gt

This tells the JSP to use apptld and that we will reference this as app allthroughout the page

Just below the table heading tags add the following line of code

ltapplistDivision gt

This invokes the DivisionTag class and starts writing the output to the page

5 Finally open HelloWorldServlet and make the following changes

In the doGet() method remove the line

String url = ldquoDisplayDivjsprdquo

Replace it with

String url = ldquoDisplayDivTagjsprdquo

Deploying the codeVAJ

1 Save the DisplayDivTagjsp in the Javaideproject resourcesIBM WebSphereTestEnvironmenthostsdefault_hostcraft folder

2 Bring up WebSphere Test Enviroment and start the servlet engine

3 Bring up a browser and type the following in the address line

httplocalhost8080craftservletController

ORION

1 Export HelloWorldServlet and DivisionTag to eservletscraftWEB-INFclasses

2 Save DisplayDivTagjsp in eservletscraft

3 Start Orion (eORIONjava ndashjar orionjar)

4 Bring up a browser and type the following in the address line

httplocalhostcraftservletController

58

Result

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

59

Lesson 11 - Model-View-Controller Design PatternBasicsIf you got this far and have understood the previous lessons then you can pat yourself onthe shoulder and say that yoursquore ready to put things together Actually you already haveWe just need to give what yoursquove been doing these past few lessons a catchy name andthat too is already done Over the years as java technology developed design patternsstarted to emerge As these patterns are recognized the most effective ones enduredand took on lives of their own One of these patterns which according to old-timers wasused to program Smalltalk applications is called Model-View-Controller or MVC for shortMVC is also called JSP Model 2 architecture Is there a Model 1 Yes there is and wersquollbriefly discuss the differences between the two models

JSP Model 1

This architecture puts the responsibility of acting on a user input accessing a db andmaintaining application state solely on a single JSP This may do for small applicationsbut not for complex ones The programmer will end up flooding the JSP with tons andtons of scriptlets and other java codes that should logically reside somewhere elseMoreover it is very difficult to coordinate the actions of all JSPs within the applicationsince they are not designed to communicate with each otherBelow is a ldquoreusedrdquo diagram of a JSP Model 1 architecture

JSP Model 2 (MVC)

This architecture extends the Model 1 concept by separating the content rendition (View)function from the application state (Model) and then adding a Controller that conducts theflow of processes within the application This provides for a clean separation ofresponsibilities between each component which results in a clearer definition of roles forweb designers and java programmers

60

Here is another ldquoreusedrdquo diagram and this time of a JSP Model 2 architecture

MVC is composed of obviously a model a view and a controller each of which havespecific functions which are described as follows

Model - represents the state of the application at any given point in time

View - renders the state of the application to the user It also receives user input andsend it to the controller for proper disposition

Controller - acts on a user input determines what action needs to be done delegatesthe action to the required business logic and invokes the Model to change itrsquos state asnecessary

There is no exercise for this lesson I thought Irsquod give you a break before we proceed withthe next one Think of this as the ldquocalm before the stormrdquoHowever letrsquos go through what yoursquove put together so far and try to match theservletsjsp against the MVC components

ControllerServlet (controller) - this contains the beginnings of a controller servlet Bytyping in the URL for this servlet on the browserrsquos address line we are asking it toperform a service for us Inside itrsquos doGet() method it knows that it needs to delegate thetask to HelloWorldServlet which performs the db access and creation of javabeans

HelloWorldServlet (model) - creates and maintains the Model for this little webapplication by storing the data in javabeanscollection It then notifies the View that theModel has changed and that it needs to render the new state

DisplayDivjsp (view) - this jsp page does not know what is happening inside theapplication All it knows is that it gets a notification from the Model that itrsquos state haschanged and that the View needs to re-render it

There we have a mini-MVC application running in our web container Of course it takesmore than a couple of servlets and a jsp to create a real-world web application and thatrsquos

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

61

what we aim to do in the next lessons Keeping this design pattern in mind we are thenready to make a quantum leap to using a framework called STRUTS that implementsthis design pattern I will save the discussion on STRUTS for the next lesson All youneed to know at this point is that STRUTS solves most of the problems (or I should saychallenges) that you will encounter when you try to build your own MVC applicationframework

6

Lesson 12 - Introduction to the Struts FrameworkApplications are generally composed of two major components business-specificcomponents and application services As an application programmer your focus tends tobe more on coding business components rather than application services since thedevelopment life-cycle is really all about gathering business requirements and creatingsystem solutions for them You will just want to be able to code your applicationrsquosbusiness functions and tie them together to create an entire process

Waawa

T

If yoursquore familiar or had worked on CICS applications then it will be easier to graspthe concept of frameworks and what they do to speed up application developmentWhen putting together a CICS application yoursquoll typically need the followingcomponents

1 Entries for CICS tables such asFile Control Table (FCT) ndash contains file aliases (tied to physical file names) to beaccessed in the CICS region (QSAM VSAM etc)

Program Control Table (PCT) ndash defines the relationships between programs andthe files they use

Program Properties Table (PPT) ndash defines the program names transaction idsand typeTerminal Control Table (TCT) ndash contains terminal definition that canaccess the CICS region

2 The symbolic and physical maps (mapsets) for the screen definitions3 CICS programs that contain the flow of the application and business logic

functions4 In the CICS startup jcl you need to put information such as load libraries (should

be in the correct order) of your programs

Once you correctly define and build these components CICS has the responsibility oftying these components together and making sure that when a user types aTransaction ID it will invoke the correct program for it and assign the correct files tothe program Unless you have too much time on your hands you do not want to findout how CICS performs these underlying processes to run your programs

2

ith application development using java programmers have had to build both businessnd application service layers for every application that they construct Most of thepplication services are so customized to the business that there is no way to reuse themith another application so programmers tend to solve the same problems over and overgain

he solution Enter frameworks

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

63

A couple of years back some genius named Craig McClanahan thought up a java-basedframework (Struts) using the MVC design pattern that is generic reusable andextensible (and of course free) It provides a lot of the application services needed toglue an application together while still giving application developers a lot of control overthe business-specific codes that they write Struts is an open source product available fordownload from wwwjakartaapachecomstruts It has a fairly big and activedeveloperuser community that can help beginners get up to speed in using Struts andanswer Struts-related questions that may not be mentioned in available documentation

Struts provides the following application services among other things

request routing errormessage handling generating client-side scripts tag libraries jdbc connection pooling xml parsing automatic population of java beans internationalization of prompts and messages validation menus page layouts

Struts ComponentsSTRUTS ESSENTIAL CLASSES

Struts employs what is called in J2EE lingo a Front Controller pattern wherein it has asingle servlet that receives all requests from the browser and forwards the processing tothe appropriate class handler In essence we do not need servlets other than the oneStruts provides We may sometimes need to extend the functionality of that servlet but inmost cases the vanilla version will do Below are the frequently used classes in theStruts framework with short descriptions

ActionServlet ndash This is the only servlet in the framework and itrsquos job is to receiverequests populate appropriate javabeans from the request delegate the process toanother class that contains business logic (Action) and forwards the process to the nextcomponent as defined in the mapping

Action ndash a class that performs a specific business function (can also dispatch to abusiness logic bean) and returns control back to the ActionServlet with correspondinginformation as to what to do next

ActionForm ndash a javabean that holds the state of the application Programmers writebeans that extend this class so that the ActionServlet can recognize it and populate itwith data from incoming requests

64

ActionForward ndash contains information that tells the ActionServlet the next componentthat will handle the current request

ActionMapping - contains information on Action classes ActionForms and resource filepaths It is read by the ActionServlet to determine which Action will process a request

ActionErrors ndash contains ActionError objects that may have been created whileprocessing a request The contents can then be rendered on an html page

ActionMessages ndash similar to ActionErrors Contains ActionMessage objects createdwhile processing a request The contents can also be rendered on an html page

JSP AND TAG LIBRARIES

In addition to the Struts classes the content rendition portion of the framework uses JSPand custom tags

Bean Tags ndash used to createcopy beans or render bean properties on the pageHtml Tags ndash used to render html form tagsLogic Tags ndash used to perform logical operations such as comparison andor to check forpresenceabsence of beans in the pageNested Tags ndash used to render nested bean properties on the pageTemplate Tags ndash used to render a composite of several jsp pages by pulling these insidea pre-defined layout

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

65

ldquoI canrsquot find the MVC pattern anywhererdquoOK so herersquos a diagram of the Struts Framework which shows how each of thepreviously discussed components work together

66

In MVC semantics the Controller would be the ActionServlet the Model is handled byAction and ActionForm classes and the View is handled by JSPs and tag librariesDid I mention that Struts works at the Presentation Layer of the application I guess notThis means that it does a swell job of conducting the process flow of programs thatinteract with the user (browser) but developers (thatrsquos you) will still need to come up withthe business objects and the data layer objects So in a bigger picture herersquos a diagramshowing where Struts lies

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

67

Below are UML representations of the different parts of the Struts framework

Action

68

Form

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

69

Message

70

Forward

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

71

Mapping

72

Config

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

73

DynaForm

74

Sequence Diagram for a request

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

75

76

The next lessons will walk you through the installation of the Struts framework in bothVAJavaWebSphere Test Environment and Orion We will also build a sample applicationthat uses most of the Struts features so you can get acquainted on the differentcomponents of Struts and how it fits into you web environment

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

77

Lesson 13 - Installing Struts 11b in VisualAge forJava 40WebSphere Test Environment 353This lesson walks you through the installation of Struts 11b in the WebSphere TestEnvironment in VisualAge for Java 40 It assumes that you already have VAJ 40installed in your workstation and that you have properly configured it using theinstructions in Lesson 2 To make sure that Struts is correctly configured you will need toinstall and run the sample application provided in this lesson

What is missing from this lesson is the explanation for the sample application codes Mygoal here is for the user to quickly setup the environment to run Struts so we can proceedwith the next lessons that discuss the different parts of Struts in greater detail

Installation and configuration1 In VAJ you will need to have the following projects present in your workspace

Servlet API ClassesJava Class LibrariesIBM WebSphere Test EnvironmentIBM Enterprise Extension LibrariesIBM XML Parser for Java

If any of the above is missing

select FileQuick Start from the menu select FeaturesAdd Features from the popup window and select the project

you need to import to your workspace

2 Downloadinstall the following

Note If you have projects in VAJ with the same name as the ones listed below be sureto version them first Then when importing the new packages make sure you selectoption create newscratch editions of versioned projectspackages

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract Xercesjar and import it in VAJava in the project XERCES

Xalan from httpxmlapacheorgxalan-jindexhtml

the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar and import them in VAJava in the project XALAN

78

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip

OPTIONAL

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and import these files to a COMMONS project in VAJava

OR

Recommended

Open the binary distribution of STRUTS and extract all commons jar files and importthem in the COMMONS project in VAJava

Struts 11b source from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1src

link is jakarta-struts-11-b1-srczip import the entire file to a STRUTS project in VAJava

Important

You will need to make some revisions to the Struts source code or you will get the following error Cannotremove Attribute from request scope in your browser I think this problem only occurs in WebSphere

In VAJ go to the orgapachestrutstaglibhtml package and open the FormTag class

Replace the following lines in the doEndTag() method in the FormTag class

pageContextremoveAttribute(ConstantsBEAN_KEY PageContextREQUEST_SCOPE)

pageContextremoveAttribute(ConstantsFORM_KEY PageContextREQUEST_SCOPE)

with the following

pageContextgetRequest()removeAttribute(ConstantsBEAN_KEY)pageContextgetRequest()removeAttribute(ConstantsFORM_KEY)

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

79

3 Open jakarta-struts-11-b1-srczip and extract the following files to eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF

struts-tld dtd xml

Note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 In the directory eappsprogram filesibmVisualAge for JavaideprojectresourcesIBM WebSphere Test Environmenthostsdefault_hostcraftWEB-INF create a file named struts-configxml file and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoISO-8859-1rdquo gtltDOCTYPE struts-config PUBLIC

ldquo-Apache Software FoundationDTD Struts Configuration 11ENrdquoldquohttpjakartaapacheorgstrutsdtdsstruts-config_1_1dtdrdquogt

ltstruts-configgtltform-beansgtltform-bean name=rdquoempFormrdquo type=rdquocomfficexamplestrutsEmployeeFormrdquo gt ltform-beansgtltaction-mappingsgtltaction path=rdquovalidateEmployeerdquo

type=rdquocomfficexamplestrutsValidateEmployeeActionrdquo name=rdquoempFormrdquo scope=rdquorequestrdquo input=rdquoInputContentjsprdquogt

ltforward name=rdquosuccessrdquo path=rdquoOutputContentjsprdquo gt ltactiongtltaction-mappingsgtltstruts-configgt

2 Open the webxml file and replace the contents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquoldquohttpjavasuncomdtdweb-app_2_3dtdrdquogtltweb-appgt

80

ltweb-appgt

Note This file is basically an empty file but we still need to provide this becausethe ActionServlet still looks for it somehow If it canrsquot find the file it throws aMalformedURLException exception

3 In the same directory create a file named apptld and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogtltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library 11ENrdquoldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogtlttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtdepartmentListltnamegtlttagclassgtcomfficexamplestrutsDepartmentTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaggt

ltnamegtskillsListltnamegtlttagclassgtcomfficexamplestrutsSkillsTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaglibgt

4 In VAJ create a project named STRUTS EXAMPLE Create a file namedApplicationResourcesproperties save it in a temporary folder and paste thecodes below in it Add it to the project that you just created (To do this click on theResources tab then right-click on the STRUTS EXAMPLE project and selectAddResource then look for the ApplicationResourceproperties file you just createdand click OK)

errormissingname=ltligtltfont colors ldquoredrdquogtPlease Enter the first nameltfontgtltligterrormissingdepartment=ltligtltfont colors ldquoredrdquogtPlease pick a departmentnameltfontgtltligterrormissingskills=ltligtltfont colors ldquoredrdquogtPlease select the relevant skillsltfontgtltligtpromptemployeename=ltbgtFirst Name ltbgtpromptemployeedepartment=ltbgtDepartment ltbgtpromptemployeeskills=ltbgtSkills ltbgt

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

81

5 Open the craftwebapp file located in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft and replace the contents with the followingcode

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegtltservletgt

ltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegtltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgtltinit-parametergt ltnamegtapplicationltnamegt

ltvaluegtApplicationResourcesltvaluegt ltinit-parametergt ltinit-parametergt

ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdebugltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdetailltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtvalidateltnamegt ltvaluegttrueltvaluegt

ltinit-parametergtltservletgt

ltservletgtltnamegtinvokerltnamegt

82

ltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegtltvaluegtindexhtmlltvaluegt

ltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

6 In VAJ create a project named STRUTS EXAMPLE and in it create a packagenamed comfficexamplestruts then create a class named EmployeeForm andpaste the following code in

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

83

Insert the typersquos description hereCreation date (1802 10946 PM)author Administrator import orgapachestrutsactionActionFormimport orgapachestrutsvalidatorValidatorForm

public class EmployeeForm extends ActionForm

private String name = ldquordquoprivate String department = ldquordquoprivate String[] skills

EmployeeForm constructor comment public EmployeeForm()

super()

public String getDepartment() return department public String getName() return name public String[] getSkills() return skills public void setDepartment(String department) thisdepartment = department public void setName(String name) thisname = name public void setSkills(String[] skills) thisskills = skills

7 In the same package create a class named DepartmentTag and paste the followingcode

84

Insert the typersquos description hereCreation date (1802 11513 PM)author Administrator

import javautilListimport javautilArrayListimport javaxservletjsptagextTagSupport public class DepartmentTag extends TagSupport

DepartmentTag constructor comment public DepartmentTag()

super()

public int doStartTag() List department = new ArrayList()departmentadd(ldquordquo)departmentadd(ldquoClient Serverrdquo)departmentadd(ldquoLegacyrdquo)departmentadd(ldquoEmerging Techrdquo)departmentadd(ldquoTech Supportrdquo)

pageContextsetAttribute(ldquodepartmentListrdquodepartment)return SKIP_BODY

8 Create a class named SkillsTag and paste the following code

Insert the typersquos description hereCreation date (1802 11910 PM)author Administrator import javautilimport javaxservletjsptagextTagSupport

public class SkillsTag extends TagSupport

SkillsTag constructor comment

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

85

public SkillsTag()

super()public int doStartTag()

List skills = new ArrayList()

skillsadd(ldquoEJBrdquo)skillsadd(ldquoJava Mailrdquo)skillsadd(ldquoJSPrdquo)skillsadd(ldquoHTMLrdquo)skillsadd(ldquoCOBOLrdquo)skillsadd(ldquoCICSrdquo)skillsadd(ldquoCrdquo)

pageContextsetAttribute(ldquoskillsListrdquoskills)return SKIP_BODY

9 Create a class named ValidateEmployeeAction and paste the following code

Insert the typersquos description hereCreation date (1802 125818 PM)author Administrator

import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

86

public class ValidateEmployeeAction extends orgapachestrutsactionAction

ValidateEmployeeAction constructor comment public ValidateEmployeeAction()

super()

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException ActionErrors errors = new ActionErrors()EmployeeForm empForm = (EmployeeForm) form

String name = empFormgetName()if(nametrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingnamerdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String department = empFormgetDepartment()if(departmenttrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingdepartmentrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String[] skills = empFormgetSkills()if(skills == null)

ActionError error = new ActionError(ldquoerrormissingskillsrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

if(errorssize() gt 0)

saveErrors(requesterrors)return new ActionForward(mappinggetInput())

return mappingfindForward(ldquosuccessrdquo)

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

87

10 In eappsprogram filesibmVisualAge for Javaideproject resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft create a file namedInputContentjsp and paste the following 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-INFapptld prefix=app gtlthtmlgt

ltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgtlthtmltext property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogtlttdgtlttdgtlthtmlselect property=rdquodepartmentrdquogtlthtmloptions name=rdquodepartmentListrdquogtlthtmlselectgtlttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogtltbeanmessage key=rdquopromptemployeeskillsrdquogtlttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoskillsListrdquogtlthtmlmultibox property=rdquoskillsrdquogtlt= currentSkill gtlthtmlmultiboxgtlt= currentSkill gt

88

ltbr gtltlogiciterategtlttdgtlttrgtlttrgtlttd colspan=rdquo2rdquo align=rdquocenterrdquogtlthtmlsubmit value=rdquoValidaterdquogtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

11 In the same folder create a file named OutputContentjsp and paste the followingcode

lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gtlttaglib uri=WEB-INFapptld prefix=app gt

lthtmlgtltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgt

ltbeanwrite name=rdquoempFormrdquo property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogt

lttdgt

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

89

lttdgt ltbeanwrite name=rdquoempFormrdquo property=rdquodepartmentrdquogt

lttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogt

ltbeanmessage key=rdquopromptemployeeskillsrdquogt

lttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoempFormrdquo property=rdquoskillsrdquogt

lt= currentSkill gtltbrgt

ltlogiciterategtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

12 Just to make sure that you have the craft application correctly configure make surethat the file defaultservlet_engine located in eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere Test Environmentpropertiescontains the following entry

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

13 In the end the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstrutsmdashconfigxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtld

90

struts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd|_ classes

Deploying and running the sample application1 Bring up the WebSphere Test Environment then click on Edit Class Path

click Select All enter the following text in the extra classpath area

EAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INFclassesEAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INF

click OK

2 Start the servlet engine

3 Once the servlet engine is started

bring up a browser enter the following URL httplocalhost8080craftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

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

91

Enter stuff in it and press Validate and

92

Lesson 14 - Installing Struts 11b in ORIONThis lesson walks you through the installation of Struts 11b in the Orion webserver Aswith the WebSphere installation you need to go through Lesson 1 to prepare yourenvironment Installation of the sample application relies heavily on the instructions inLesson 12 so it is assumed that you have already gone through that lesson Otherwisefollow the instructions for Installing the sample application in Lesson 12 to create thenecessary components

Installation and configuration1 Downloadinstall the following

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract the Xercesjar file and save it in EORIONservletscraftWEB-INFlib

Xalan from httpxmlapacheorgxalan-jindexhtml the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar save them in EORIONservletscraftWEB-

INFlib

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip extract Strutsjar and save it in EORIONservletscraftWEB-INFlib

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and save the commons-jar files toEORIONservletscraftWEB-INFlib

OR

Open the binary distribution of STRUTS and extract all commons jar files and save themin

eORIONservletscraftWEB-INFlib

2 Open jakarta-struts-11-b1zip and extract the following files toeORIONservletscraftWEB-INF

struts-tld ndash dtd ndash xml

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

93

note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 Copy the file struts-configxml from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF toeORIONservletscraftWEB-INF

2 Open the webxml file in eORIONservletscraftWEB-INF and replace thecontents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquo

ldquohttpjavasuncomj2eedtdsweb-app_2_3dtdrdquogt

ltweb-appgtltservletgt

ltservlet-namegtactionltservlet-namegtltservlet-classgtorgapachestrutsactionActionServletltservlet-classgtltinit-paramgt

ltparam-namegtapplicationltparam-namegtltparam-valuegtApplicationResourcesltparam-valuegt

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgtltservlet-mappinggt

ltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggtlttaglibgtlttaglib-urigtbeanlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-beantldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigthtmllttaglib-urigt

94

lttaglib-locationgtWEB-INFstruts-htmltldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtformlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-formtldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtlogiclttaglib-urigt

lttaglib-locationgtWEB-INFstruts-logictldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigttemplatelttaglib-urigtlttaglib-locationgtWEB-INFstruts-templatetldlttaglib-locationgtlttaglibgtlttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgt

lttaglibgtltweb-appgt

3 Copy the file apptld from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraftWEB-INF

4 Copy the file ApplicationResourcesproperties from eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftcomfficfincraftresource toeORIONservletscraftWEB-INFclasses

5 From VAJ export the class named EmployeeForm to

eORIONservletscraftWEB-INFclasses

Note the classes will be exported to the corresponding directory structurecomfficexamplestruts

6 From VAJ export the class named DepartmentTag toeORIONservletscraftWEB-INFclasses

7 From VAJ export the class named SkillsTag to eORIONservletscraftWEB-INFclasses

8 From VAJ export the class named ValidateEmployeeAction toeORIONservletscraftWEB-INFclasses

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

95

9 Copy the file InputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

10 Copy the file OutputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

11 Upon completion the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstruts-configxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtldstruts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd

|_ classesApplicationResourcesproperties|_com

|_ffic|_example

|_strutsValidateEmployeeActionclassDepartmentTagclassSkillsTagclassEmployeeFormclass

|_libstrutsjarXercesjarXalanjarxml-apisjartilesjarcommons-validatorjarcommons-servicesjarcommons-pooljar

96

commons-loggingjarcommons-digesterjarcommons-dbcpjarcommons-collectionsjarcommons-beanutilsjar

Deploying and running the sample application1 Start ORION (eorionjava -jar orionjar)

2 Once the ORION is started

bring up a browser enter the following URL

httplocalhostcraftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

Enter stuff in it and press Validate and the output should look something like the nextscreen

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

97

98

Lesson 15 - Struts ComponentsHere is a more detailed discussion on the commonly used classestaglibs in the Strutsframework To learn Struts I strongly suggest that you read this document a number oftimes revisit the example application andor hack it and most important of all ask lots ofquestions It takes more than just this document to help you understand and work withthe struts framework The last part of this document lists some very useful struts-relatedURLs that can supplement what yoursquove learned so far

Struts ComponentsThe classes described below are part of the Struts distribution package which youdownloaded in Lesson 13 In VAJ these are in the STRUTS project They may also befound in the strutsjar file that came with the binary distribution of struts

ActionServlet (orgapachestrutsactionActionServlet)

This class extends HttpServlet and is the only servlet in the Struts framework

Itrsquos main responsibilities are

receive request from the browser automatically populate any associated javabeans (ActionForms) with data from the

browser determine the class (Action) that will process the request receives notice of completion from the Action class to do either a a server-side or

client-side redirect

To configure the ActionServlet we need to enter information about this servlet in theapplication deployment descriptor just like any other servlets

In webxml (ORION)

ltservletgtltservlet-namegtactionltservlet-namegtltservlet-classgt

orgapachestrutsactionActionServletltservlet-classgt

This line tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-paramgtltparam-namegtapplicationltparam-namegtltparam-valuegt

ApplicationResourcesltparam-valuegt

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

99

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-mappinggtltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggt

In craftwebapp (VAJWebSphere Test Environment)

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgt

This tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-parametergt ltnamegtapplicationltnamegt ltvaluegt

ApplicationResourcesltvaluegt ltinit-parametergt

This tells the ActionServlet where to look for mapping information(ActionActionForm definitions)

ltinit-parametergt ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltservletgt

Yoursquoll notice that we sometimes override some initialization parameters for theActionServlet with our own values For a complete list of initialization parameters youcan go the jakartaapachecomstruts website For our purpose of building a simplestruts-based application these initialization parameters will suffice

100

ActionForm (orgapachestrutsactionActionForm)

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

public class DivisionBean extends orgapachestrutsactionActionForm

place your settersgetters etc here

Enter the form information in the struts-configxml file using ltform-beangt tags

ltform-beansgtltform-bean name=rdquoDivisionFormrdquo type=rdquocomffictrainingDivisionBeanrdquo gt

ltform-beansgt

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

ltaction-mappingsgtltaction path=rdquovalidateDivisionrdquo

type=rdquocomfficexamplestrutsValidateDivisionrdquoname=rdquoDivisionFormrdquoscope=rdquorequestrdquoinput=rdquoInputjsprdquogtltforward name=rdquosuccessrdquo path=rdquoDisplayDivisionjsprdquogt

ltactiongtltaction-mappingsgt

Action (orgapachestrutsactionAction)

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)

250

Complete code (comffictrainingLoginAction)

import orgapachestrutsactionimport orgapachestrutsvalidator

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

public class LoginAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws IOExceptionServletException

ActionErrors errors = new ActionErrors()

try

errors = ((DynaValidatorForm)form)validate(mappingrequest)if (errorsempty())

saveErrors(request errors) return new ActionForward(mappinggetInput())

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

251

5 We then need to define new validation rules for the dynamic form Open the filevalidationxml located in craftWEB-INF and add the following entries within theltformsetgt tags

ltform name=logonFormgtltfield property=userId depends=requiredgt

ltarg0 key=promptloginusergtltfieldgtltfield property=password depends=requiredmaskgt

ltarg0 key=promptloginpasswordgtltvargt

ltvar-namegtmaskltvar-namegtltvar-valuegt^[a-zA-Z]$ltvar-valuegt

ltvargtltfieldgt

ltformgt

The rules are the same as the entry for loginForm except that we donrsquot force the user to enter avalid email address in the userId field This tells us that this rule is what gets read when we validatethe login information in the DynaValidatorForm

Deploying the code (Part 2 ndash DynaValidatorForm 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

Result (Part 2 ndash DynaValidatorForm example)The result should look like the following screens below

The login form

252

Submitting the form without any data will result in the following screen

Entering a userid and an alphanumeric password will result in 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

253

Entering a userid and an alpha password will navigate the user to the welcome page

Since the user was not required to enter a valid email address for the userid we can besure that the new process is whatrsquos working behind the scenes to contain form data usingthe DynaValidatorForm and to perform the validation using struts-validator

254

Lesson 28 ndash Using tokensBasics A highly recommended way of keeping our transactions in synch is the use of tokens Atoken is a random number that gets stored in the users session a copy of which issupposed to be stored in the request If the session and request tokens are missing orare different then the transaction is out of synch To illustrate this if we have a processthat adds a record to a database using a jsp and an action class The user aftersubmitting the form and getting the confirmation that the record was successfully addedmay click on the dreaded BACK button and navigate back to the data entry screen andclick the SUBMIT button again to add the same record As a rule of thumb it is not safeto assume that users will follow instructions all the time ndash most will but there are a fewgremlins out there who will want to play around with the application We want to design asystem that deals with this type of situation The simplest way to address this is to use atoken that gets created when the entry form is displayed for the first time and theninvalidatedreset after the successful completion of the operation If the user tries to goback to the data entry screen the token will no longer be valid since it has already beenreset and therefore we can navigate the user to an error page where he canrsquot hurt himselfor the application

CodingInstead of creating a new process we will use the existing edit function to demonstratethe use of tokens in Struts

The flow of the new edit process will be as follows

Displayjsp will display all Division items Clicking on the ldquoeditrdquo link will invoke DivisionActionrsquos edit() method which will bring up

an edit page containing the selected Division item At this point a token will begenerated

The user makes changes to the division descripition (or not) and submits the formThe DivisionActionrsquos update() method will then be invoked In this method the tokenwill be validated and if valid the update will occur Otherwise the user will be thrownto the login page with the corresponding error message

1 In VAJ make the following changes to the edit() and update() methods of theDivisionAction class and the execute() method of the FindDivisionAction class

Add the following line of code within the try block just before returning an ActionForward

saveToken(request)

This code puts the token in the request which will be written in the output jsp as a hiddenfield inside the lthtmlformgt 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

255

2 Next is to make changes to the update() method of the DivisionAction class tovalidate the token and make the necessary decisions

In the try block change the following lines of code

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

to

if (isTokenValid(request))

resetToken(request)

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

else

ActionError error = new ActionError(errorduplicatesubmit)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

3 Since we created a new key for an error message in the previous step we need tomake an entry in the ApplicationResourcesproperties to assign a value to thiskey Add the following line of code in the ApplicationResourcesproperties file

errorduplicatesubmit=ltbgtltfont color=redgtDuplicate page submission session has beeninvalidate Please log in againltfontgtltbgt

4 There is also a new forward named loginpage in the update() method so add aforward named loginpage for the DivisionAction action-mapping entry in struts-configxml that maps to the login jsp

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

256

ltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

We have completed the coding changes at this point so letrsquos 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 Click on the Display Division link

ResultTo test out the use of the token just follow the screen sequence below

The list of division items will be displayed initially

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

257

Select an item to bring up an edit screen

258

After submitting the edit form the items will be redisplayed

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

259

Clickin on the browserrsquos back button will cause the screen to navigate back to the editpage

Since the token was already reset submitting that same form will trigger an exceptionand the screen will navigate to the login page with the corresponding error message

260

Lesson 29 ndash Implementing security in StrutsBasics

First some definitions

Authentication is the process by which a user submits a set of credentials to theapplication which then checks if the submitted credentials match those that are keptinternally

Authorization is the process of determining if a user authenticated or not is able toaccess a protected resource

J2EE standards provide for container-managed authentication and authorization usingentries in the application deployment descriptor (the deployment descriptor would be thecraftwebapp in VAJ and webxml in ORION) If you are not familiar with and want tolearn about configuring container-managed security form-based authentication inparticular go to this url for an overview ==gthttpwwwonjavacompubaonjava20010806webformhtml The implementation ofcontainer-managed security varies from webserver to webserver and we thereforecannot cover this in our lesson We however will be implementing the authenticationpiece using Policy Director (PD) which uses an LDAP to retrieve user infoauthorizationparameters We will then handle the implementation of the authorization piece withinStruts

Lets look at how our application will interact with PD to authenticate users

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

261

From the diagram above we can retrive the information from the HttpRequestrsquos headerusing the following codes

To retrieve the user name

String user = (String)reqgetHeader(IvUserHeaderKey)

To retrieve the groups to which the user is associated

String groups = reqgetHeader(IvGroupsHeaderKey)

Note that groups is defined as a String instead of a collection This is because theinformation retrieved from the header is a comma-delimited string so we need to providea convenience method to parse this information and place them in a collection

Upon successful authentication we need to save the user information off to a sessionobject so we can access this information anywhere within the application We then needto design a security framework around our application that will provide authorizationservices As mentioned before PD will provide the authentication service for ourapplication

Declarative security

Declarative security provides for setting security parameters outside the applicationcodes usually in an xml file the advantage of which is there is no need to recompile anyof the source codes to effect new security rules

Struts does not (yet) provide for declarative security and for good reason The frameworkneeds to be independent of any type of implementation for authenticationauthorizationfor the purpose of portability While it does not provide declarative security it does haveprovisions which enables developers to quickly develop their own mechanism fordeclarative security The next section will walk you through the steps in creating a simplebut effective security framework in Struts

Coding (Part 1 ndash protecting do classes)In this section we will create an abstract action class wersquoll call it BaseAction that willperform the necessary security checks This way we only have one place to make achange in case we need to enhance the code This class will then be extended by allother action classes

262

Below is a diagram that represents how our example application will look like at the endof this section

1 A ltset-propertygt tag can be used to define arbitrary parameters that will be passedto the action class using the ActionMapping object We will take advantage of thisfeature to declare our own security parameter In the struts-configxml file add thefollowing tag to the action classes that need to be protected

ltset-property property=isSecure value=true gt

Add this tag to the entries for the LoginAction DivisionAction and FindDivisionActionclasses

ltaction path=login type=comffictrainingLoginAction name=logonForm scope=requestinput=Loginjspgt

ltset-property property=isSecure value=falsegtltforward name=success path=welcomepagegt

ltactiongt

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

263

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

ltset-property property=secure value=truegt ltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

ltaction path=findDiv type=comffictrainingFindDivisionAction name=srchFormscope=request input=diveditpagegt

ltset-property property=secure value=truegtltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltexception key=errordivisionnotnumber type=javalangNumberFormatException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=loginpage path=Loginjspgt

ltactiongt

Note The parameter we defined above will cause Struts to invoke the setIsSecure() method ofthe ActionMapping object

2 To make sure that Struts reads the parameter we defined in the previous step weneed to define a variable in subclass of the ActionMapping class with thecorresponding accessorsmutators Create a subclass oforgapachestrutsactionActionMapping named FFICActionMapping in thepackage comffictraining

public class FFICActionMapping extends orgapachestrutsactionActionMapping

Declare a private variable for the parameter

private boolean isSecure = false

Define the settergetter that corresponds with the property attribute in the ltset-propertygt tag

public boolean getIsSecure() return isSecure

public void setIsSecure(boolean secure)

264

thisisSecure = isSecure

Complete code (comffictrainingFFICActionMapping)

Insert the types description here Creation date (6302 24414 PM) author Administrator public class FFICActionMapping extends orgapachestrutsactionActionMapping

private boolean secure = false

Construct a new instance of this class with the desired default form bean scope public FFICActionMapping()

super()

Insert the methods description here Creation date (6302 24740 PM) return boolean public boolean getSecure()

return secure Insert the methods description here Creation date (6302 24717 PM) param secure boolean public void setSecure(boolean secure)

thissecure = secureSystemoutprintln(security indicator set)

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

265

3 Now that weve can set security parameters in our config we need to create anaction class that uses this parameter To centralize the code for this create aabstract class named BaseAction which extends orgapachestrutsactionActionThis class will contain the logic that checks if an action class requires a user to belogged-in If so it then checks if the user is already logged in before it runs theexecuteAction() method of its subclass

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

The execute() method receives the FFICActionMapping object and we cast it here

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

Check if this action class requires the user to be logged-in based on the isSecurevariables value

if (requiresLogin(mapping1))

If log-in is required invoke a method that checks for the presence of the userKeyattribute in the session

if (isUserLoggedIn(request))

Execute the subclasss executeAction() method if user is logged-in

return executeAction(mapping1formrequestresponse)

else

If the user has not been authenticated create an ActionError object with thecorresponding error key and forward the user back to the login page

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

266

else

If no authentication is required that is if the isSecure parameter is not coded in theactionmapping invoke the subclass executeAction() method

return executeAction(mapping1formrequestresponse)

Create an unimplemented executeAction() method which will be implemented bysubclasses of BaseAction

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

This method checks if the user is logged-in to the application

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

This method retrieves the actions isSecure parameter to check if log-in is required

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

Complete code (comffictrainingBaseAction)

package comffictraining

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

267

import orgapachestrutsactionActionimport orgapachestrutsactionActionFormimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservlethttpHttpSessionimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

if (requiresLogin(mapping1))

Systemoutprintln(log-in required)

if (isUserLoggedIn(request))

return executeAction(mapping1formrequestresponse)

else

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

268

else

return executeAction(mapping1formrequestresponse)

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

4 Revise all the action classes - extend BaseAction instead of orgapachestrutsactionAction- change the signature of the execute() method

from

public ActionForward execute(ActionMapping mapping ActionFormform

HttpServletRequest requestHttpServletResponse response)

to

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

269

public ActionForward executeAction(FFICActionMapping mappingActionForm form

HttpServletRequest requestHttpServletResponse response)

So far we have the following action classes to change

FindDivisionAction LoginAction

5 The DispatchAction class which we discussed in previous lessons also needs toextend the BaseAction class to be able to implement the security framework

create a copy of orgapachestrutsactionDispatchAction which extendsBaseAction instead of Action in the package comffictraining

change the signature of comffictrainingDispatchActions execute() method

from

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

to

public ActionForward executeAction(FFICActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

6 Change the DivisionAction class that extendsorgapachestrutsactionDispatchAction to extend the newcomffictrainingDispatchAction

public class DivisionAction extends comffictrainingDispatchAction

7 Revise the LoginAction class to save the user information to a session objectnamed userKey This assumes that the user has been successfully authenticatedby PD and that our code has retrieved the user information from the HttpRequestrsquosheader

requestgetSession()setAttribute(userKey((DynaValidatorForm)form)get(userId))

8 Create a new entry in the ApplicationResourcesproperties file for the followingkeyvalue pair

270

errorusernotauthenticated=ltbgtltfont color=redgtYou have not been properlyauthenticatedplease log inltfontgtltbgt

9 Create the class LogoutAction in the package comffictraining so we caninvalidate the session and later on test the security framework

Create a regular action class

public class LogoutAction extends orgapachestrutsactionAction

In the execute() method just invalidate the session and forward the user to the loginpage

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)

throws Exception ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

Complete code (comffictrainingLogoutAction)

import orgapachestrutsaction

import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponse

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

271

import javaxservletServletException

import javaioIOException

import javasqlConnectionimport javasqlSQLException

import javautilCollection

Insert the types description here Creation date (12202 92827 AM) author Administrator public class LogoutAction extends orgapachestrutsactionAction LogoutAction constructor comment public LogoutAction()

super() Insert the methods description here Creation date (12202 94602 AM) return orgapachestrutsactionActionForward public ActionForward execute(ActionMapping mapping ActionForm form

HttpServletRequest request HttpServletResponse response)throws Exception

ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

272

10 Create an entry for the LogoutAction in struts-configxml

ltaction path=logout type=comffictrainingLogoutAction scope=request input=Loginjspgtltforward name=logoutpage path=logoutpagegt

ltactiongt

11 Create LogoutContentjsp in the craft folder

lttable width=100 height=100gtlttrgt lttd valign=center align=centergt lth2gtYou have been logged off lth2gt lttdgtlttrgtlttablegt

12 Open the file tilesDefinitionxml in craftWEB-INF and create a new definition forthe logout page

lt-- Extended definition for account display --gtltdefinition name=logoutpage extends=welcomepagegt

ltput name=body content=LogoutContentjspgtltdefinitiongt

13 Add a line in the menu-configxml for a link to the logout action class (in bold)

ltMenu name=MainMenu title=MainMenu gtltItem 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 gtltItem name=LogOut title=Log Out location=logoutdo gt

ltMenugt

14 Change the TileTemplatejsp in craft to include code that checks for the presence of theuserKey attribute to correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logic 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

273

Encapsulate the menu with logic tags that check for the presence of the userKey session attribute

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

Complete Code (TileTemplatejsp)

lt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFtilestld prefix=tiles gtlt taglib uri=WEB-INFstruts-logictld prefix=logic gt

ltHTMLgtltHEADgtltTITLEgtFiremans Fund Insurance CRAFTltTITLEgt

ltHEADgt

ltBODYgt ltscript language=JavaScript12 src=scriptscoolmenus3jsgtltscriptgtltscript src=scriptscoolmenu-configjsgtltscriptgt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

lttable width=100 border=0gt lttrgt lttd bgcolor=graygtltdiv align=centergtlth1gtMy Applicationlth1gtltdivgt lttdgt lttrgtlttablegt

lttable width=100 height=75 border=0gt

274

lttrgt lttd width=10 align=right valign=top bgcolor=ABABABgt

lttilesinsert attribute=menu gt

lttdgt lttd width=90 valign=center align=centergt

lttilesinsert name=bodygt lttdgt lttrgtlttablegt

lttable width=100 border=0gt lttrgt lttdgtltdiv align=centergt

ltfont size=-1gtCopyright 2002ltfontgtltdivgt

lttdgt lttrgtlttablegt

15 Change the Menujsp to include code that checks for the presence of the userKey attributeto correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logicgt

Encapsulate the menu with logic tags that check for the presence of the userKey sessionattribute

ltlogicpresent name=userKeygt

ltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

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

275

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

Add the following codes that provides a link to the log-in page Encapsulate this code withlogic tags that make the link appear only if the userKey is not present

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

Complete Code (Menujsp)

lt taglib uri=WEB-INFstruts-htmltld prefix=html gtlt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFstruts-logictld prefix=logicgt

lthtmlgtltheadgtltheadgtltbodygt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt

276

ltmenuuseMenuDisplayergt

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

ltbodygtlthtmlgt

Deploying the code (Part 1 ndash protecting do classes)

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

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

277

Result (Part 1 ndash protecting do classes)The login screen

The welcome page now shows a ldquoLog Outrdquo link which invalidates the session

278

Clicking on the ldquoDisplay Divisionrdquo link displays the division items as before No errors atthis point since the user was successfully authenticated during login

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

279

Clicking on the ldquoLog Outrdquo link will navigate the user to the page below It shows the ldquoLogInrdquo link which navigates the user to the login page when clicked

If instead of logging back in the user types a url(httplocalhost8080craftadminDivdomethod=view) on the address line (or uses abookmark) the application will determine that the user has not been authenticated andwill then be navigated to the login page which displays an error message

280

OK now we can prevent those gremlins from bookmarking our applicationrsquos urls Wehave one more thing to do though there are urls that map directly to our jsp pages and atthis point anyone can type a valid url to a particular jsp and can successfully bring up thepage without authenticating to the system There are two recommended ways ofprotecting the jsps

1 Place all jsps under the WEB-INF folder This folder per J2EE standardcan only be accessed from within an application and is not publiclyaccessible via urls typed in the browser

2 Create a custom tag that checks if the user has been authenticated similarto the code we placed in the BaseAction class and perform a redirect to thelogin page if the user has not properly logged in

For option 1 it works well with J2EE compliant application servers but since we are usingWebSphere 353 there is basically no WEB-INF folder to speak off We created a WEB-INF folder in our craft application but this is just to line up our directory structure withJ2EE standards We will therefore cover option 2 in the next section

Coding (Part 2 ndash protecting jsp pages)Unlike the example that we put together in part 1 of this lesson the custom tag that wewill create in this section unconditionally checks if the user has logged-in already Inshort there will be no logic in this custom tag that is equivalent to the code in therequiresLogin() method of BaseAction The MVC patternrsquos basic premise is that usersneed to interact with a controller at all times and not the view It therefore follows thatusers should not be able to bring up jsprsquos (view) directly without going to an action classfirst

1 As previously mentioned we will create a custom tag that checks if a user has loggedin already In the package comffictraining create a class named CheckLoginTag

Create the class by extending TagSupport

public final class CheckLoginTag extends TagSupport

Create an instance variable containing information for the login page

private String page = loginjsp

The doEndTag() is where we check for the presence of the ldquouserKeyrdquo The logic is similarto the BaseActionrsquos isUserLoggedIn() method

public int doEndTag() throws JspException

Is there a valid user logged on

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

281

boolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered

public int doStartTag() throws JspException

return (SKIP_BODY)

Complete Code

import javaioIOExceptionimport javaxservlethttpHttpSessionimport javaxservletjspJspExceptionimport javaxservletjspJspWriterimport javaxservletjspPageContextimport javaxservletjsptagextTagSupportimport orgapachestrutsactionimport orgapachestrutsutilMessageResourcesimport javaxservlethttpHttpServletRequest

Check for a valid User logged on in the current session If there is no such user forward control to the logon page

282

public final class CheckLoginTag extends TagSupport

The page to which we should forward for the user to log on private String page = loginjsp

Perform our logged-in user check by looking for the existence of a session scope bean under the specified name If this bean is not present control is forwarded to the specified logon page exception JspException if a JSP exception has occurred public int doEndTag() throws JspException

Is there a valid user logged onboolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered exception JspException if a JSP exception has occurred public int doStartTag() throws JspException

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

283

return (SKIP_BODY)

2 Open the file apptld in craftWEB-INF and add an entry for the new tag

lttaggtltnamegtcheckLoginltnamegtlttagclassgtcomffictrainingCheckLoginTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggt

3 Make changes to ALL the jsps that wersquove created so far

Add a directive for the apptld

lt taglib uri=WEB-INFapptld prefix=app gt

Place this line of code at the top of each jsp

ltappcheckLogin gt

Deploying the code (Part 2 ndash protecting jsp pages)

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

Result (Part 2 ndash protecting jsp pages)Log into the application then click on the ldquoLog Outrdquo link to make sure that whateversession you have in your browser has been invalidated

284

The screen below makes sure that you have been logged out

In the same page type in the url for the divisionrsquos search pagehttplocalhost8080craftdivSearchjsp

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

285

The checkLogin tag will check to see if the user has logged in or not Since the sessionhas been invalidated the checkLoginTag will perform a forward to the login page

Note Irsquom still working on getting the tag to write an error message similar to what theBaseAction does when it forwards to the login page if the user has not authenticated yet

  • Lesson 1 - ORION webserver configuration
    • Preparation
    • Installation
    • Configuration
    • Review
      • Lesson 2 - VisualAge for JAVAWebSphere Test Environment configuration
        • Installation
        • Configuration
        • Usage
          • Lesson 3 - Servlet primer
            • Basics
            • Your first servlet
            • Deploying the code
              • Lesson 4 - Database Connectivity
                • Preparation
                • Coding
                • Deploying the code
                  • Lesson 5 - ServletDatabase Connectivity
                    • Preparation
                    • Coding
                    • Deploying the code
                      • Lesson 6 - Servlet Redirection
                        • Basics
                        • Preparation
                        • Coding
                        • Deploying the code
                        • Result
                          • Lesson 7 - JavaBeans
                            • Basics
                            • Coding
                            • Deploying the code
                            • Result
                              • Lesson 8 - Object Scope
                                • Basics
                                • Coding
                                • Deploying the code
                                • Result
                                  • Lesson 9 - Java Server Pages (JSP)
                                    • Basics
                                    • Coding
                                    • Deploying the code
                                    • Result
                                      • Lesson 10 - Custom Tags
                                        • Basics
                                          • Anatomy of a Tag
                                          • Custom Tag components
                                            • Coding
                                            • Deploying the code
                                            • Result
                                              • Lesson 11 - Model-View-Controller Design Pattern
                                                • Basics
                                                  • Lesson 12 - Introduction to the Struts Framework
                                                    • Struts Components
                                                    • ldquoI canrsquot find the MVC pattern anywhererdquo
                                                      • Lesson 13 - Installing Struts 11b in VisualAge for Java 40WebSphere Test Environment 353
                                                        • Installation and configuration
                                                        • Installing the sample application
                                                        • Deploying and running the sample application
                                                        • Result
                                                          • Lesson 14 - Installing Struts 11b in ORION
                                                            • Installation and configuration
                                                            • Installing the sample application
                                                            • Deploying and running the sample application
                                                            • Result
                                                              • Lesson 15 - Struts Components
                                                                • Struts Components
                                                                • Tag Libraries
                                                                • Useful Links
                                                                  • Lesson 16 - Building a simple web application using Struts
                                                                    • Basics
                                                                    • Coding
                                                                    • Deploying the code
                                                                    • Result
                                                                      • Lesson 17 ndash Validating form values
                                                                        • Basics
                                                                        • Installation
                                                                        • Coding
                                                                        • Deploying the code
                                                                        • Results
                                                                          • Lesson 18 ndash Nested Beans
                                                                            • Basics
                                                                            • Installation
                                                                            • Coding
                                                                              • CODING PART 1
                                                                              • CODING PART 2
                                                                              • CODING PART 3
                                                                                  • Lesson 19 ndash Creating reusable screen components
                                                                                    • Basics
                                                                                    • Coding (Part 1)
                                                                                    • Deploying the code (Part 1)
                                                                                    • Results (Part 1)
                                                                                    • Coding (Part 2)
                                                                                    • Deploying the code (Part 2)
                                                                                    • Result (Part 2)
                                                                                    • Coding (Part 3)
                                                                                    • Deploying the code (Part 3)
                                                                                    • Result (Part 3)
                                                                                      • Lesson 20 ndash Creating reusable menu components
                                                                                        • Basics
                                                                                        • Installation
                                                                                          • Option 1
                                                                                          • Option 2
                                                                                            • Coding
                                                                                            • Deploying the code
                                                                                            • Result
                                                                                              • Lesson 21 ndash Connection Pooling
                                                                                                • Basics
                                                                                                • Coding
                                                                                                • Deploying the code
                                                                                                • Result
                                                                                                  • Lesson 22 ndash Creating a singleton to maintain the
                                                                                                    • Basics
                                                                                                    • Coding
                                                                                                    • Deploying the code
                                                                                                    • Result
                                                                                                      • Lesson 23 ndash Data Access Objects
                                                                                                        • Basics
                                                                                                        • Coding
                                                                                                        • Deploying the code
                                                                                                        • Result
                                                                                                          • Lesson 24 ndash Business Objects
                                                                                                            • Coding
                                                                                                            • Deploying the code
                                                                                                            • Result
                                                                                                              • Lesson 25 ndash Action subclasses
                                                                                                                • Coding
                                                                                                                • Deploying the code
                                                                                                                • Result
                                                                                                                  • Lesson 26 ndash Exception handling
                                                                                                                    • Basics
                                                                                                                      • Using nested ifrsquos
                                                                                                                      • Using trycatch blocks
                                                                                                                        • Coding (Part 1 ndash programmatic exception handlin
                                                                                                                        • Deploying the code (Part 1 ndash programmatic excep
                                                                                                                        • Result (Part 1 ndash programmatic exception handlin
                                                                                                                        • Coding (Part 2 ndash using declarative exception
                                                                                                                        • Deploying the code (Part 2 ndash using declarative
                                                                                                                        • Result (Part 2 ndash using declarative exception
                                                                                                                          • Lesson 27 ndash Creating dynamic forms
                                                                                                                            • Basics
                                                                                                                            • Coding (Part 1 ndash DynaActionForm example)
                                                                                                                            • Deploying the code (Part 1 ndash DynaActionForm exa
                                                                                                                            • Result (Part 1 ndash DynaActionForm example)
                                                                                                                            • Coding (Part 2 ndash DynaValidatorForm example)
                                                                                                                            • Deploying the code (Part 2 ndash DynaValidatorForm
                                                                                                                            • Result (Part 2 ndash DynaValidatorForm example)
                                                                                                                              • Lesson 28 ndash Using tokens
                                                                                                                                • Basics
                                                                                                                                • Coding
                                                                                                                                • Deploying the code
                                                                                                                                • Result
                                                                                                                                  • Lesson 29 ndash Implementing security in Struts
                                                                                                                                    • Basics
                                                                                                                                    • Coding (Part 1 ndash protecting do classes)
                                                                                                                                    • Deploying the code (Part 1 ndash protecting do cl
                                                                                                                                    • Result (Part 1 ndash protecting do classes)
                                                                                                                                    • Coding (Part 2 ndash protecting jsp pages)
                                                                                                                                    • Deploying the code (Part 2 ndash protecting jsp pag
                                                                                                                                    • Result (Part 2 ndash protecting jsp pages)

4

Result 225

Lesson 26 ndash Exception handling 229Basics 229Coding (Part 1 ndash programmatic exception handling) 231Deploying the code (Part 1 ndash programmatic exception handling) 234Result (Part 1 ndash programmatic exception handling) 235Coding (Part 2 ndash using declarative exception) 238Deploying the code (Part 2 ndash using declarative exception) 242Result (Part 2 ndash using declarative exception) 242

Lesson 27 ndash Creating dynamic forms 243Basics 243Coding (Part 1 ndash DynaActionForm example) 243Deploying the code (Part 1 ndash DynaActionForm example) 246Result (Part 1 ndash DynaActionForm example) 246Coding (Part 2 ndash DynaValidatorForm example) 249Deploying the code (Part 2 ndash DynaValidatorForm example) 251Result (Part 2 ndash DynaValidatorForm example) 251

Lesson 28 ndash Using tokens 254Basics 254Coding 254Deploying the code 256Result 256

Lesson 29 ndash Implementing security in Struts 260Basics 260Coding (Part 1 ndash protecting do classes) 261Deploying the code (Part 1 ndash protecting do classes) 276Result (Part 1 ndash protecting do classes) 277Coding (Part 2 ndash protecting jsp pages) 280Deploying the code (Part 2 ndash protecting jsp pages) 283Result (Part 2 ndash protecting jsp pages) 283

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

5

Lesson 1 - ORION webserver configurationThis document lists the steps to install the ORION webserver on your workstation (andrun it of course) I picked ORION since Irsquom more familiar with it than Tomcat or Resinetc The entire thing should take about an hour to accomplish I can either walk youthrough the installation or you can just follow these steps yourself and if I didnrsquot missanything have it running in no time Once yoursquore familiar with it I can then walk youthrough the configuration of WebSphere Test Environment in VAJava and we can talkabout the differences between WTE and the rest of the J2EE webappservers

PreparationThe following steps will install the java toolkit in your workstation Yoursquoll need this tocompile andor run stand-alone java programs outside of VAJava

1 Download the java sdk from httpjavasuncomj2se13downloadhtml (selectWindows (all languages) and click the download link under the SDK column)

2 Accept the license and proceed with the download (place it in your favorite folder)3 Run the downloaded executable file j2sdk-1_3_1_03-winexe and unzip it in E (it

should unzip the contents under ejdk131_03)4 Go to your desktop and right-click on My Computer and bring up the properties5 Click on the Environment tab6 Enter the following

Variable JAVA_HOMEValue ejdk131_03

7 Click on OK

Installation1 Download ORION from httpwwworionservercom

on the left-side nav of the screen click on Stable binaries under the Downloadsection

save the file to your favorite local directory

2 Open the downloaded file orion152zip and extract the contents to eorion (thisfolder will be automatically created when you check the ldquoUse foldersrdquo option inWinZip)

3 This is from the orion docscopy toolsjar from ejdk131_03lib into eorion tomake jsprsquos work

6

ConfigurationCreate a J2EE compliant directory structure To do this follow the steps

1 Create the following directory Eservletscraft This will be your applicationrsquos rootdirectory

2 Under the craft folder create the following directory structure

craft|___images|___WEB-INF

|___classes|___libFolder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

3 Create a file named webxml and save it in eservletscraftWEB-INF then pastethe following code

ltxml version=10gtltDOCTYPE web-app PUBLIC -Sun Microsystems IncDTD Web Application22EN httpjavasuncomdtdweb-app_2_2dtdgt

ltweb-appgt

ltweb-appgt

This file contains the applicationrsquos configuration information Right now itrsquos empty but thewebserver still expects to find this file or else it wonrsquot startup the application

4 To let ORION know about your new application (the one you just created above) youneed to enter some stuff in the ORION xml files To do this

go to EORIONCONFIG open applicationxml using a text editor enter the following information (in bold) right after the tag ltweb-module

id=rdquodefaultWebApprdquo path=rdquodefault-web-apprdquo gt

lt-- --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

7

ltweb-module id=rdquoCRAFTrdquo path=rdquoEservletscraftrdquo gtlt-- --gtltpersistence path=rdquopersistencerdquo gt

save and exit the file open default-web-sitexml again using a text editor enter the following information (in bold)

lt-- The default web-app for this site bound to the root --gtltdefault-web-app application=rdquodefaultrdquo name=rdquodefaultWebApprdquo gt

lt-- --gtlt-- get name from applicationxml ltweb-module id=rdquothis will be the namerdquopath=rdquocrdquogt --gtltweb-app application=rdquodefaultrdquo name=rdquoCRAFTrdquo root=rdquocraftrdquo gt

lt-- --gt

saveexit the file

5 Go to the command prompt and go to eorion

6 Start the server by typing java -jar orionjar on the command line

7 If everything was setup properly you should see the message Orion152 initialized

8 Create an html file named pagehtml and save it in Eservletscraft then pastethe following code

lthtmlgtltheadgt ltheadgtltbodygtltdiv align=centergtlth1gtHELLO WORLDlth1gtltdivgtltbodygtlthtmlgt

9 To test your webserver

bring up a browser (IE or NS) type in httplocalhostcraftpagehtml You should see proverbial HELLO

WORLD on your browser

8

(Hint While Windows itself is not case-sensitive unlike AIX the URL should thatyou type in the browserrsquos address line should match the entry in the xml file)

10 Congratulations yoursquore a survivor

ReviewThe following information is worth rememberingDIRECTORY STRUCTURE

craft|___images|___WEB-INF

|___classes|___lib

Folder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

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

9

Lesson 2 - VisualAge for JAVAWebSphere TestEnvironment configurationThis is a minimalist instruction on how to configure your WebSphere Test Environment(WTE) in VAJava to start serving web applications It walks you through the steps increating a CRAFT application and testing the setup to make sure that is runs It shouldtake an hour (or more) to complete this exercise

InstallationInstall VAJava 40 (easy to say huh) You should already have it in your workstationCheck that the WebSphere Test environment is installed in VAJ By selectingWorkspaceToolsWebSphere Test Environment VAJ should tell you if itrsquos there or not If not

Select FileQuick StartSelect FeaturesAdd FeatureSelect WebSphere Test Environment 353 from the list and click OK

Configuration1 Create the following directory structure under eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_host (whew)

craft|_images|_WEB-INF

|_classes

Folder Descriptions

craft - root directorycontains html and jsp filesimages - contains image filesWEB-INF - is not automatically recognized by WebSphere but wersquoll create this so wecan create a pseudo-J2EE directory structureclasses - again not automatically recognized by WebSphere wersquoll create this for thesame reason as the previous folder

2 Create a file craftwebapp and put the following text in the file

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegt

10

ltservletgtltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtinvokerltnamegtltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegt

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

11

ltvaluegtindexhtmlltvaluegtltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

3 To let WTE know about your new application go to the directory eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmentproperties and open the file defaultservlet_engine using a text editorAdd the following text

Look for this tag ltwebsphere-servlet-host name=rdquodefault_hostrdquogt and paste the followingtext right after it

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

UsageThis section will walk you through how to test if your WTE configuration is correctly setup1 Create a file named indexhtml and save it in eappsprogram

filesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft then paste the following code

ltHTMLgtltHEADgtltMETA NAME=GENERATOR Content=NetObjects ScriptBuilder 30gtltTITLEgtWebSphere Test Environment Index PageltTITLEgtltHEADgtltBODYgtlth1gtThis is the index page for the WebSphere Test Environmentlth1gtltBODYgtltHTMLgt

2 Bring up VAJava

3 Select WorkspaceToolsWebSphere Test Environment

4 Click on Start Servlet Engine

12

5 When the message at the lower left says ldquoServlet engine is startedrdquo bring up abrowser

6 Type in this URL httplocalhost8080craft

If the installation is successful yoursquoll get the following message on your browser This is the index page for the WebSphere Test Environmentif not wersquoll take a look at your problem

7 Thatrsquos itnow on to greater 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

13

Lesson 3 - Servlet primerHerersquos the next installment on the web-application development crash-course You willcreate your first servlet which will hopefully give you a basic understanding of whatservlets are and how they work I gave examples on how to deploy the code both in VAJWTE and in Orion so you can continuously compare the two web environments This willgo on for the next few lessons and then when we get to Struts wersquoll just retain theWebSphere Test Environment which is where we should be developing our codes

BasicsServlet

body of java code that extends a java-enabled serverrsquos functionality listens to requests and usually sends back a response to the client Can also pass

processing on to other servlets does not have a main() method so it cannot run outside of the servlet container to create a servlet we generally extend the class HttpServlet which is a subclass of

GenericServlet HttpServlet makes use of the HTTP protocol

Servlet life-cycle

An HttpServlet contains the following methods

init() doGet()doPost() destroy()

When a servlet is first invoked the servlet container calls the servletrsquos init() method thenit calls either the doGet() or doPost() method

For subsequent requests only the doGet() or doPost() method is called A separatethread is created for every doGet()doPost() invocation so different requests will not runinto each other We place the majority of our code in either of these methods

When the servlet container is shutdown it calls the servletrsquos destroy() method

RequestResponse paradigm

Uses HTTP which is a stateless protocol

In itrsquos simplest form

client sends a request and servlet receives request (and response) object which mayhave objects attached to it (parameters or attributes RemoteUser etc)

14

servlet processes the request (access a db contruct an html response forward toanother servlet etc)

client receives some form of response from the servlet and renders the output to the browser

Your first servletIn VAJ

1 Create a project named TRAINING2 Create a package named comffictraining3 Create a class named HelloWorldServlet4 Add these codes to HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

Code Walkthrough

1 To make HelloWorldServlet a servlet it needs to extend HttpServlet

public class HelloWorldServlet extends HttpServlet

2 We will then need to implement one of the following methods

doGet()doPost()

In this example we implemented the doGet() method

public void doGet(HttpServletRequest 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

15

3 Inside the doGet()

we set the content type for the response to texthtml since we intend to send back anhtml response

responsesetContentType(ldquotexthtmlrdquo)

4 We then retrieve the PrintWriter from the response so we can start writing our outputto it

PrintWriter out = responsegetWriter()

5 Lastly we start writing our output

outprintln(ldquolth1gtHello worldlth1gtrdquo)

After executing the last line of code the servlet returns control back to the web containerwhich sends the response back to the client Since we added stuff in the response theclientrsquos browser will attempt to render it

Deploying the codeVAJava (WebSphere Test Environment)

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (this can be the last entry just beforethe

ltwebappgt tag)

ltservletgtltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

Orion

16

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgtltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in ldquoHello Worldrdquo being displayed on your browser

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

17

Lesson 4 - Database ConnectivityBefore we move on to other web components we need to briefly go through the topic onconnecting to a database and retrieving information from the tables This will make thenext few topics a lot more interesting since you will be displaying data on the browser thatwere retrieved straight off of the db instead of flooding your servlet with ldquoset-this set-thatvaluerdquo lines of codes

After going through this exercise it will become more obvious that this is not the real-world way of creating and maintaining connections to a database Creating a connectionfor each sql to be executed is a pretty expensive operation In later exercises we willexplore how to create a pool of connections using DataSource and the methods withwhich this datasource is maintained and accessed (the FFIC way of course)This section discusses the java code required to connect to a database and execute sqlto retrieve data

Preparation1 You should have the IOU database information entered in your UDB-client with the

following details

DB Alias = IOUODBC entry = IOU (not really needed in this exercise but check it anyway)

2 We will be using the DB2 driver to create the connection to our database If youhavenrsquot done so import the db2javazip file into your VAJ ide

create a DB2 DRIVER project import db2javazip from EAPPSSQLLIBjava into your newly created project

using the following option ldquoimport as a Jar filerdquo

3 For ORION copy the file db2javazip to EservletsORIONcraftWEB-INFliband rename it to db2javajar

CodingIn your TRAINING project create a class JDBCSample in the comffictraining packageand paste the following code in it

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcapp

18

import javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(ldquoDivision ldquo + ldquoCoderdquo + ldquo ldquo + ldquoDescriptionrdquo) while (rsnext())

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

19

String s = rsgetString(1)String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

CODE WALKTHROUGH

1 We need to import the following packages so the program can load the necessaryjdbc classesdrivers

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

2 We define variables for the sql to execute and the useridpassword needed to accessthe database Obviously you must change the userpassword if you have a differentone We also specify here the driver that we will use to create a connection to thedatabase (DB2 in this case)

String query = ldquoSELECT FROM IOUDIVISIONrdquoConnection conn = nullStatement stmt = nullString user = ldquoiccw0t00rdquoString password = ldquoiccw0t00rdquoString driver = ldquoCOMibmdb2jdbcappDB2Driverrdquo

3 This trycatch block attempts to load the database driver and create a connection

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)

20

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)

4 When a connection is successfully created the next trycatch block creates aStatement from the connection and executes the sql that we defined earlier

try 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 )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

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 JDBCSample class and select Run

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

21

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 JDBCSample 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

The output should look similar to the following

loading driverconnectingtojdbcdb2IOUconnectedDivision Code Description1 CID Involuntary 2 CID Voluntary 3 PID 4 CID Specialty 10 National Accounts 11 Jefferson Insurance 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

22

END

NEXTLetrsquos try what we just learned using our servlet example

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

23

Lesson 5 - ServletDatabase Connectivity From the last two lessons you learned to a) construct a simple servlet and b) create ajava program that retrieves data from a database Now we will combine the two andcome up with a servlet that accesses the database and displays the result (ResultSet) ona browser

PreparationRemember your two previous programs If not here are the source codes

HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServletpublic void doGet(HttpServletRequest request

HttpServletResponse response)throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

JDBCSample

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

24

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try 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 )

stmtclose()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

25

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

Before you proceed briefly review how each of the programs work so it will be mucheasier to understand the codes belowthatrsquos all

CodingWith a little tweak (additional codes) the code below shows a combined version of thetwo programs we previously created You can cut and paste it in your HelloWorldServletin VAJ

The blue portion is the HelloWorldServlet while the red portion shows theJDBCSample

You will also notice that there are codes in green These lines of codes were added toaccomodate the codes for JDBCSample and to properly display the output to thebrowser

import javaioimport javaxservletimport javaxservlethttp

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

public class HelloWorldServlet extends HttpServletString query = SELECT FROM IOUDIVISIONConnection conn = nullStatement stmt = nullString user = iccw0t00String password = iccw0t00String driver = COMibmdb2jdbcappDB2Driver

HelloWorldServlet constructor comment

26

public HelloWorldServlet()

super()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() outprintln(lth1gtHello worldlth1gt)

try

stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(Division Code + + Description) outprintln(lth2gtDivisionlth2gt) outprintln(lth3gtCode Descriptionlth3gt)

while (rsnext()) String s = rsgetString(1)

String ln = rsgetString(2) Systemoutprintln(s + + ln )

outprintln(lth3gt + s +ampnbspampnbspampnbspampnbspampnbspampnbspampnbsp + ln + lth3gt)

stmtclose()

conclose()

catch(SQLException ex) Systemerrprintln(SQLException + exgetMessage())

Insert the methods description here Creation date (42402 22142 PM) public void init()

try Systemoutprintln(loading driver) ClassforName(driver) String url = jdbcdb2IOU Systemoutprintln(connectingto + url) conn = DriverManagergetConnection(urluserpassword) Systemoutprintln(connected)

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

27

try catch(ClassNotFoundException ex) Systemoutprintln(Couldnt load jdbc driver) Systemoutprintln(ex) catch(SQLException ex) Systemoutprintln(Database Problem) Systemoutprintln(ex) catch(Exception ex) Systemoutprintln(Some other problem) Systemoutprintln(ex)

CODE WALKTHROUGH

Irsquove pretty much gone through the codes line by line in the previous lessons What needs to be mentioned here is that a method called init() was added and the codesthat load the DB2 driver and create the connection were added here

Insert the methodrsquos description hereCreation date (42402 22142 PM) public void init()

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

28

Systemoutprintln(ex)

When a servlet starts up the first thing it looks for is an init() method and it executes thismethod once within itrsquos lifetime It is good practice to place initialization stuff in thismethod especially when we only need to run these once A good example is creating aconnection to the database and this is just what we did with this exampleNote As with the init() method a servlet also has a destroy() method which is calledwhen it shuts down

Deploying the codeDeploying the code to VAJ and ORION is the same as in the servlet lesson I listed ithere again just in case you donrsquot have that lesson anymore

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (can be the last entry just before the ltwebappgt tag)

ltservletgt

ltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

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

29

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in the following output on your browser

30

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

31

Lesson 6 - Servlet RedirectionThis lesson briefly covers one of the more important features of servlets which isforwarding or redirecting In simple terms redirection is passing control to another entitywhich can be a servlet html or jsp at the same logical level It works pretty much like anxctl in CICS with some differences There are two types of redirection client-side andserver-side and these are described in the following section

BasicsClient-side redirection

The redirection happens at the client-side and the URL on the browserrsquos address linechanges to the URL that was sent to it User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and sends a message

(redirect) to the browser containing a URL which the browser will load The browser receives the redirect from the servlet and loads the URL that was sent

to it

Note The URL in the redirect can be another servlet html or a jsp file

To illustrate this process

BROWSER==gtservlet==gtBROWSER==gtresult(jsphtmlservlet)

Client-side redirection is useful when after a servlet processes you want to navigate theuser to another page where even if he reloads that result page will not cause the servletto re-execute In other words the user is navigated to a safe place where he canrsquot hurthimself or the application

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoresponsesendRedirect(url)

if you want to retrieve the original URL to redirect the servlet to itself do this

String url = requestgetRequestURI()responsesendRedirect(url)

Note the getRequestURI() method leaves out the parameters if any that wereincluded in the original URL You can use the requestgetParameter() to retrieve theparameters and attach them to the url

32

Server-side redirection

The redirection happens only at the server-side and the browser does not know anythingabout it The URL on the browserrsquos address line does not change

User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and forwards itrsquos output to

another servlet jsp or html The receiving sevlet jsp or html renders the output to the browser

To illustrate this process

BROWSER==gtservlet==gtresult(jsphtmlservlet)

Server-side redirection is used to combine several operations to make them appear asone without involving the clientrsquos browser This cuts down traffic between the server andthe browser The browser will receive the result only after the last of the processes hasreleased the output to the web container

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

PreparationThis exercise involves server-side redirection The idea is to have one servlet receive therequest from the browser and perform a redirect to another servlet which will retrieve datafrom a db and construct the html output to be rendered on the browserWe will need the HelloWorldServlet servlet for this exercise which will act as the receivingservlet All we need to contruct is the servlet that will forward the processing toHelloWorldServlet

CodingIn VAJ create a new class called ControllerServlet in the package comffictraining andpaste the following code to it

import javaioimport javaxservletimport javaxservlethttp

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

33

public class ControllerServlet extends HttpServletpublic void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionString url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

1 We define ControllerServlet as a servlet by extending HttpServlet

public class ControllerServlet extends HttpServlet

2 These lines construct the URL of the receiving servlet and performs the redirection

String url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtControllerltnamegtltdescriptiongtDB access servletltdescriptiongtltcodegtcomffictrainingControllerServletltcodegtltautostartgttrueltautostartgt

ltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

34

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtControllerltservlet-namegtltservlet-classgt

comffictrainingControllerServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

35

You can verify that the servlet did a server-side redirect if the URL on the browserrsquosaddress line did not change It should still show

httplocalhost8080craftservletController for WTE

or

httplocalhostcraftservletController for ORION

WATCH OUT NEXT FORJAVA BEANS

36

Lesson 7 - JavaBeansUp to this point we have been dealing mostly with webserver configuration andprocedural java codes In this lesson we will start to incorporate object orientation in ourexamples using javabeans

BasicsIn our example programs we created data in our servlet by retrieving information fromthe database and by assigning values to variables There will be times when we want topass this data around and manipulate them before we send them to the browser fordisplay A convenient way of doing this is to encapsulate all these related informationhide them in an object and provide methods to access each value To accomplish thiswe create a java class called javabean or bean that contains only private variables andsettergetter methods for each of these variables For instance we can create a bean called divisionBean and store each row that weretrieve from the database to a divisionBean instance We can then put all these beansinside a collection object that we can pass around and eventually render to the browserSounds confusing Letrsquos do an example then

Coding1 In VAJ create a class called DivisionBean in comffictraining package and paste the

following in it

public class DivisionBean private String divNoprivate String divDesc

public String getDivDesc()return divDescpublic String getdivNo()return divNopublic void setDivDesc(String divDesc)thisdivDesc = divDescpublic void setDivNo(String divNo) thisdivNo = divNo

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

37

2 Open your HelloWorldServlet and make the following changes

Add the following code right after the class declaration

ArrayList divList = new ArrayList()

In the doGet() method

delete the following lines or better yet just comment them out (ie put a beforeeach line)

String s = rsgetString(1)

String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )outprintln(ldquolth3gtrdquo + s + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + ln + ldquolth3gtrdquo)

add the following lines within the while loop

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

after the while loop add the following lines of code

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

Code Walkthrough

DivisionBean

1 We defined the two variables divNo and divDesc as private to prevent them frombeing accessed directly (ie divisionBeandivNo)

private String divNoprivate String divDesc

38

2 We then define getters and setters for the two variables

public String getDivDesc()

return divDesc

public String getdivNo()

return divNo

public void setDivDesc(String divDesc)

thisdivDesc = divDesc

public void setDivNo(String divNo)

thisdivNo = divNo

HelloWorldServlet

1 We defined an Arraylist (called divList) which part of the java collections to containthe instances of the beans that we create

ArrayList divList = new ArrayList()

2 In the while loop we instantiate a new divisionBean and set itrsquos variables to thevalues that we retrieve from the db The we add that instance to divList

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

3 After wersquove gone through the entire resultset we loop through divList and create anhtml output for each instance of the bean in the ArrayList The code provided here ispretty much boiler plate code

retrieve an interator from divList (all collections have an interator)

Iterator iterator = divListiterator()

the interator has methods that loop through the ArrayList object (hasNext()) andto retrieve each item (next())

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

39

while (iteratorhasNext())

when an item is retrieved it has to be cast back to the original object In thiscase we cast the item back to DivisionBean

DivisionBean divbean = (DivisionBean) iteratornext() outprintln(ldquolth3gtrdquo +divbeangetDivNo() + ampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +divbeangetDivDesc() + ldquolth3gtrdquo)

Enhancement idea

You may ask ldquoWhy put more code that does the same thing as the originalrdquo

The answer is that creating beans and storing them in collections (or even if you justhave a single bean) enables you to attach this object to for example the request object(ie requestsetAttribute(ldquodivisionListrdquodivList)) and perform a forward to another servletthat contains code (such as the while loop with the iterator) that performs the creation ofthe output to the browser In this case the components can be further divided into thefollowing

ControllerServlet - receives the request from the browser and forwards it toHelloWorldServlet

HelloWorldServlet - retrieves data from the db stores the results inbeanscollection attaches the collection to the request object then performs aserver-side redirect to another servletjsp which we can call DisplayServletDisplayServlet - retrieves the collection from the request object and builds thehtml output while iterating through the collection

This approach enables you as the programmer to assign specific tasks to eachcomponent and keep them loosely coupled so that you can easily change onecomponent without making massive changes to the rest of your application As anexample you can change HelloWorldServlet to access another database (other thanDB2) without affecting the two other servlets in the chain

Deploying the codeVAJ

1 Bring up WTE and start the servlet engine

2 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

40

ORION

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Start ORION (eORIONjava -jar orionjar)

3 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

41

42

Lesson 8 - Object ScopeThis lesson is a sidetrip to learning the concept of object scope We need to cover thisimportant topic before we head on to JSPrsquos (are we there yet)

BasicsIn the previous lesson we learned to create javabeans and put them in a collection(called divList) to be processed by another set of codes within the same servlet We alsotoyed with the idea of creating another servlet (DisplayServlet) that will construct the htmloutput from this collection Since we want to pass the collection from HelloWorldServletto DisplayServlet we need to somehow associate the collection object with a particularscope When we perform a server-side redirect the request and response objects arepassed as arguments in the forward method Before we actually forward the process toanother servlet we make sure that we associate the collection object to the requestobject so that the receiving servlet can access that collection This is an example of anobject scope and in this instance we defined the collection to be in the request scope

A simple definition of Object Scope is the level of availabilityvisibility of an object withinthe application

It can be any of the following

page - object is visible in the page that created itrequest - object is visible in the request to which is belongssession - object is visible in the same session where it was created application - object is visible within the entire application Any servlet regardless of

what session created them can access the object in this scope

To associate an object to a particular scope we use the setAttribute() method If we want to say make the divList collection available to a userrsquos session we use thefollowing code

HttpSession session = requestgetSession(true)sessionsetAttribute(ldquodivListrdquodivList)

so long as the session still exists we can extract that collection at any point within theapplication with the following code

HttpSession session = requestgetSession(true)ArrayList divList = (ArrayList) sessiongetAttribute(ldquodivListrdquo)

Note We have to cast the collection back to itrsquos original form which is an ArrayList

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

43

Letrsquos create the DisplayServlet that we discussed in the previous lesson

1 Create a class called DisplayServlet in your TRAINING project in the packagecomffictraining and paste the following

import javaioimport javaxservletimport javaxservlethttp

import javautilpublic class DisplayServlet extends HttpServlet

ArrayList divList = new ArrayList()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionresponsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCodeDescriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() +ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

2 Open HelloWorldServlet and make the following changes

comment out the following lines of code in the doGet() method

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCode Descriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +

44

divbeangetDivDesc() + ldquolth3gtrdquo)

add the following lines of code after the stmtclose() line

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

Display Servlet

1 We define DisplayServlet by extending HttpServlet

public class DisplayServlet extends HttpServlet

3 Define an ArrayList to contain the collection that this servlet will receive fromHelloWorldServlet

ArrayList divList = new ArrayList()

4 Set the content type and get the output writer from the response so we can startwriting output data to it

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()

5 Retrieve the divList collection from the request object and cast it back to an ArrayList

divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)

6 Create the html output while iterating through the collection

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

HelloWorldServlet

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

45

1 The lines that we removed from this servlet were transferred to DisplayServlet

2 In the lines that we added we associate the divList collection with the request objectand then do a server-side redirect to DisplayServlet

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquo

RequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtDisplayltnamegtltdescriptiongtDisplay Outputltdescriptiongt

ltcodegtcomffictrainingDisplayServletltcodegtltautostartgttrueltautostartgtltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtDisplayltservlet-namegtltservlet-classgt

comffictrainingDisplayServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

46

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

47

Lesson 9 - Java Server Pages (JSP)BasicsIn the previous lessons we had been constructing our html response within the servletitself It works well with simple html outputs but later on as your webpages get morecomplicated you will find (or you may already have) that this will not work for real-worlddevelopment Java Server Pages (JSP) technology was introduced to make life easier forus programmers and for web designers How If yoursquore familiar with HTML JSP isbasically an html page with little (thatrsquos the plan) java code You get to construct your htmlpage as you normally would and start putting in java logic to a) iterate through acollection of beans b) to include output from another jsp and more To create a jsp filefrom a static html file simply change the filersquos extension from html to jsp and yoursquoreready to go But wait therersquos moreBefore we move on also remember that a jsp is first converted and compiled into aservlet by the web container before it is executed so it will have a similar life cycle as thatof a servlet Inside the jsp file we can put java codes to create dynamic output on thebrowser We accomplish this by using scriptlets expressions declarations and directiveswhich are described below

Scriptlet lt

Scriptlets are regular java codes that are automatically executed by the jsp containerwhen the jsp is invoked so they should be syntactically correct

lt String i = ldquofoordquoSystemoutprintln(i)

gt

Expression lt=

Expressions evaluate to a value that is directly displayed on the browserlt= i gt

The example is converted to outprintln(i) by the jsp container and the value of ldquoirdquo isdisplayed on the browser

Declarations lt

Declarations are java codes that are not automatically executed by the jsp container butmay be invoked if you call it from a scriptlet

lt static printName (String name) Systemoutprintln(name)

gt

48

You can invoke this by writing a scriptlet such as

lt printName(ldquoMyNamerdquo) gt

Directives lt

Directives desribe the necessary components of a jsp

lt page import=rdquojavautilcomffictrainingrdquo gt ==gt imports necessary packageslt taglib uri=rdquobeanrdquo prefix=rdquobeanrdquo gt ==gt declares a taglib referencelt include file=rdquoextraInfojsprdquo gt ==gt includes output from another jsp file

Coding

Suppose the web designer (if there is one) hands you this html file (DisplayDivhtml) lthtmlgtltbodygtlttable border=1gt

lttr align=left gtltthgtDivision IDltthgtltthgtDescriptionltthgtlttrgtlttr align=leftgtlttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgtlttdgt2lttdgtlttdgtCID Voluntarylttdgtlttrgt

lttablegtltbodygtlthtmlgt

The browser output looks like this

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

49

So you the java programmer need to convert this layout to a dynamically generated htmlfile

KNOWN

The data will come from the IOUDIVISION table You already have the servlets (ControllerServlet and HelloWorldServlet) necessary to

perform data retrieval from the db You have a DisplayServlet servlet that creates html output but you want to use a jsp

since you already have the html code and you just need to insert the necessary javacodes to render the dynamic output correctly

HINT We created javabeans (DivisionBean instances) containing Division information and

put them in a collection (divList) that is associated with the request object In our jsp file we can retrieve this collection and iterate through them pretty much the

same way we did with DisplayServlet So most of the codes that we have inDisplayServlet can be reused in the jsp file

Code Walkthrough

1 If you saved the above code in DisplayDivhtml simply rename it to DisplayDivjsp tomake it a jsp file

2 At the topmost portion paste the following code

lt page import=rdquojavautilcomffictrainingrdquo gt

This tells the jsp page that your scriptlets will be looking for necessary classes in thesepackages

3 To display the division code and description we have to insert codes that iteratethrough the collection and render them inside the table

Just after the table header definition (The ones with the ltthgt ltthgt tags) make thefollowing changes

delete the following lines of codes since these are just representations of what thedynamic portion of the page are

lttr align=leftgt

lttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgt

lttdgt2lttdgt

50

lttdgtCID Voluntarylttdgtlttrgt

insert the following codes

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()gt

Notice that this is strikingly similar to the code in DisplayServlet Thatrsquos because we justcut and paste it from there Even though the loop is not yet complete we terminated these lines of code with a ldquogtrdquo because we need to pasteregular html tags or non-java codes right after it

4 Once the above code starts iterating through the collection we need additional codesto render the details so paste the following code right after it

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

Here we used expressions to execute the ldquogetrdquo methods of the DivisionBean instance toretrieve the division code and description

5 Now this is where most beginners get bit We need to properly terminate the ldquowhilerdquoloop that we started in the previous steps To do this paste the following code rightafter the previous step

lt End whilegt

The completed code looks like the following

lt page import=rdquojavautilcomffictrainingrdquo gtlthtmlgtltbodygtlttable border=1gt

lttr align=leftgtltthgtDivision IDltthgtltthgtDescriptionltthgt

lttrgt

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

51

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()

gtlttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End whilegt

lttablegtltbodygtlthtmlgt

HelloWorldServlet

Open HelloWorldServlet and make the following changes

1 Remove the following line of code

String url = ldquoservletDisplayrdquo

2 Replace it with the following line of code to forward the process to DisplayDivjspinstead of DisplayServlet

String url = ldquoDisplayDivjsprdquo

Deploying the codeVAJ

1 Be sure to save DisplayDivjsp in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

52

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Save the DisplayDivjsp file in eservletscraft3 Start ORION (eORIONjava -jar orionjar)4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

53

Lesson 10 - Custom TagsBasicsIn Lesson 9 you learned how to create a JSP to handle content rendition in place of aservlet Wersquove seen how the same codes that we used in the servlet can be re-appliedinside the JSP using scriptlets expressions declarations and directives Again as yourJSPs get more complicated you will want to reduce the amount of java codes in themespecially codes or logic that are candidates for re-use in other JSPs In our exampleprogram if you want the logic that displays the Division information in more than oneJSPs you may want to put that body of code in a central place where you can just call itfrom different JSPs Otherwise you will end up copyingpasting the same codes in everyJSP that needs these codes

Starting with JSP 11 a feature was introduced wherein java codes can be encapsulatedand represented on the JSP using custom tags Custom tags are not unlike HTML tags(ie lthtmlgt ltformgt lttablegt etc) except that we provide the logic that makes the tagswork An example is to replace the scriptlets in your JSP with one tag such asltapplistDivision gt and this will take care of displaying the list of division codes anddescriptions JSP 12 introduced more enhancements to the custom tag feature such asIterationTag but we wonrsquot cover it here since FFIC still uses JSP 11 in WebSphere

Anatomy of a Tag

ltmytaggtvalueltmytaggt

ltmytaggt - opening tagvalue - body of the tagltmytaggt - closing tag

Custom Tag components

1 Developer-provided class that extends the classjavaxservletjsptagextTagSupport TagSupport is a helper class that implementsthe Tag interface When you write your custom tag you will need to implement atleast one of the two most used methods

doStartTag()

triggered when the opening tag is encountered return SKIP_BODY if you donrsquot want to evaluate the body of the tag return EVAL_PAGE_INCLUDE to evaluate the body of the tag

doEndTag()

triggered when the closing tag is encountered return EVAL_PAGE to continue processing the rest of the JSP

54

return SKIP_PAGE to halt processing of the JSP

2 TagLib Descriptor An XML file that describes the custom tag and the class thatimplements the logic

Example

You can save this in a file named apptldltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomfficexamplestrutsDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

3 WEBXML appWEBAPP entry ndash describes the location of your taglib descriptorand assigns a URI to be used in your JSP

Example

lttaglibgtlttaglib-urigtcraftlttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 JSP Directive ltndash tells your JSP that you will be using a custom tag what itrsquos URIis and how you will reference it in your page (using a prefix)

Example

Place this at the top of your JSP

lttaglib uri=WEB-INFapptld prefix=app gt

With these components in place you can start using custom tags in your JSPs

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

55

CodingNow letrsquos create a custom tag out of the scriptlets that we have in DisplayDivjsp

1 In VAJ in the package comffictraining create a class named DivisionTag andpaste the following codes

Insert the typersquos description here Creation date (1802 11910 PM) author Administrator

import javautilimport javaxservletjsptagextTagSupportimport javaxservletjsp

public class DivisionTag extends TagSupportHere we used the doEndTag() method to start evaluating after the body In thiscase there is no bodypublic int doEndTag() throws JspException We retrieve the collection (divList) from the request that is forwarded byHelloWorldServletArrayList divList = (ArrayList)pageContextgetRequest()getAttribute(ldquodivListrdquo)

We then iterate through the collection as we did before and write the output tothe outputstream of the pagetry Iterator iterator = divListiterator()

while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()pageContextgetOut()print(ldquolttr align=leftgtlttdgtrdquo + divbeangetDivNo() +ldquolttdgtlttdgtrdquo + divbeangetDivDesc() + ldquolttdgtlttrgtrdquo)

pageContextgetOut()print(ldquolth3gthelplth3gtrdquo) catch (Exception e) throw new JspException(etoString())

We return eval page to tell the JSP to continue processing the rest of thepage if anyreturn EVAL_PAGE

2 We then need to create a taglib descriptor for this new class Create a file namedapptld and paste the following code

56

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomffictrainingDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

lttaglibgt

3 We then need to tell the webserver about this taglib descriptor In the webxml file(only for Orion) lttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 Copy the DisplayDivjsp to a new JSP file named DisplayDivTagjsp and make thefollowing changes

Remove the following lines of code

lt page import=rdquojavautilcomffictrainingrdquo gt

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext())

DivisionBean divBean = (DivisionBean) inext()gt

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End while(ihasNext())

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

57

gt

At the top of the jsp add the following

lttaglib uri=WEB-INFapptld prefix=app gt

This tells the JSP to use apptld and that we will reference this as app allthroughout the page

Just below the table heading tags add the following line of code

ltapplistDivision gt

This invokes the DivisionTag class and starts writing the output to the page

5 Finally open HelloWorldServlet and make the following changes

In the doGet() method remove the line

String url = ldquoDisplayDivjsprdquo

Replace it with

String url = ldquoDisplayDivTagjsprdquo

Deploying the codeVAJ

1 Save the DisplayDivTagjsp in the Javaideproject resourcesIBM WebSphereTestEnvironmenthostsdefault_hostcraft folder

2 Bring up WebSphere Test Enviroment and start the servlet engine

3 Bring up a browser and type the following in the address line

httplocalhost8080craftservletController

ORION

1 Export HelloWorldServlet and DivisionTag to eservletscraftWEB-INFclasses

2 Save DisplayDivTagjsp in eservletscraft

3 Start Orion (eORIONjava ndashjar orionjar)

4 Bring up a browser and type the following in the address line

httplocalhostcraftservletController

58

Result

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

59

Lesson 11 - Model-View-Controller Design PatternBasicsIf you got this far and have understood the previous lessons then you can pat yourself onthe shoulder and say that yoursquore ready to put things together Actually you already haveWe just need to give what yoursquove been doing these past few lessons a catchy name andthat too is already done Over the years as java technology developed design patternsstarted to emerge As these patterns are recognized the most effective ones enduredand took on lives of their own One of these patterns which according to old-timers wasused to program Smalltalk applications is called Model-View-Controller or MVC for shortMVC is also called JSP Model 2 architecture Is there a Model 1 Yes there is and wersquollbriefly discuss the differences between the two models

JSP Model 1

This architecture puts the responsibility of acting on a user input accessing a db andmaintaining application state solely on a single JSP This may do for small applicationsbut not for complex ones The programmer will end up flooding the JSP with tons andtons of scriptlets and other java codes that should logically reside somewhere elseMoreover it is very difficult to coordinate the actions of all JSPs within the applicationsince they are not designed to communicate with each otherBelow is a ldquoreusedrdquo diagram of a JSP Model 1 architecture

JSP Model 2 (MVC)

This architecture extends the Model 1 concept by separating the content rendition (View)function from the application state (Model) and then adding a Controller that conducts theflow of processes within the application This provides for a clean separation ofresponsibilities between each component which results in a clearer definition of roles forweb designers and java programmers

60

Here is another ldquoreusedrdquo diagram and this time of a JSP Model 2 architecture

MVC is composed of obviously a model a view and a controller each of which havespecific functions which are described as follows

Model - represents the state of the application at any given point in time

View - renders the state of the application to the user It also receives user input andsend it to the controller for proper disposition

Controller - acts on a user input determines what action needs to be done delegatesthe action to the required business logic and invokes the Model to change itrsquos state asnecessary

There is no exercise for this lesson I thought Irsquod give you a break before we proceed withthe next one Think of this as the ldquocalm before the stormrdquoHowever letrsquos go through what yoursquove put together so far and try to match theservletsjsp against the MVC components

ControllerServlet (controller) - this contains the beginnings of a controller servlet Bytyping in the URL for this servlet on the browserrsquos address line we are asking it toperform a service for us Inside itrsquos doGet() method it knows that it needs to delegate thetask to HelloWorldServlet which performs the db access and creation of javabeans

HelloWorldServlet (model) - creates and maintains the Model for this little webapplication by storing the data in javabeanscollection It then notifies the View that theModel has changed and that it needs to render the new state

DisplayDivjsp (view) - this jsp page does not know what is happening inside theapplication All it knows is that it gets a notification from the Model that itrsquos state haschanged and that the View needs to re-render it

There we have a mini-MVC application running in our web container Of course it takesmore than a couple of servlets and a jsp to create a real-world web application and thatrsquos

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

61

what we aim to do in the next lessons Keeping this design pattern in mind we are thenready to make a quantum leap to using a framework called STRUTS that implementsthis design pattern I will save the discussion on STRUTS for the next lesson All youneed to know at this point is that STRUTS solves most of the problems (or I should saychallenges) that you will encounter when you try to build your own MVC applicationframework

6

Lesson 12 - Introduction to the Struts FrameworkApplications are generally composed of two major components business-specificcomponents and application services As an application programmer your focus tends tobe more on coding business components rather than application services since thedevelopment life-cycle is really all about gathering business requirements and creatingsystem solutions for them You will just want to be able to code your applicationrsquosbusiness functions and tie them together to create an entire process

Waawa

T

If yoursquore familiar or had worked on CICS applications then it will be easier to graspthe concept of frameworks and what they do to speed up application developmentWhen putting together a CICS application yoursquoll typically need the followingcomponents

1 Entries for CICS tables such asFile Control Table (FCT) ndash contains file aliases (tied to physical file names) to beaccessed in the CICS region (QSAM VSAM etc)

Program Control Table (PCT) ndash defines the relationships between programs andthe files they use

Program Properties Table (PPT) ndash defines the program names transaction idsand typeTerminal Control Table (TCT) ndash contains terminal definition that canaccess the CICS region

2 The symbolic and physical maps (mapsets) for the screen definitions3 CICS programs that contain the flow of the application and business logic

functions4 In the CICS startup jcl you need to put information such as load libraries (should

be in the correct order) of your programs

Once you correctly define and build these components CICS has the responsibility oftying these components together and making sure that when a user types aTransaction ID it will invoke the correct program for it and assign the correct files tothe program Unless you have too much time on your hands you do not want to findout how CICS performs these underlying processes to run your programs

2

ith application development using java programmers have had to build both businessnd application service layers for every application that they construct Most of thepplication services are so customized to the business that there is no way to reuse themith another application so programmers tend to solve the same problems over and overgain

he solution Enter frameworks

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

63

A couple of years back some genius named Craig McClanahan thought up a java-basedframework (Struts) using the MVC design pattern that is generic reusable andextensible (and of course free) It provides a lot of the application services needed toglue an application together while still giving application developers a lot of control overthe business-specific codes that they write Struts is an open source product available fordownload from wwwjakartaapachecomstruts It has a fairly big and activedeveloperuser community that can help beginners get up to speed in using Struts andanswer Struts-related questions that may not be mentioned in available documentation

Struts provides the following application services among other things

request routing errormessage handling generating client-side scripts tag libraries jdbc connection pooling xml parsing automatic population of java beans internationalization of prompts and messages validation menus page layouts

Struts ComponentsSTRUTS ESSENTIAL CLASSES

Struts employs what is called in J2EE lingo a Front Controller pattern wherein it has asingle servlet that receives all requests from the browser and forwards the processing tothe appropriate class handler In essence we do not need servlets other than the oneStruts provides We may sometimes need to extend the functionality of that servlet but inmost cases the vanilla version will do Below are the frequently used classes in theStruts framework with short descriptions

ActionServlet ndash This is the only servlet in the framework and itrsquos job is to receiverequests populate appropriate javabeans from the request delegate the process toanother class that contains business logic (Action) and forwards the process to the nextcomponent as defined in the mapping

Action ndash a class that performs a specific business function (can also dispatch to abusiness logic bean) and returns control back to the ActionServlet with correspondinginformation as to what to do next

ActionForm ndash a javabean that holds the state of the application Programmers writebeans that extend this class so that the ActionServlet can recognize it and populate itwith data from incoming requests

64

ActionForward ndash contains information that tells the ActionServlet the next componentthat will handle the current request

ActionMapping - contains information on Action classes ActionForms and resource filepaths It is read by the ActionServlet to determine which Action will process a request

ActionErrors ndash contains ActionError objects that may have been created whileprocessing a request The contents can then be rendered on an html page

ActionMessages ndash similar to ActionErrors Contains ActionMessage objects createdwhile processing a request The contents can also be rendered on an html page

JSP AND TAG LIBRARIES

In addition to the Struts classes the content rendition portion of the framework uses JSPand custom tags

Bean Tags ndash used to createcopy beans or render bean properties on the pageHtml Tags ndash used to render html form tagsLogic Tags ndash used to perform logical operations such as comparison andor to check forpresenceabsence of beans in the pageNested Tags ndash used to render nested bean properties on the pageTemplate Tags ndash used to render a composite of several jsp pages by pulling these insidea pre-defined layout

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

65

ldquoI canrsquot find the MVC pattern anywhererdquoOK so herersquos a diagram of the Struts Framework which shows how each of thepreviously discussed components work together

66

In MVC semantics the Controller would be the ActionServlet the Model is handled byAction and ActionForm classes and the View is handled by JSPs and tag librariesDid I mention that Struts works at the Presentation Layer of the application I guess notThis means that it does a swell job of conducting the process flow of programs thatinteract with the user (browser) but developers (thatrsquos you) will still need to come up withthe business objects and the data layer objects So in a bigger picture herersquos a diagramshowing where Struts lies

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

67

Below are UML representations of the different parts of the Struts framework

Action

68

Form

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

69

Message

70

Forward

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

71

Mapping

72

Config

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

73

DynaForm

74

Sequence Diagram for a request

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

75

76

The next lessons will walk you through the installation of the Struts framework in bothVAJavaWebSphere Test Environment and Orion We will also build a sample applicationthat uses most of the Struts features so you can get acquainted on the differentcomponents of Struts and how it fits into you web environment

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

77

Lesson 13 - Installing Struts 11b in VisualAge forJava 40WebSphere Test Environment 353This lesson walks you through the installation of Struts 11b in the WebSphere TestEnvironment in VisualAge for Java 40 It assumes that you already have VAJ 40installed in your workstation and that you have properly configured it using theinstructions in Lesson 2 To make sure that Struts is correctly configured you will need toinstall and run the sample application provided in this lesson

What is missing from this lesson is the explanation for the sample application codes Mygoal here is for the user to quickly setup the environment to run Struts so we can proceedwith the next lessons that discuss the different parts of Struts in greater detail

Installation and configuration1 In VAJ you will need to have the following projects present in your workspace

Servlet API ClassesJava Class LibrariesIBM WebSphere Test EnvironmentIBM Enterprise Extension LibrariesIBM XML Parser for Java

If any of the above is missing

select FileQuick Start from the menu select FeaturesAdd Features from the popup window and select the project

you need to import to your workspace

2 Downloadinstall the following

Note If you have projects in VAJ with the same name as the ones listed below be sureto version them first Then when importing the new packages make sure you selectoption create newscratch editions of versioned projectspackages

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract Xercesjar and import it in VAJava in the project XERCES

Xalan from httpxmlapacheorgxalan-jindexhtml

the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar and import them in VAJava in the project XALAN

78

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip

OPTIONAL

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and import these files to a COMMONS project in VAJava

OR

Recommended

Open the binary distribution of STRUTS and extract all commons jar files and importthem in the COMMONS project in VAJava

Struts 11b source from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1src

link is jakarta-struts-11-b1-srczip import the entire file to a STRUTS project in VAJava

Important

You will need to make some revisions to the Struts source code or you will get the following error Cannotremove Attribute from request scope in your browser I think this problem only occurs in WebSphere

In VAJ go to the orgapachestrutstaglibhtml package and open the FormTag class

Replace the following lines in the doEndTag() method in the FormTag class

pageContextremoveAttribute(ConstantsBEAN_KEY PageContextREQUEST_SCOPE)

pageContextremoveAttribute(ConstantsFORM_KEY PageContextREQUEST_SCOPE)

with the following

pageContextgetRequest()removeAttribute(ConstantsBEAN_KEY)pageContextgetRequest()removeAttribute(ConstantsFORM_KEY)

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

79

3 Open jakarta-struts-11-b1-srczip and extract the following files to eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF

struts-tld dtd xml

Note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 In the directory eappsprogram filesibmVisualAge for JavaideprojectresourcesIBM WebSphere Test Environmenthostsdefault_hostcraftWEB-INF create a file named struts-configxml file and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoISO-8859-1rdquo gtltDOCTYPE struts-config PUBLIC

ldquo-Apache Software FoundationDTD Struts Configuration 11ENrdquoldquohttpjakartaapacheorgstrutsdtdsstruts-config_1_1dtdrdquogt

ltstruts-configgtltform-beansgtltform-bean name=rdquoempFormrdquo type=rdquocomfficexamplestrutsEmployeeFormrdquo gt ltform-beansgtltaction-mappingsgtltaction path=rdquovalidateEmployeerdquo

type=rdquocomfficexamplestrutsValidateEmployeeActionrdquo name=rdquoempFormrdquo scope=rdquorequestrdquo input=rdquoInputContentjsprdquogt

ltforward name=rdquosuccessrdquo path=rdquoOutputContentjsprdquo gt ltactiongtltaction-mappingsgtltstruts-configgt

2 Open the webxml file and replace the contents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquoldquohttpjavasuncomdtdweb-app_2_3dtdrdquogtltweb-appgt

80

ltweb-appgt

Note This file is basically an empty file but we still need to provide this becausethe ActionServlet still looks for it somehow If it canrsquot find the file it throws aMalformedURLException exception

3 In the same directory create a file named apptld and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogtltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library 11ENrdquoldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogtlttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtdepartmentListltnamegtlttagclassgtcomfficexamplestrutsDepartmentTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaggt

ltnamegtskillsListltnamegtlttagclassgtcomfficexamplestrutsSkillsTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaglibgt

4 In VAJ create a project named STRUTS EXAMPLE Create a file namedApplicationResourcesproperties save it in a temporary folder and paste thecodes below in it Add it to the project that you just created (To do this click on theResources tab then right-click on the STRUTS EXAMPLE project and selectAddResource then look for the ApplicationResourceproperties file you just createdand click OK)

errormissingname=ltligtltfont colors ldquoredrdquogtPlease Enter the first nameltfontgtltligterrormissingdepartment=ltligtltfont colors ldquoredrdquogtPlease pick a departmentnameltfontgtltligterrormissingskills=ltligtltfont colors ldquoredrdquogtPlease select the relevant skillsltfontgtltligtpromptemployeename=ltbgtFirst Name ltbgtpromptemployeedepartment=ltbgtDepartment ltbgtpromptemployeeskills=ltbgtSkills ltbgt

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

81

5 Open the craftwebapp file located in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft and replace the contents with the followingcode

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegtltservletgt

ltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegtltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgtltinit-parametergt ltnamegtapplicationltnamegt

ltvaluegtApplicationResourcesltvaluegt ltinit-parametergt ltinit-parametergt

ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdebugltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdetailltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtvalidateltnamegt ltvaluegttrueltvaluegt

ltinit-parametergtltservletgt

ltservletgtltnamegtinvokerltnamegt

82

ltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegtltvaluegtindexhtmlltvaluegt

ltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

6 In VAJ create a project named STRUTS EXAMPLE and in it create a packagenamed comfficexamplestruts then create a class named EmployeeForm andpaste the following code in

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

83

Insert the typersquos description hereCreation date (1802 10946 PM)author Administrator import orgapachestrutsactionActionFormimport orgapachestrutsvalidatorValidatorForm

public class EmployeeForm extends ActionForm

private String name = ldquordquoprivate String department = ldquordquoprivate String[] skills

EmployeeForm constructor comment public EmployeeForm()

super()

public String getDepartment() return department public String getName() return name public String[] getSkills() return skills public void setDepartment(String department) thisdepartment = department public void setName(String name) thisname = name public void setSkills(String[] skills) thisskills = skills

7 In the same package create a class named DepartmentTag and paste the followingcode

84

Insert the typersquos description hereCreation date (1802 11513 PM)author Administrator

import javautilListimport javautilArrayListimport javaxservletjsptagextTagSupport public class DepartmentTag extends TagSupport

DepartmentTag constructor comment public DepartmentTag()

super()

public int doStartTag() List department = new ArrayList()departmentadd(ldquordquo)departmentadd(ldquoClient Serverrdquo)departmentadd(ldquoLegacyrdquo)departmentadd(ldquoEmerging Techrdquo)departmentadd(ldquoTech Supportrdquo)

pageContextsetAttribute(ldquodepartmentListrdquodepartment)return SKIP_BODY

8 Create a class named SkillsTag and paste the following code

Insert the typersquos description hereCreation date (1802 11910 PM)author Administrator import javautilimport javaxservletjsptagextTagSupport

public class SkillsTag extends TagSupport

SkillsTag constructor comment

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

85

public SkillsTag()

super()public int doStartTag()

List skills = new ArrayList()

skillsadd(ldquoEJBrdquo)skillsadd(ldquoJava Mailrdquo)skillsadd(ldquoJSPrdquo)skillsadd(ldquoHTMLrdquo)skillsadd(ldquoCOBOLrdquo)skillsadd(ldquoCICSrdquo)skillsadd(ldquoCrdquo)

pageContextsetAttribute(ldquoskillsListrdquoskills)return SKIP_BODY

9 Create a class named ValidateEmployeeAction and paste the following code

Insert the typersquos description hereCreation date (1802 125818 PM)author Administrator

import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

86

public class ValidateEmployeeAction extends orgapachestrutsactionAction

ValidateEmployeeAction constructor comment public ValidateEmployeeAction()

super()

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException ActionErrors errors = new ActionErrors()EmployeeForm empForm = (EmployeeForm) form

String name = empFormgetName()if(nametrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingnamerdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String department = empFormgetDepartment()if(departmenttrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingdepartmentrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String[] skills = empFormgetSkills()if(skills == null)

ActionError error = new ActionError(ldquoerrormissingskillsrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

if(errorssize() gt 0)

saveErrors(requesterrors)return new ActionForward(mappinggetInput())

return mappingfindForward(ldquosuccessrdquo)

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

87

10 In eappsprogram filesibmVisualAge for Javaideproject resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft create a file namedInputContentjsp and paste the following 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-INFapptld prefix=app gtlthtmlgt

ltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgtlthtmltext property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogtlttdgtlttdgtlthtmlselect property=rdquodepartmentrdquogtlthtmloptions name=rdquodepartmentListrdquogtlthtmlselectgtlttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogtltbeanmessage key=rdquopromptemployeeskillsrdquogtlttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoskillsListrdquogtlthtmlmultibox property=rdquoskillsrdquogtlt= currentSkill gtlthtmlmultiboxgtlt= currentSkill gt

88

ltbr gtltlogiciterategtlttdgtlttrgtlttrgtlttd colspan=rdquo2rdquo align=rdquocenterrdquogtlthtmlsubmit value=rdquoValidaterdquogtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

11 In the same folder create a file named OutputContentjsp and paste the followingcode

lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gtlttaglib uri=WEB-INFapptld prefix=app gt

lthtmlgtltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgt

ltbeanwrite name=rdquoempFormrdquo property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogt

lttdgt

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

89

lttdgt ltbeanwrite name=rdquoempFormrdquo property=rdquodepartmentrdquogt

lttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogt

ltbeanmessage key=rdquopromptemployeeskillsrdquogt

lttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoempFormrdquo property=rdquoskillsrdquogt

lt= currentSkill gtltbrgt

ltlogiciterategtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

12 Just to make sure that you have the craft application correctly configure make surethat the file defaultservlet_engine located in eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere Test Environmentpropertiescontains the following entry

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

13 In the end the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstrutsmdashconfigxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtld

90

struts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd|_ classes

Deploying and running the sample application1 Bring up the WebSphere Test Environment then click on Edit Class Path

click Select All enter the following text in the extra classpath area

EAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INFclassesEAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INF

click OK

2 Start the servlet engine

3 Once the servlet engine is started

bring up a browser enter the following URL httplocalhost8080craftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

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

91

Enter stuff in it and press Validate and

92

Lesson 14 - Installing Struts 11b in ORIONThis lesson walks you through the installation of Struts 11b in the Orion webserver Aswith the WebSphere installation you need to go through Lesson 1 to prepare yourenvironment Installation of the sample application relies heavily on the instructions inLesson 12 so it is assumed that you have already gone through that lesson Otherwisefollow the instructions for Installing the sample application in Lesson 12 to create thenecessary components

Installation and configuration1 Downloadinstall the following

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract the Xercesjar file and save it in EORIONservletscraftWEB-INFlib

Xalan from httpxmlapacheorgxalan-jindexhtml the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar save them in EORIONservletscraftWEB-

INFlib

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip extract Strutsjar and save it in EORIONservletscraftWEB-INFlib

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and save the commons-jar files toEORIONservletscraftWEB-INFlib

OR

Open the binary distribution of STRUTS and extract all commons jar files and save themin

eORIONservletscraftWEB-INFlib

2 Open jakarta-struts-11-b1zip and extract the following files toeORIONservletscraftWEB-INF

struts-tld ndash dtd ndash xml

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

93

note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 Copy the file struts-configxml from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF toeORIONservletscraftWEB-INF

2 Open the webxml file in eORIONservletscraftWEB-INF and replace thecontents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquo

ldquohttpjavasuncomj2eedtdsweb-app_2_3dtdrdquogt

ltweb-appgtltservletgt

ltservlet-namegtactionltservlet-namegtltservlet-classgtorgapachestrutsactionActionServletltservlet-classgtltinit-paramgt

ltparam-namegtapplicationltparam-namegtltparam-valuegtApplicationResourcesltparam-valuegt

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgtltservlet-mappinggt

ltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggtlttaglibgtlttaglib-urigtbeanlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-beantldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigthtmllttaglib-urigt

94

lttaglib-locationgtWEB-INFstruts-htmltldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtformlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-formtldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtlogiclttaglib-urigt

lttaglib-locationgtWEB-INFstruts-logictldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigttemplatelttaglib-urigtlttaglib-locationgtWEB-INFstruts-templatetldlttaglib-locationgtlttaglibgtlttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgt

lttaglibgtltweb-appgt

3 Copy the file apptld from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraftWEB-INF

4 Copy the file ApplicationResourcesproperties from eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftcomfficfincraftresource toeORIONservletscraftWEB-INFclasses

5 From VAJ export the class named EmployeeForm to

eORIONservletscraftWEB-INFclasses

Note the classes will be exported to the corresponding directory structurecomfficexamplestruts

6 From VAJ export the class named DepartmentTag toeORIONservletscraftWEB-INFclasses

7 From VAJ export the class named SkillsTag to eORIONservletscraftWEB-INFclasses

8 From VAJ export the class named ValidateEmployeeAction toeORIONservletscraftWEB-INFclasses

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

95

9 Copy the file InputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

10 Copy the file OutputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

11 Upon completion the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstruts-configxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtldstruts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd

|_ classesApplicationResourcesproperties|_com

|_ffic|_example

|_strutsValidateEmployeeActionclassDepartmentTagclassSkillsTagclassEmployeeFormclass

|_libstrutsjarXercesjarXalanjarxml-apisjartilesjarcommons-validatorjarcommons-servicesjarcommons-pooljar

96

commons-loggingjarcommons-digesterjarcommons-dbcpjarcommons-collectionsjarcommons-beanutilsjar

Deploying and running the sample application1 Start ORION (eorionjava -jar orionjar)

2 Once the ORION is started

bring up a browser enter the following URL

httplocalhostcraftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

Enter stuff in it and press Validate and the output should look something like the nextscreen

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

97

98

Lesson 15 - Struts ComponentsHere is a more detailed discussion on the commonly used classestaglibs in the Strutsframework To learn Struts I strongly suggest that you read this document a number oftimes revisit the example application andor hack it and most important of all ask lots ofquestions It takes more than just this document to help you understand and work withthe struts framework The last part of this document lists some very useful struts-relatedURLs that can supplement what yoursquove learned so far

Struts ComponentsThe classes described below are part of the Struts distribution package which youdownloaded in Lesson 13 In VAJ these are in the STRUTS project They may also befound in the strutsjar file that came with the binary distribution of struts

ActionServlet (orgapachestrutsactionActionServlet)

This class extends HttpServlet and is the only servlet in the Struts framework

Itrsquos main responsibilities are

receive request from the browser automatically populate any associated javabeans (ActionForms) with data from the

browser determine the class (Action) that will process the request receives notice of completion from the Action class to do either a a server-side or

client-side redirect

To configure the ActionServlet we need to enter information about this servlet in theapplication deployment descriptor just like any other servlets

In webxml (ORION)

ltservletgtltservlet-namegtactionltservlet-namegtltservlet-classgt

orgapachestrutsactionActionServletltservlet-classgt

This line tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-paramgtltparam-namegtapplicationltparam-namegtltparam-valuegt

ApplicationResourcesltparam-valuegt

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

99

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-mappinggtltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggt

In craftwebapp (VAJWebSphere Test Environment)

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgt

This tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-parametergt ltnamegtapplicationltnamegt ltvaluegt

ApplicationResourcesltvaluegt ltinit-parametergt

This tells the ActionServlet where to look for mapping information(ActionActionForm definitions)

ltinit-parametergt ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltservletgt

Yoursquoll notice that we sometimes override some initialization parameters for theActionServlet with our own values For a complete list of initialization parameters youcan go the jakartaapachecomstruts website For our purpose of building a simplestruts-based application these initialization parameters will suffice

100

ActionForm (orgapachestrutsactionActionForm)

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

public class DivisionBean extends orgapachestrutsactionActionForm

place your settersgetters etc here

Enter the form information in the struts-configxml file using ltform-beangt tags

ltform-beansgtltform-bean name=rdquoDivisionFormrdquo type=rdquocomffictrainingDivisionBeanrdquo gt

ltform-beansgt

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

ltaction-mappingsgtltaction path=rdquovalidateDivisionrdquo

type=rdquocomfficexamplestrutsValidateDivisionrdquoname=rdquoDivisionFormrdquoscope=rdquorequestrdquoinput=rdquoInputjsprdquogtltforward name=rdquosuccessrdquo path=rdquoDisplayDivisionjsprdquogt

ltactiongtltaction-mappingsgt

Action (orgapachestrutsactionAction)

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)

250

Complete code (comffictrainingLoginAction)

import orgapachestrutsactionimport orgapachestrutsvalidator

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

public class LoginAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws IOExceptionServletException

ActionErrors errors = new ActionErrors()

try

errors = ((DynaValidatorForm)form)validate(mappingrequest)if (errorsempty())

saveErrors(request errors) return new ActionForward(mappinggetInput())

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

251

5 We then need to define new validation rules for the dynamic form Open the filevalidationxml located in craftWEB-INF and add the following entries within theltformsetgt tags

ltform name=logonFormgtltfield property=userId depends=requiredgt

ltarg0 key=promptloginusergtltfieldgtltfield property=password depends=requiredmaskgt

ltarg0 key=promptloginpasswordgtltvargt

ltvar-namegtmaskltvar-namegtltvar-valuegt^[a-zA-Z]$ltvar-valuegt

ltvargtltfieldgt

ltformgt

The rules are the same as the entry for loginForm except that we donrsquot force the user to enter avalid email address in the userId field This tells us that this rule is what gets read when we validatethe login information in the DynaValidatorForm

Deploying the code (Part 2 ndash DynaValidatorForm 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

Result (Part 2 ndash DynaValidatorForm example)The result should look like the following screens below

The login form

252

Submitting the form without any data will result in the following screen

Entering a userid and an alphanumeric password will result in 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

253

Entering a userid and an alpha password will navigate the user to the welcome page

Since the user was not required to enter a valid email address for the userid we can besure that the new process is whatrsquos working behind the scenes to contain form data usingthe DynaValidatorForm and to perform the validation using struts-validator

254

Lesson 28 ndash Using tokensBasics A highly recommended way of keeping our transactions in synch is the use of tokens Atoken is a random number that gets stored in the users session a copy of which issupposed to be stored in the request If the session and request tokens are missing orare different then the transaction is out of synch To illustrate this if we have a processthat adds a record to a database using a jsp and an action class The user aftersubmitting the form and getting the confirmation that the record was successfully addedmay click on the dreaded BACK button and navigate back to the data entry screen andclick the SUBMIT button again to add the same record As a rule of thumb it is not safeto assume that users will follow instructions all the time ndash most will but there are a fewgremlins out there who will want to play around with the application We want to design asystem that deals with this type of situation The simplest way to address this is to use atoken that gets created when the entry form is displayed for the first time and theninvalidatedreset after the successful completion of the operation If the user tries to goback to the data entry screen the token will no longer be valid since it has already beenreset and therefore we can navigate the user to an error page where he canrsquot hurt himselfor the application

CodingInstead of creating a new process we will use the existing edit function to demonstratethe use of tokens in Struts

The flow of the new edit process will be as follows

Displayjsp will display all Division items Clicking on the ldquoeditrdquo link will invoke DivisionActionrsquos edit() method which will bring up

an edit page containing the selected Division item At this point a token will begenerated

The user makes changes to the division descripition (or not) and submits the formThe DivisionActionrsquos update() method will then be invoked In this method the tokenwill be validated and if valid the update will occur Otherwise the user will be thrownto the login page with the corresponding error message

1 In VAJ make the following changes to the edit() and update() methods of theDivisionAction class and the execute() method of the FindDivisionAction class

Add the following line of code within the try block just before returning an ActionForward

saveToken(request)

This code puts the token in the request which will be written in the output jsp as a hiddenfield inside the lthtmlformgt 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

255

2 Next is to make changes to the update() method of the DivisionAction class tovalidate the token and make the necessary decisions

In the try block change the following lines of code

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

to

if (isTokenValid(request))

resetToken(request)

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

else

ActionError error = new ActionError(errorduplicatesubmit)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

3 Since we created a new key for an error message in the previous step we need tomake an entry in the ApplicationResourcesproperties to assign a value to thiskey Add the following line of code in the ApplicationResourcesproperties file

errorduplicatesubmit=ltbgtltfont color=redgtDuplicate page submission session has beeninvalidate Please log in againltfontgtltbgt

4 There is also a new forward named loginpage in the update() method so add aforward named loginpage for the DivisionAction action-mapping entry in struts-configxml that maps to the login jsp

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

256

ltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

We have completed the coding changes at this point so letrsquos 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 Click on the Display Division link

ResultTo test out the use of the token just follow the screen sequence below

The list of division items will be displayed initially

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

257

Select an item to bring up an edit screen

258

After submitting the edit form the items will be redisplayed

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

259

Clickin on the browserrsquos back button will cause the screen to navigate back to the editpage

Since the token was already reset submitting that same form will trigger an exceptionand the screen will navigate to the login page with the corresponding error message

260

Lesson 29 ndash Implementing security in StrutsBasics

First some definitions

Authentication is the process by which a user submits a set of credentials to theapplication which then checks if the submitted credentials match those that are keptinternally

Authorization is the process of determining if a user authenticated or not is able toaccess a protected resource

J2EE standards provide for container-managed authentication and authorization usingentries in the application deployment descriptor (the deployment descriptor would be thecraftwebapp in VAJ and webxml in ORION) If you are not familiar with and want tolearn about configuring container-managed security form-based authentication inparticular go to this url for an overview ==gthttpwwwonjavacompubaonjava20010806webformhtml The implementation ofcontainer-managed security varies from webserver to webserver and we thereforecannot cover this in our lesson We however will be implementing the authenticationpiece using Policy Director (PD) which uses an LDAP to retrieve user infoauthorizationparameters We will then handle the implementation of the authorization piece withinStruts

Lets look at how our application will interact with PD to authenticate users

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

261

From the diagram above we can retrive the information from the HttpRequestrsquos headerusing the following codes

To retrieve the user name

String user = (String)reqgetHeader(IvUserHeaderKey)

To retrieve the groups to which the user is associated

String groups = reqgetHeader(IvGroupsHeaderKey)

Note that groups is defined as a String instead of a collection This is because theinformation retrieved from the header is a comma-delimited string so we need to providea convenience method to parse this information and place them in a collection

Upon successful authentication we need to save the user information off to a sessionobject so we can access this information anywhere within the application We then needto design a security framework around our application that will provide authorizationservices As mentioned before PD will provide the authentication service for ourapplication

Declarative security

Declarative security provides for setting security parameters outside the applicationcodes usually in an xml file the advantage of which is there is no need to recompile anyof the source codes to effect new security rules

Struts does not (yet) provide for declarative security and for good reason The frameworkneeds to be independent of any type of implementation for authenticationauthorizationfor the purpose of portability While it does not provide declarative security it does haveprovisions which enables developers to quickly develop their own mechanism fordeclarative security The next section will walk you through the steps in creating a simplebut effective security framework in Struts

Coding (Part 1 ndash protecting do classes)In this section we will create an abstract action class wersquoll call it BaseAction that willperform the necessary security checks This way we only have one place to make achange in case we need to enhance the code This class will then be extended by allother action classes

262

Below is a diagram that represents how our example application will look like at the endof this section

1 A ltset-propertygt tag can be used to define arbitrary parameters that will be passedto the action class using the ActionMapping object We will take advantage of thisfeature to declare our own security parameter In the struts-configxml file add thefollowing tag to the action classes that need to be protected

ltset-property property=isSecure value=true gt

Add this tag to the entries for the LoginAction DivisionAction and FindDivisionActionclasses

ltaction path=login type=comffictrainingLoginAction name=logonForm scope=requestinput=Loginjspgt

ltset-property property=isSecure value=falsegtltforward name=success path=welcomepagegt

ltactiongt

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

263

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

ltset-property property=secure value=truegt ltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

ltaction path=findDiv type=comffictrainingFindDivisionAction name=srchFormscope=request input=diveditpagegt

ltset-property property=secure value=truegtltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltexception key=errordivisionnotnumber type=javalangNumberFormatException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=loginpage path=Loginjspgt

ltactiongt

Note The parameter we defined above will cause Struts to invoke the setIsSecure() method ofthe ActionMapping object

2 To make sure that Struts reads the parameter we defined in the previous step weneed to define a variable in subclass of the ActionMapping class with thecorresponding accessorsmutators Create a subclass oforgapachestrutsactionActionMapping named FFICActionMapping in thepackage comffictraining

public class FFICActionMapping extends orgapachestrutsactionActionMapping

Declare a private variable for the parameter

private boolean isSecure = false

Define the settergetter that corresponds with the property attribute in the ltset-propertygt tag

public boolean getIsSecure() return isSecure

public void setIsSecure(boolean secure)

264

thisisSecure = isSecure

Complete code (comffictrainingFFICActionMapping)

Insert the types description here Creation date (6302 24414 PM) author Administrator public class FFICActionMapping extends orgapachestrutsactionActionMapping

private boolean secure = false

Construct a new instance of this class with the desired default form bean scope public FFICActionMapping()

super()

Insert the methods description here Creation date (6302 24740 PM) return boolean public boolean getSecure()

return secure Insert the methods description here Creation date (6302 24717 PM) param secure boolean public void setSecure(boolean secure)

thissecure = secureSystemoutprintln(security indicator set)

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

265

3 Now that weve can set security parameters in our config we need to create anaction class that uses this parameter To centralize the code for this create aabstract class named BaseAction which extends orgapachestrutsactionActionThis class will contain the logic that checks if an action class requires a user to belogged-in If so it then checks if the user is already logged in before it runs theexecuteAction() method of its subclass

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

The execute() method receives the FFICActionMapping object and we cast it here

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

Check if this action class requires the user to be logged-in based on the isSecurevariables value

if (requiresLogin(mapping1))

If log-in is required invoke a method that checks for the presence of the userKeyattribute in the session

if (isUserLoggedIn(request))

Execute the subclasss executeAction() method if user is logged-in

return executeAction(mapping1formrequestresponse)

else

If the user has not been authenticated create an ActionError object with thecorresponding error key and forward the user back to the login page

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

266

else

If no authentication is required that is if the isSecure parameter is not coded in theactionmapping invoke the subclass executeAction() method

return executeAction(mapping1formrequestresponse)

Create an unimplemented executeAction() method which will be implemented bysubclasses of BaseAction

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

This method checks if the user is logged-in to the application

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

This method retrieves the actions isSecure parameter to check if log-in is required

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

Complete code (comffictrainingBaseAction)

package comffictraining

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

267

import orgapachestrutsactionActionimport orgapachestrutsactionActionFormimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservlethttpHttpSessionimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

if (requiresLogin(mapping1))

Systemoutprintln(log-in required)

if (isUserLoggedIn(request))

return executeAction(mapping1formrequestresponse)

else

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

268

else

return executeAction(mapping1formrequestresponse)

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

4 Revise all the action classes - extend BaseAction instead of orgapachestrutsactionAction- change the signature of the execute() method

from

public ActionForward execute(ActionMapping mapping ActionFormform

HttpServletRequest requestHttpServletResponse response)

to

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

269

public ActionForward executeAction(FFICActionMapping mappingActionForm form

HttpServletRequest requestHttpServletResponse response)

So far we have the following action classes to change

FindDivisionAction LoginAction

5 The DispatchAction class which we discussed in previous lessons also needs toextend the BaseAction class to be able to implement the security framework

create a copy of orgapachestrutsactionDispatchAction which extendsBaseAction instead of Action in the package comffictraining

change the signature of comffictrainingDispatchActions execute() method

from

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

to

public ActionForward executeAction(FFICActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

6 Change the DivisionAction class that extendsorgapachestrutsactionDispatchAction to extend the newcomffictrainingDispatchAction

public class DivisionAction extends comffictrainingDispatchAction

7 Revise the LoginAction class to save the user information to a session objectnamed userKey This assumes that the user has been successfully authenticatedby PD and that our code has retrieved the user information from the HttpRequestrsquosheader

requestgetSession()setAttribute(userKey((DynaValidatorForm)form)get(userId))

8 Create a new entry in the ApplicationResourcesproperties file for the followingkeyvalue pair

270

errorusernotauthenticated=ltbgtltfont color=redgtYou have not been properlyauthenticatedplease log inltfontgtltbgt

9 Create the class LogoutAction in the package comffictraining so we caninvalidate the session and later on test the security framework

Create a regular action class

public class LogoutAction extends orgapachestrutsactionAction

In the execute() method just invalidate the session and forward the user to the loginpage

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)

throws Exception ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

Complete code (comffictrainingLogoutAction)

import orgapachestrutsaction

import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponse

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

271

import javaxservletServletException

import javaioIOException

import javasqlConnectionimport javasqlSQLException

import javautilCollection

Insert the types description here Creation date (12202 92827 AM) author Administrator public class LogoutAction extends orgapachestrutsactionAction LogoutAction constructor comment public LogoutAction()

super() Insert the methods description here Creation date (12202 94602 AM) return orgapachestrutsactionActionForward public ActionForward execute(ActionMapping mapping ActionForm form

HttpServletRequest request HttpServletResponse response)throws Exception

ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

272

10 Create an entry for the LogoutAction in struts-configxml

ltaction path=logout type=comffictrainingLogoutAction scope=request input=Loginjspgtltforward name=logoutpage path=logoutpagegt

ltactiongt

11 Create LogoutContentjsp in the craft folder

lttable width=100 height=100gtlttrgt lttd valign=center align=centergt lth2gtYou have been logged off lth2gt lttdgtlttrgtlttablegt

12 Open the file tilesDefinitionxml in craftWEB-INF and create a new definition forthe logout page

lt-- Extended definition for account display --gtltdefinition name=logoutpage extends=welcomepagegt

ltput name=body content=LogoutContentjspgtltdefinitiongt

13 Add a line in the menu-configxml for a link to the logout action class (in bold)

ltMenu name=MainMenu title=MainMenu gtltItem 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 gtltItem name=LogOut title=Log Out location=logoutdo gt

ltMenugt

14 Change the TileTemplatejsp in craft to include code that checks for the presence of theuserKey attribute to correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logic 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

273

Encapsulate the menu with logic tags that check for the presence of the userKey session attribute

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

Complete Code (TileTemplatejsp)

lt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFtilestld prefix=tiles gtlt taglib uri=WEB-INFstruts-logictld prefix=logic gt

ltHTMLgtltHEADgtltTITLEgtFiremans Fund Insurance CRAFTltTITLEgt

ltHEADgt

ltBODYgt ltscript language=JavaScript12 src=scriptscoolmenus3jsgtltscriptgtltscript src=scriptscoolmenu-configjsgtltscriptgt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

lttable width=100 border=0gt lttrgt lttd bgcolor=graygtltdiv align=centergtlth1gtMy Applicationlth1gtltdivgt lttdgt lttrgtlttablegt

lttable width=100 height=75 border=0gt

274

lttrgt lttd width=10 align=right valign=top bgcolor=ABABABgt

lttilesinsert attribute=menu gt

lttdgt lttd width=90 valign=center align=centergt

lttilesinsert name=bodygt lttdgt lttrgtlttablegt

lttable width=100 border=0gt lttrgt lttdgtltdiv align=centergt

ltfont size=-1gtCopyright 2002ltfontgtltdivgt

lttdgt lttrgtlttablegt

15 Change the Menujsp to include code that checks for the presence of the userKey attributeto correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logicgt

Encapsulate the menu with logic tags that check for the presence of the userKey sessionattribute

ltlogicpresent name=userKeygt

ltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

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

275

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

Add the following codes that provides a link to the log-in page Encapsulate this code withlogic tags that make the link appear only if the userKey is not present

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

Complete Code (Menujsp)

lt taglib uri=WEB-INFstruts-htmltld prefix=html gtlt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFstruts-logictld prefix=logicgt

lthtmlgtltheadgtltheadgtltbodygt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt

276

ltmenuuseMenuDisplayergt

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

ltbodygtlthtmlgt

Deploying the code (Part 1 ndash protecting do classes)

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

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

277

Result (Part 1 ndash protecting do classes)The login screen

The welcome page now shows a ldquoLog Outrdquo link which invalidates the session

278

Clicking on the ldquoDisplay Divisionrdquo link displays the division items as before No errors atthis point since the user was successfully authenticated during login

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

279

Clicking on the ldquoLog Outrdquo link will navigate the user to the page below It shows the ldquoLogInrdquo link which navigates the user to the login page when clicked

If instead of logging back in the user types a url(httplocalhost8080craftadminDivdomethod=view) on the address line (or uses abookmark) the application will determine that the user has not been authenticated andwill then be navigated to the login page which displays an error message

280

OK now we can prevent those gremlins from bookmarking our applicationrsquos urls Wehave one more thing to do though there are urls that map directly to our jsp pages and atthis point anyone can type a valid url to a particular jsp and can successfully bring up thepage without authenticating to the system There are two recommended ways ofprotecting the jsps

1 Place all jsps under the WEB-INF folder This folder per J2EE standardcan only be accessed from within an application and is not publiclyaccessible via urls typed in the browser

2 Create a custom tag that checks if the user has been authenticated similarto the code we placed in the BaseAction class and perform a redirect to thelogin page if the user has not properly logged in

For option 1 it works well with J2EE compliant application servers but since we are usingWebSphere 353 there is basically no WEB-INF folder to speak off We created a WEB-INF folder in our craft application but this is just to line up our directory structure withJ2EE standards We will therefore cover option 2 in the next section

Coding (Part 2 ndash protecting jsp pages)Unlike the example that we put together in part 1 of this lesson the custom tag that wewill create in this section unconditionally checks if the user has logged-in already Inshort there will be no logic in this custom tag that is equivalent to the code in therequiresLogin() method of BaseAction The MVC patternrsquos basic premise is that usersneed to interact with a controller at all times and not the view It therefore follows thatusers should not be able to bring up jsprsquos (view) directly without going to an action classfirst

1 As previously mentioned we will create a custom tag that checks if a user has loggedin already In the package comffictraining create a class named CheckLoginTag

Create the class by extending TagSupport

public final class CheckLoginTag extends TagSupport

Create an instance variable containing information for the login page

private String page = loginjsp

The doEndTag() is where we check for the presence of the ldquouserKeyrdquo The logic is similarto the BaseActionrsquos isUserLoggedIn() method

public int doEndTag() throws JspException

Is there a valid user logged on

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

281

boolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered

public int doStartTag() throws JspException

return (SKIP_BODY)

Complete Code

import javaioIOExceptionimport javaxservlethttpHttpSessionimport javaxservletjspJspExceptionimport javaxservletjspJspWriterimport javaxservletjspPageContextimport javaxservletjsptagextTagSupportimport orgapachestrutsactionimport orgapachestrutsutilMessageResourcesimport javaxservlethttpHttpServletRequest

Check for a valid User logged on in the current session If there is no such user forward control to the logon page

282

public final class CheckLoginTag extends TagSupport

The page to which we should forward for the user to log on private String page = loginjsp

Perform our logged-in user check by looking for the existence of a session scope bean under the specified name If this bean is not present control is forwarded to the specified logon page exception JspException if a JSP exception has occurred public int doEndTag() throws JspException

Is there a valid user logged onboolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered exception JspException if a JSP exception has occurred public int doStartTag() throws JspException

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

283

return (SKIP_BODY)

2 Open the file apptld in craftWEB-INF and add an entry for the new tag

lttaggtltnamegtcheckLoginltnamegtlttagclassgtcomffictrainingCheckLoginTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggt

3 Make changes to ALL the jsps that wersquove created so far

Add a directive for the apptld

lt taglib uri=WEB-INFapptld prefix=app gt

Place this line of code at the top of each jsp

ltappcheckLogin gt

Deploying the code (Part 2 ndash protecting jsp pages)

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

Result (Part 2 ndash protecting jsp pages)Log into the application then click on the ldquoLog Outrdquo link to make sure that whateversession you have in your browser has been invalidated

284

The screen below makes sure that you have been logged out

In the same page type in the url for the divisionrsquos search pagehttplocalhost8080craftdivSearchjsp

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

285

The checkLogin tag will check to see if the user has logged in or not Since the sessionhas been invalidated the checkLoginTag will perform a forward to the login page

Note Irsquom still working on getting the tag to write an error message similar to what theBaseAction does when it forwards to the login page if the user has not authenticated yet

  • Lesson 1 - ORION webserver configuration
    • Preparation
    • Installation
    • Configuration
    • Review
      • Lesson 2 - VisualAge for JAVAWebSphere Test Environment configuration
        • Installation
        • Configuration
        • Usage
          • Lesson 3 - Servlet primer
            • Basics
            • Your first servlet
            • Deploying the code
              • Lesson 4 - Database Connectivity
                • Preparation
                • Coding
                • Deploying the code
                  • Lesson 5 - ServletDatabase Connectivity
                    • Preparation
                    • Coding
                    • Deploying the code
                      • Lesson 6 - Servlet Redirection
                        • Basics
                        • Preparation
                        • Coding
                        • Deploying the code
                        • Result
                          • Lesson 7 - JavaBeans
                            • Basics
                            • Coding
                            • Deploying the code
                            • Result
                              • Lesson 8 - Object Scope
                                • Basics
                                • Coding
                                • Deploying the code
                                • Result
                                  • Lesson 9 - Java Server Pages (JSP)
                                    • Basics
                                    • Coding
                                    • Deploying the code
                                    • Result
                                      • Lesson 10 - Custom Tags
                                        • Basics
                                          • Anatomy of a Tag
                                          • Custom Tag components
                                            • Coding
                                            • Deploying the code
                                            • Result
                                              • Lesson 11 - Model-View-Controller Design Pattern
                                                • Basics
                                                  • Lesson 12 - Introduction to the Struts Framework
                                                    • Struts Components
                                                    • ldquoI canrsquot find the MVC pattern anywhererdquo
                                                      • Lesson 13 - Installing Struts 11b in VisualAge for Java 40WebSphere Test Environment 353
                                                        • Installation and configuration
                                                        • Installing the sample application
                                                        • Deploying and running the sample application
                                                        • Result
                                                          • Lesson 14 - Installing Struts 11b in ORION
                                                            • Installation and configuration
                                                            • Installing the sample application
                                                            • Deploying and running the sample application
                                                            • Result
                                                              • Lesson 15 - Struts Components
                                                                • Struts Components
                                                                • Tag Libraries
                                                                • Useful Links
                                                                  • Lesson 16 - Building a simple web application using Struts
                                                                    • Basics
                                                                    • Coding
                                                                    • Deploying the code
                                                                    • Result
                                                                      • Lesson 17 ndash Validating form values
                                                                        • Basics
                                                                        • Installation
                                                                        • Coding
                                                                        • Deploying the code
                                                                        • Results
                                                                          • Lesson 18 ndash Nested Beans
                                                                            • Basics
                                                                            • Installation
                                                                            • Coding
                                                                              • CODING PART 1
                                                                              • CODING PART 2
                                                                              • CODING PART 3
                                                                                  • Lesson 19 ndash Creating reusable screen components
                                                                                    • Basics
                                                                                    • Coding (Part 1)
                                                                                    • Deploying the code (Part 1)
                                                                                    • Results (Part 1)
                                                                                    • Coding (Part 2)
                                                                                    • Deploying the code (Part 2)
                                                                                    • Result (Part 2)
                                                                                    • Coding (Part 3)
                                                                                    • Deploying the code (Part 3)
                                                                                    • Result (Part 3)
                                                                                      • Lesson 20 ndash Creating reusable menu components
                                                                                        • Basics
                                                                                        • Installation
                                                                                          • Option 1
                                                                                          • Option 2
                                                                                            • Coding
                                                                                            • Deploying the code
                                                                                            • Result
                                                                                              • Lesson 21 ndash Connection Pooling
                                                                                                • Basics
                                                                                                • Coding
                                                                                                • Deploying the code
                                                                                                • Result
                                                                                                  • Lesson 22 ndash Creating a singleton to maintain the
                                                                                                    • Basics
                                                                                                    • Coding
                                                                                                    • Deploying the code
                                                                                                    • Result
                                                                                                      • Lesson 23 ndash Data Access Objects
                                                                                                        • Basics
                                                                                                        • Coding
                                                                                                        • Deploying the code
                                                                                                        • Result
                                                                                                          • Lesson 24 ndash Business Objects
                                                                                                            • Coding
                                                                                                            • Deploying the code
                                                                                                            • Result
                                                                                                              • Lesson 25 ndash Action subclasses
                                                                                                                • Coding
                                                                                                                • Deploying the code
                                                                                                                • Result
                                                                                                                  • Lesson 26 ndash Exception handling
                                                                                                                    • Basics
                                                                                                                      • Using nested ifrsquos
                                                                                                                      • Using trycatch blocks
                                                                                                                        • Coding (Part 1 ndash programmatic exception handlin
                                                                                                                        • Deploying the code (Part 1 ndash programmatic excep
                                                                                                                        • Result (Part 1 ndash programmatic exception handlin
                                                                                                                        • Coding (Part 2 ndash using declarative exception
                                                                                                                        • Deploying the code (Part 2 ndash using declarative
                                                                                                                        • Result (Part 2 ndash using declarative exception
                                                                                                                          • Lesson 27 ndash Creating dynamic forms
                                                                                                                            • Basics
                                                                                                                            • Coding (Part 1 ndash DynaActionForm example)
                                                                                                                            • Deploying the code (Part 1 ndash DynaActionForm exa
                                                                                                                            • Result (Part 1 ndash DynaActionForm example)
                                                                                                                            • Coding (Part 2 ndash DynaValidatorForm example)
                                                                                                                            • Deploying the code (Part 2 ndash DynaValidatorForm
                                                                                                                            • Result (Part 2 ndash DynaValidatorForm example)
                                                                                                                              • Lesson 28 ndash Using tokens
                                                                                                                                • Basics
                                                                                                                                • Coding
                                                                                                                                • Deploying the code
                                                                                                                                • Result
                                                                                                                                  • Lesson 29 ndash Implementing security in Struts
                                                                                                                                    • Basics
                                                                                                                                    • Coding (Part 1 ndash protecting do classes)
                                                                                                                                    • Deploying the code (Part 1 ndash protecting do cl
                                                                                                                                    • Result (Part 1 ndash protecting do classes)
                                                                                                                                    • Coding (Part 2 ndash protecting jsp pages)
                                                                                                                                    • Deploying the code (Part 2 ndash protecting jsp pag
                                                                                                                                    • Result (Part 2 ndash protecting jsp pages)

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

5

Lesson 1 - ORION webserver configurationThis document lists the steps to install the ORION webserver on your workstation (andrun it of course) I picked ORION since Irsquom more familiar with it than Tomcat or Resinetc The entire thing should take about an hour to accomplish I can either walk youthrough the installation or you can just follow these steps yourself and if I didnrsquot missanything have it running in no time Once yoursquore familiar with it I can then walk youthrough the configuration of WebSphere Test Environment in VAJava and we can talkabout the differences between WTE and the rest of the J2EE webappservers

PreparationThe following steps will install the java toolkit in your workstation Yoursquoll need this tocompile andor run stand-alone java programs outside of VAJava

1 Download the java sdk from httpjavasuncomj2se13downloadhtml (selectWindows (all languages) and click the download link under the SDK column)

2 Accept the license and proceed with the download (place it in your favorite folder)3 Run the downloaded executable file j2sdk-1_3_1_03-winexe and unzip it in E (it

should unzip the contents under ejdk131_03)4 Go to your desktop and right-click on My Computer and bring up the properties5 Click on the Environment tab6 Enter the following

Variable JAVA_HOMEValue ejdk131_03

7 Click on OK

Installation1 Download ORION from httpwwworionservercom

on the left-side nav of the screen click on Stable binaries under the Downloadsection

save the file to your favorite local directory

2 Open the downloaded file orion152zip and extract the contents to eorion (thisfolder will be automatically created when you check the ldquoUse foldersrdquo option inWinZip)

3 This is from the orion docscopy toolsjar from ejdk131_03lib into eorion tomake jsprsquos work

6

ConfigurationCreate a J2EE compliant directory structure To do this follow the steps

1 Create the following directory Eservletscraft This will be your applicationrsquos rootdirectory

2 Under the craft folder create the following directory structure

craft|___images|___WEB-INF

|___classes|___libFolder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

3 Create a file named webxml and save it in eservletscraftWEB-INF then pastethe following code

ltxml version=10gtltDOCTYPE web-app PUBLIC -Sun Microsystems IncDTD Web Application22EN httpjavasuncomdtdweb-app_2_2dtdgt

ltweb-appgt

ltweb-appgt

This file contains the applicationrsquos configuration information Right now itrsquos empty but thewebserver still expects to find this file or else it wonrsquot startup the application

4 To let ORION know about your new application (the one you just created above) youneed to enter some stuff in the ORION xml files To do this

go to EORIONCONFIG open applicationxml using a text editor enter the following information (in bold) right after the tag ltweb-module

id=rdquodefaultWebApprdquo path=rdquodefault-web-apprdquo gt

lt-- --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

7

ltweb-module id=rdquoCRAFTrdquo path=rdquoEservletscraftrdquo gtlt-- --gtltpersistence path=rdquopersistencerdquo gt

save and exit the file open default-web-sitexml again using a text editor enter the following information (in bold)

lt-- The default web-app for this site bound to the root --gtltdefault-web-app application=rdquodefaultrdquo name=rdquodefaultWebApprdquo gt

lt-- --gtlt-- get name from applicationxml ltweb-module id=rdquothis will be the namerdquopath=rdquocrdquogt --gtltweb-app application=rdquodefaultrdquo name=rdquoCRAFTrdquo root=rdquocraftrdquo gt

lt-- --gt

saveexit the file

5 Go to the command prompt and go to eorion

6 Start the server by typing java -jar orionjar on the command line

7 If everything was setup properly you should see the message Orion152 initialized

8 Create an html file named pagehtml and save it in Eservletscraft then pastethe following code

lthtmlgtltheadgt ltheadgtltbodygtltdiv align=centergtlth1gtHELLO WORLDlth1gtltdivgtltbodygtlthtmlgt

9 To test your webserver

bring up a browser (IE or NS) type in httplocalhostcraftpagehtml You should see proverbial HELLO

WORLD on your browser

8

(Hint While Windows itself is not case-sensitive unlike AIX the URL should thatyou type in the browserrsquos address line should match the entry in the xml file)

10 Congratulations yoursquore a survivor

ReviewThe following information is worth rememberingDIRECTORY STRUCTURE

craft|___images|___WEB-INF

|___classes|___lib

Folder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

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

9

Lesson 2 - VisualAge for JAVAWebSphere TestEnvironment configurationThis is a minimalist instruction on how to configure your WebSphere Test Environment(WTE) in VAJava to start serving web applications It walks you through the steps increating a CRAFT application and testing the setup to make sure that is runs It shouldtake an hour (or more) to complete this exercise

InstallationInstall VAJava 40 (easy to say huh) You should already have it in your workstationCheck that the WebSphere Test environment is installed in VAJ By selectingWorkspaceToolsWebSphere Test Environment VAJ should tell you if itrsquos there or not If not

Select FileQuick StartSelect FeaturesAdd FeatureSelect WebSphere Test Environment 353 from the list and click OK

Configuration1 Create the following directory structure under eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_host (whew)

craft|_images|_WEB-INF

|_classes

Folder Descriptions

craft - root directorycontains html and jsp filesimages - contains image filesWEB-INF - is not automatically recognized by WebSphere but wersquoll create this so wecan create a pseudo-J2EE directory structureclasses - again not automatically recognized by WebSphere wersquoll create this for thesame reason as the previous folder

2 Create a file craftwebapp and put the following text in the file

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegt

10

ltservletgtltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtinvokerltnamegtltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegt

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

11

ltvaluegtindexhtmlltvaluegtltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

3 To let WTE know about your new application go to the directory eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmentproperties and open the file defaultservlet_engine using a text editorAdd the following text

Look for this tag ltwebsphere-servlet-host name=rdquodefault_hostrdquogt and paste the followingtext right after it

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

UsageThis section will walk you through how to test if your WTE configuration is correctly setup1 Create a file named indexhtml and save it in eappsprogram

filesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft then paste the following code

ltHTMLgtltHEADgtltMETA NAME=GENERATOR Content=NetObjects ScriptBuilder 30gtltTITLEgtWebSphere Test Environment Index PageltTITLEgtltHEADgtltBODYgtlth1gtThis is the index page for the WebSphere Test Environmentlth1gtltBODYgtltHTMLgt

2 Bring up VAJava

3 Select WorkspaceToolsWebSphere Test Environment

4 Click on Start Servlet Engine

12

5 When the message at the lower left says ldquoServlet engine is startedrdquo bring up abrowser

6 Type in this URL httplocalhost8080craft

If the installation is successful yoursquoll get the following message on your browser This is the index page for the WebSphere Test Environmentif not wersquoll take a look at your problem

7 Thatrsquos itnow on to greater 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

13

Lesson 3 - Servlet primerHerersquos the next installment on the web-application development crash-course You willcreate your first servlet which will hopefully give you a basic understanding of whatservlets are and how they work I gave examples on how to deploy the code both in VAJWTE and in Orion so you can continuously compare the two web environments This willgo on for the next few lessons and then when we get to Struts wersquoll just retain theWebSphere Test Environment which is where we should be developing our codes

BasicsServlet

body of java code that extends a java-enabled serverrsquos functionality listens to requests and usually sends back a response to the client Can also pass

processing on to other servlets does not have a main() method so it cannot run outside of the servlet container to create a servlet we generally extend the class HttpServlet which is a subclass of

GenericServlet HttpServlet makes use of the HTTP protocol

Servlet life-cycle

An HttpServlet contains the following methods

init() doGet()doPost() destroy()

When a servlet is first invoked the servlet container calls the servletrsquos init() method thenit calls either the doGet() or doPost() method

For subsequent requests only the doGet() or doPost() method is called A separatethread is created for every doGet()doPost() invocation so different requests will not runinto each other We place the majority of our code in either of these methods

When the servlet container is shutdown it calls the servletrsquos destroy() method

RequestResponse paradigm

Uses HTTP which is a stateless protocol

In itrsquos simplest form

client sends a request and servlet receives request (and response) object which mayhave objects attached to it (parameters or attributes RemoteUser etc)

14

servlet processes the request (access a db contruct an html response forward toanother servlet etc)

client receives some form of response from the servlet and renders the output to the browser

Your first servletIn VAJ

1 Create a project named TRAINING2 Create a package named comffictraining3 Create a class named HelloWorldServlet4 Add these codes to HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

Code Walkthrough

1 To make HelloWorldServlet a servlet it needs to extend HttpServlet

public class HelloWorldServlet extends HttpServlet

2 We will then need to implement one of the following methods

doGet()doPost()

In this example we implemented the doGet() method

public void doGet(HttpServletRequest 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

15

3 Inside the doGet()

we set the content type for the response to texthtml since we intend to send back anhtml response

responsesetContentType(ldquotexthtmlrdquo)

4 We then retrieve the PrintWriter from the response so we can start writing our outputto it

PrintWriter out = responsegetWriter()

5 Lastly we start writing our output

outprintln(ldquolth1gtHello worldlth1gtrdquo)

After executing the last line of code the servlet returns control back to the web containerwhich sends the response back to the client Since we added stuff in the response theclientrsquos browser will attempt to render it

Deploying the codeVAJava (WebSphere Test Environment)

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (this can be the last entry just beforethe

ltwebappgt tag)

ltservletgtltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

Orion

16

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgtltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in ldquoHello Worldrdquo being displayed on your browser

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

17

Lesson 4 - Database ConnectivityBefore we move on to other web components we need to briefly go through the topic onconnecting to a database and retrieving information from the tables This will make thenext few topics a lot more interesting since you will be displaying data on the browser thatwere retrieved straight off of the db instead of flooding your servlet with ldquoset-this set-thatvaluerdquo lines of codes

After going through this exercise it will become more obvious that this is not the real-world way of creating and maintaining connections to a database Creating a connectionfor each sql to be executed is a pretty expensive operation In later exercises we willexplore how to create a pool of connections using DataSource and the methods withwhich this datasource is maintained and accessed (the FFIC way of course)This section discusses the java code required to connect to a database and execute sqlto retrieve data

Preparation1 You should have the IOU database information entered in your UDB-client with the

following details

DB Alias = IOUODBC entry = IOU (not really needed in this exercise but check it anyway)

2 We will be using the DB2 driver to create the connection to our database If youhavenrsquot done so import the db2javazip file into your VAJ ide

create a DB2 DRIVER project import db2javazip from EAPPSSQLLIBjava into your newly created project

using the following option ldquoimport as a Jar filerdquo

3 For ORION copy the file db2javazip to EservletsORIONcraftWEB-INFliband rename it to db2javajar

CodingIn your TRAINING project create a class JDBCSample in the comffictraining packageand paste the following code in it

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcapp

18

import javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(ldquoDivision ldquo + ldquoCoderdquo + ldquo ldquo + ldquoDescriptionrdquo) while (rsnext())

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

19

String s = rsgetString(1)String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

CODE WALKTHROUGH

1 We need to import the following packages so the program can load the necessaryjdbc classesdrivers

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

2 We define variables for the sql to execute and the useridpassword needed to accessthe database Obviously you must change the userpassword if you have a differentone We also specify here the driver that we will use to create a connection to thedatabase (DB2 in this case)

String query = ldquoSELECT FROM IOUDIVISIONrdquoConnection conn = nullStatement stmt = nullString user = ldquoiccw0t00rdquoString password = ldquoiccw0t00rdquoString driver = ldquoCOMibmdb2jdbcappDB2Driverrdquo

3 This trycatch block attempts to load the database driver and create a connection

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)

20

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)

4 When a connection is successfully created the next trycatch block creates aStatement from the connection and executes the sql that we defined earlier

try 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 )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

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 JDBCSample class and select Run

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

21

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 JDBCSample 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

The output should look similar to the following

loading driverconnectingtojdbcdb2IOUconnectedDivision Code Description1 CID Involuntary 2 CID Voluntary 3 PID 4 CID Specialty 10 National Accounts 11 Jefferson Insurance 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

22

END

NEXTLetrsquos try what we just learned using our servlet example

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

23

Lesson 5 - ServletDatabase Connectivity From the last two lessons you learned to a) construct a simple servlet and b) create ajava program that retrieves data from a database Now we will combine the two andcome up with a servlet that accesses the database and displays the result (ResultSet) ona browser

PreparationRemember your two previous programs If not here are the source codes

HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServletpublic void doGet(HttpServletRequest request

HttpServletResponse response)throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

JDBCSample

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

24

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try 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 )

stmtclose()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

25

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

Before you proceed briefly review how each of the programs work so it will be mucheasier to understand the codes belowthatrsquos all

CodingWith a little tweak (additional codes) the code below shows a combined version of thetwo programs we previously created You can cut and paste it in your HelloWorldServletin VAJ

The blue portion is the HelloWorldServlet while the red portion shows theJDBCSample

You will also notice that there are codes in green These lines of codes were added toaccomodate the codes for JDBCSample and to properly display the output to thebrowser

import javaioimport javaxservletimport javaxservlethttp

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

public class HelloWorldServlet extends HttpServletString query = SELECT FROM IOUDIVISIONConnection conn = nullStatement stmt = nullString user = iccw0t00String password = iccw0t00String driver = COMibmdb2jdbcappDB2Driver

HelloWorldServlet constructor comment

26

public HelloWorldServlet()

super()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() outprintln(lth1gtHello worldlth1gt)

try

stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(Division Code + + Description) outprintln(lth2gtDivisionlth2gt) outprintln(lth3gtCode Descriptionlth3gt)

while (rsnext()) String s = rsgetString(1)

String ln = rsgetString(2) Systemoutprintln(s + + ln )

outprintln(lth3gt + s +ampnbspampnbspampnbspampnbspampnbspampnbspampnbsp + ln + lth3gt)

stmtclose()

conclose()

catch(SQLException ex) Systemerrprintln(SQLException + exgetMessage())

Insert the methods description here Creation date (42402 22142 PM) public void init()

try Systemoutprintln(loading driver) ClassforName(driver) String url = jdbcdb2IOU Systemoutprintln(connectingto + url) conn = DriverManagergetConnection(urluserpassword) Systemoutprintln(connected)

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

27

try catch(ClassNotFoundException ex) Systemoutprintln(Couldnt load jdbc driver) Systemoutprintln(ex) catch(SQLException ex) Systemoutprintln(Database Problem) Systemoutprintln(ex) catch(Exception ex) Systemoutprintln(Some other problem) Systemoutprintln(ex)

CODE WALKTHROUGH

Irsquove pretty much gone through the codes line by line in the previous lessons What needs to be mentioned here is that a method called init() was added and the codesthat load the DB2 driver and create the connection were added here

Insert the methodrsquos description hereCreation date (42402 22142 PM) public void init()

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

28

Systemoutprintln(ex)

When a servlet starts up the first thing it looks for is an init() method and it executes thismethod once within itrsquos lifetime It is good practice to place initialization stuff in thismethod especially when we only need to run these once A good example is creating aconnection to the database and this is just what we did with this exampleNote As with the init() method a servlet also has a destroy() method which is calledwhen it shuts down

Deploying the codeDeploying the code to VAJ and ORION is the same as in the servlet lesson I listed ithere again just in case you donrsquot have that lesson anymore

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (can be the last entry just before the ltwebappgt tag)

ltservletgt

ltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

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

29

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in the following output on your browser

30

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

31

Lesson 6 - Servlet RedirectionThis lesson briefly covers one of the more important features of servlets which isforwarding or redirecting In simple terms redirection is passing control to another entitywhich can be a servlet html or jsp at the same logical level It works pretty much like anxctl in CICS with some differences There are two types of redirection client-side andserver-side and these are described in the following section

BasicsClient-side redirection

The redirection happens at the client-side and the URL on the browserrsquos address linechanges to the URL that was sent to it User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and sends a message

(redirect) to the browser containing a URL which the browser will load The browser receives the redirect from the servlet and loads the URL that was sent

to it

Note The URL in the redirect can be another servlet html or a jsp file

To illustrate this process

BROWSER==gtservlet==gtBROWSER==gtresult(jsphtmlservlet)

Client-side redirection is useful when after a servlet processes you want to navigate theuser to another page where even if he reloads that result page will not cause the servletto re-execute In other words the user is navigated to a safe place where he canrsquot hurthimself or the application

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoresponsesendRedirect(url)

if you want to retrieve the original URL to redirect the servlet to itself do this

String url = requestgetRequestURI()responsesendRedirect(url)

Note the getRequestURI() method leaves out the parameters if any that wereincluded in the original URL You can use the requestgetParameter() to retrieve theparameters and attach them to the url

32

Server-side redirection

The redirection happens only at the server-side and the browser does not know anythingabout it The URL on the browserrsquos address line does not change

User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and forwards itrsquos output to

another servlet jsp or html The receiving sevlet jsp or html renders the output to the browser

To illustrate this process

BROWSER==gtservlet==gtresult(jsphtmlservlet)

Server-side redirection is used to combine several operations to make them appear asone without involving the clientrsquos browser This cuts down traffic between the server andthe browser The browser will receive the result only after the last of the processes hasreleased the output to the web container

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

PreparationThis exercise involves server-side redirection The idea is to have one servlet receive therequest from the browser and perform a redirect to another servlet which will retrieve datafrom a db and construct the html output to be rendered on the browserWe will need the HelloWorldServlet servlet for this exercise which will act as the receivingservlet All we need to contruct is the servlet that will forward the processing toHelloWorldServlet

CodingIn VAJ create a new class called ControllerServlet in the package comffictraining andpaste the following code to it

import javaioimport javaxservletimport javaxservlethttp

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

33

public class ControllerServlet extends HttpServletpublic void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionString url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

1 We define ControllerServlet as a servlet by extending HttpServlet

public class ControllerServlet extends HttpServlet

2 These lines construct the URL of the receiving servlet and performs the redirection

String url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtControllerltnamegtltdescriptiongtDB access servletltdescriptiongtltcodegtcomffictrainingControllerServletltcodegtltautostartgttrueltautostartgt

ltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

34

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtControllerltservlet-namegtltservlet-classgt

comffictrainingControllerServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

35

You can verify that the servlet did a server-side redirect if the URL on the browserrsquosaddress line did not change It should still show

httplocalhost8080craftservletController for WTE

or

httplocalhostcraftservletController for ORION

WATCH OUT NEXT FORJAVA BEANS

36

Lesson 7 - JavaBeansUp to this point we have been dealing mostly with webserver configuration andprocedural java codes In this lesson we will start to incorporate object orientation in ourexamples using javabeans

BasicsIn our example programs we created data in our servlet by retrieving information fromthe database and by assigning values to variables There will be times when we want topass this data around and manipulate them before we send them to the browser fordisplay A convenient way of doing this is to encapsulate all these related informationhide them in an object and provide methods to access each value To accomplish thiswe create a java class called javabean or bean that contains only private variables andsettergetter methods for each of these variables For instance we can create a bean called divisionBean and store each row that weretrieve from the database to a divisionBean instance We can then put all these beansinside a collection object that we can pass around and eventually render to the browserSounds confusing Letrsquos do an example then

Coding1 In VAJ create a class called DivisionBean in comffictraining package and paste the

following in it

public class DivisionBean private String divNoprivate String divDesc

public String getDivDesc()return divDescpublic String getdivNo()return divNopublic void setDivDesc(String divDesc)thisdivDesc = divDescpublic void setDivNo(String divNo) thisdivNo = divNo

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

37

2 Open your HelloWorldServlet and make the following changes

Add the following code right after the class declaration

ArrayList divList = new ArrayList()

In the doGet() method

delete the following lines or better yet just comment them out (ie put a beforeeach line)

String s = rsgetString(1)

String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )outprintln(ldquolth3gtrdquo + s + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + ln + ldquolth3gtrdquo)

add the following lines within the while loop

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

after the while loop add the following lines of code

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

Code Walkthrough

DivisionBean

1 We defined the two variables divNo and divDesc as private to prevent them frombeing accessed directly (ie divisionBeandivNo)

private String divNoprivate String divDesc

38

2 We then define getters and setters for the two variables

public String getDivDesc()

return divDesc

public String getdivNo()

return divNo

public void setDivDesc(String divDesc)

thisdivDesc = divDesc

public void setDivNo(String divNo)

thisdivNo = divNo

HelloWorldServlet

1 We defined an Arraylist (called divList) which part of the java collections to containthe instances of the beans that we create

ArrayList divList = new ArrayList()

2 In the while loop we instantiate a new divisionBean and set itrsquos variables to thevalues that we retrieve from the db The we add that instance to divList

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

3 After wersquove gone through the entire resultset we loop through divList and create anhtml output for each instance of the bean in the ArrayList The code provided here ispretty much boiler plate code

retrieve an interator from divList (all collections have an interator)

Iterator iterator = divListiterator()

the interator has methods that loop through the ArrayList object (hasNext()) andto retrieve each item (next())

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

39

while (iteratorhasNext())

when an item is retrieved it has to be cast back to the original object In thiscase we cast the item back to DivisionBean

DivisionBean divbean = (DivisionBean) iteratornext() outprintln(ldquolth3gtrdquo +divbeangetDivNo() + ampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +divbeangetDivDesc() + ldquolth3gtrdquo)

Enhancement idea

You may ask ldquoWhy put more code that does the same thing as the originalrdquo

The answer is that creating beans and storing them in collections (or even if you justhave a single bean) enables you to attach this object to for example the request object(ie requestsetAttribute(ldquodivisionListrdquodivList)) and perform a forward to another servletthat contains code (such as the while loop with the iterator) that performs the creation ofthe output to the browser In this case the components can be further divided into thefollowing

ControllerServlet - receives the request from the browser and forwards it toHelloWorldServlet

HelloWorldServlet - retrieves data from the db stores the results inbeanscollection attaches the collection to the request object then performs aserver-side redirect to another servletjsp which we can call DisplayServletDisplayServlet - retrieves the collection from the request object and builds thehtml output while iterating through the collection

This approach enables you as the programmer to assign specific tasks to eachcomponent and keep them loosely coupled so that you can easily change onecomponent without making massive changes to the rest of your application As anexample you can change HelloWorldServlet to access another database (other thanDB2) without affecting the two other servlets in the chain

Deploying the codeVAJ

1 Bring up WTE and start the servlet engine

2 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

40

ORION

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Start ORION (eORIONjava -jar orionjar)

3 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

41

42

Lesson 8 - Object ScopeThis lesson is a sidetrip to learning the concept of object scope We need to cover thisimportant topic before we head on to JSPrsquos (are we there yet)

BasicsIn the previous lesson we learned to create javabeans and put them in a collection(called divList) to be processed by another set of codes within the same servlet We alsotoyed with the idea of creating another servlet (DisplayServlet) that will construct the htmloutput from this collection Since we want to pass the collection from HelloWorldServletto DisplayServlet we need to somehow associate the collection object with a particularscope When we perform a server-side redirect the request and response objects arepassed as arguments in the forward method Before we actually forward the process toanother servlet we make sure that we associate the collection object to the requestobject so that the receiving servlet can access that collection This is an example of anobject scope and in this instance we defined the collection to be in the request scope

A simple definition of Object Scope is the level of availabilityvisibility of an object withinthe application

It can be any of the following

page - object is visible in the page that created itrequest - object is visible in the request to which is belongssession - object is visible in the same session where it was created application - object is visible within the entire application Any servlet regardless of

what session created them can access the object in this scope

To associate an object to a particular scope we use the setAttribute() method If we want to say make the divList collection available to a userrsquos session we use thefollowing code

HttpSession session = requestgetSession(true)sessionsetAttribute(ldquodivListrdquodivList)

so long as the session still exists we can extract that collection at any point within theapplication with the following code

HttpSession session = requestgetSession(true)ArrayList divList = (ArrayList) sessiongetAttribute(ldquodivListrdquo)

Note We have to cast the collection back to itrsquos original form which is an ArrayList

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

43

Letrsquos create the DisplayServlet that we discussed in the previous lesson

1 Create a class called DisplayServlet in your TRAINING project in the packagecomffictraining and paste the following

import javaioimport javaxservletimport javaxservlethttp

import javautilpublic class DisplayServlet extends HttpServlet

ArrayList divList = new ArrayList()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionresponsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCodeDescriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() +ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

2 Open HelloWorldServlet and make the following changes

comment out the following lines of code in the doGet() method

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCode Descriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +

44

divbeangetDivDesc() + ldquolth3gtrdquo)

add the following lines of code after the stmtclose() line

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

Display Servlet

1 We define DisplayServlet by extending HttpServlet

public class DisplayServlet extends HttpServlet

3 Define an ArrayList to contain the collection that this servlet will receive fromHelloWorldServlet

ArrayList divList = new ArrayList()

4 Set the content type and get the output writer from the response so we can startwriting output data to it

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()

5 Retrieve the divList collection from the request object and cast it back to an ArrayList

divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)

6 Create the html output while iterating through the collection

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

HelloWorldServlet

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

45

1 The lines that we removed from this servlet were transferred to DisplayServlet

2 In the lines that we added we associate the divList collection with the request objectand then do a server-side redirect to DisplayServlet

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquo

RequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtDisplayltnamegtltdescriptiongtDisplay Outputltdescriptiongt

ltcodegtcomffictrainingDisplayServletltcodegtltautostartgttrueltautostartgtltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtDisplayltservlet-namegtltservlet-classgt

comffictrainingDisplayServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

46

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

47

Lesson 9 - Java Server Pages (JSP)BasicsIn the previous lessons we had been constructing our html response within the servletitself It works well with simple html outputs but later on as your webpages get morecomplicated you will find (or you may already have) that this will not work for real-worlddevelopment Java Server Pages (JSP) technology was introduced to make life easier forus programmers and for web designers How If yoursquore familiar with HTML JSP isbasically an html page with little (thatrsquos the plan) java code You get to construct your htmlpage as you normally would and start putting in java logic to a) iterate through acollection of beans b) to include output from another jsp and more To create a jsp filefrom a static html file simply change the filersquos extension from html to jsp and yoursquoreready to go But wait therersquos moreBefore we move on also remember that a jsp is first converted and compiled into aservlet by the web container before it is executed so it will have a similar life cycle as thatof a servlet Inside the jsp file we can put java codes to create dynamic output on thebrowser We accomplish this by using scriptlets expressions declarations and directiveswhich are described below

Scriptlet lt

Scriptlets are regular java codes that are automatically executed by the jsp containerwhen the jsp is invoked so they should be syntactically correct

lt String i = ldquofoordquoSystemoutprintln(i)

gt

Expression lt=

Expressions evaluate to a value that is directly displayed on the browserlt= i gt

The example is converted to outprintln(i) by the jsp container and the value of ldquoirdquo isdisplayed on the browser

Declarations lt

Declarations are java codes that are not automatically executed by the jsp container butmay be invoked if you call it from a scriptlet

lt static printName (String name) Systemoutprintln(name)

gt

48

You can invoke this by writing a scriptlet such as

lt printName(ldquoMyNamerdquo) gt

Directives lt

Directives desribe the necessary components of a jsp

lt page import=rdquojavautilcomffictrainingrdquo gt ==gt imports necessary packageslt taglib uri=rdquobeanrdquo prefix=rdquobeanrdquo gt ==gt declares a taglib referencelt include file=rdquoextraInfojsprdquo gt ==gt includes output from another jsp file

Coding

Suppose the web designer (if there is one) hands you this html file (DisplayDivhtml) lthtmlgtltbodygtlttable border=1gt

lttr align=left gtltthgtDivision IDltthgtltthgtDescriptionltthgtlttrgtlttr align=leftgtlttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgtlttdgt2lttdgtlttdgtCID Voluntarylttdgtlttrgt

lttablegtltbodygtlthtmlgt

The browser output looks like this

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

49

So you the java programmer need to convert this layout to a dynamically generated htmlfile

KNOWN

The data will come from the IOUDIVISION table You already have the servlets (ControllerServlet and HelloWorldServlet) necessary to

perform data retrieval from the db You have a DisplayServlet servlet that creates html output but you want to use a jsp

since you already have the html code and you just need to insert the necessary javacodes to render the dynamic output correctly

HINT We created javabeans (DivisionBean instances) containing Division information and

put them in a collection (divList) that is associated with the request object In our jsp file we can retrieve this collection and iterate through them pretty much the

same way we did with DisplayServlet So most of the codes that we have inDisplayServlet can be reused in the jsp file

Code Walkthrough

1 If you saved the above code in DisplayDivhtml simply rename it to DisplayDivjsp tomake it a jsp file

2 At the topmost portion paste the following code

lt page import=rdquojavautilcomffictrainingrdquo gt

This tells the jsp page that your scriptlets will be looking for necessary classes in thesepackages

3 To display the division code and description we have to insert codes that iteratethrough the collection and render them inside the table

Just after the table header definition (The ones with the ltthgt ltthgt tags) make thefollowing changes

delete the following lines of codes since these are just representations of what thedynamic portion of the page are

lttr align=leftgt

lttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgt

lttdgt2lttdgt

50

lttdgtCID Voluntarylttdgtlttrgt

insert the following codes

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()gt

Notice that this is strikingly similar to the code in DisplayServlet Thatrsquos because we justcut and paste it from there Even though the loop is not yet complete we terminated these lines of code with a ldquogtrdquo because we need to pasteregular html tags or non-java codes right after it

4 Once the above code starts iterating through the collection we need additional codesto render the details so paste the following code right after it

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

Here we used expressions to execute the ldquogetrdquo methods of the DivisionBean instance toretrieve the division code and description

5 Now this is where most beginners get bit We need to properly terminate the ldquowhilerdquoloop that we started in the previous steps To do this paste the following code rightafter the previous step

lt End whilegt

The completed code looks like the following

lt page import=rdquojavautilcomffictrainingrdquo gtlthtmlgtltbodygtlttable border=1gt

lttr align=leftgtltthgtDivision IDltthgtltthgtDescriptionltthgt

lttrgt

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

51

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()

gtlttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End whilegt

lttablegtltbodygtlthtmlgt

HelloWorldServlet

Open HelloWorldServlet and make the following changes

1 Remove the following line of code

String url = ldquoservletDisplayrdquo

2 Replace it with the following line of code to forward the process to DisplayDivjspinstead of DisplayServlet

String url = ldquoDisplayDivjsprdquo

Deploying the codeVAJ

1 Be sure to save DisplayDivjsp in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

52

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Save the DisplayDivjsp file in eservletscraft3 Start ORION (eORIONjava -jar orionjar)4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

53

Lesson 10 - Custom TagsBasicsIn Lesson 9 you learned how to create a JSP to handle content rendition in place of aservlet Wersquove seen how the same codes that we used in the servlet can be re-appliedinside the JSP using scriptlets expressions declarations and directives Again as yourJSPs get more complicated you will want to reduce the amount of java codes in themespecially codes or logic that are candidates for re-use in other JSPs In our exampleprogram if you want the logic that displays the Division information in more than oneJSPs you may want to put that body of code in a central place where you can just call itfrom different JSPs Otherwise you will end up copyingpasting the same codes in everyJSP that needs these codes

Starting with JSP 11 a feature was introduced wherein java codes can be encapsulatedand represented on the JSP using custom tags Custom tags are not unlike HTML tags(ie lthtmlgt ltformgt lttablegt etc) except that we provide the logic that makes the tagswork An example is to replace the scriptlets in your JSP with one tag such asltapplistDivision gt and this will take care of displaying the list of division codes anddescriptions JSP 12 introduced more enhancements to the custom tag feature such asIterationTag but we wonrsquot cover it here since FFIC still uses JSP 11 in WebSphere

Anatomy of a Tag

ltmytaggtvalueltmytaggt

ltmytaggt - opening tagvalue - body of the tagltmytaggt - closing tag

Custom Tag components

1 Developer-provided class that extends the classjavaxservletjsptagextTagSupport TagSupport is a helper class that implementsthe Tag interface When you write your custom tag you will need to implement atleast one of the two most used methods

doStartTag()

triggered when the opening tag is encountered return SKIP_BODY if you donrsquot want to evaluate the body of the tag return EVAL_PAGE_INCLUDE to evaluate the body of the tag

doEndTag()

triggered when the closing tag is encountered return EVAL_PAGE to continue processing the rest of the JSP

54

return SKIP_PAGE to halt processing of the JSP

2 TagLib Descriptor An XML file that describes the custom tag and the class thatimplements the logic

Example

You can save this in a file named apptldltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomfficexamplestrutsDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

3 WEBXML appWEBAPP entry ndash describes the location of your taglib descriptorand assigns a URI to be used in your JSP

Example

lttaglibgtlttaglib-urigtcraftlttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 JSP Directive ltndash tells your JSP that you will be using a custom tag what itrsquos URIis and how you will reference it in your page (using a prefix)

Example

Place this at the top of your JSP

lttaglib uri=WEB-INFapptld prefix=app gt

With these components in place you can start using custom tags in your JSPs

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

55

CodingNow letrsquos create a custom tag out of the scriptlets that we have in DisplayDivjsp

1 In VAJ in the package comffictraining create a class named DivisionTag andpaste the following codes

Insert the typersquos description here Creation date (1802 11910 PM) author Administrator

import javautilimport javaxservletjsptagextTagSupportimport javaxservletjsp

public class DivisionTag extends TagSupportHere we used the doEndTag() method to start evaluating after the body In thiscase there is no bodypublic int doEndTag() throws JspException We retrieve the collection (divList) from the request that is forwarded byHelloWorldServletArrayList divList = (ArrayList)pageContextgetRequest()getAttribute(ldquodivListrdquo)

We then iterate through the collection as we did before and write the output tothe outputstream of the pagetry Iterator iterator = divListiterator()

while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()pageContextgetOut()print(ldquolttr align=leftgtlttdgtrdquo + divbeangetDivNo() +ldquolttdgtlttdgtrdquo + divbeangetDivDesc() + ldquolttdgtlttrgtrdquo)

pageContextgetOut()print(ldquolth3gthelplth3gtrdquo) catch (Exception e) throw new JspException(etoString())

We return eval page to tell the JSP to continue processing the rest of thepage if anyreturn EVAL_PAGE

2 We then need to create a taglib descriptor for this new class Create a file namedapptld and paste the following code

56

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomffictrainingDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

lttaglibgt

3 We then need to tell the webserver about this taglib descriptor In the webxml file(only for Orion) lttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 Copy the DisplayDivjsp to a new JSP file named DisplayDivTagjsp and make thefollowing changes

Remove the following lines of code

lt page import=rdquojavautilcomffictrainingrdquo gt

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext())

DivisionBean divBean = (DivisionBean) inext()gt

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End while(ihasNext())

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

57

gt

At the top of the jsp add the following

lttaglib uri=WEB-INFapptld prefix=app gt

This tells the JSP to use apptld and that we will reference this as app allthroughout the page

Just below the table heading tags add the following line of code

ltapplistDivision gt

This invokes the DivisionTag class and starts writing the output to the page

5 Finally open HelloWorldServlet and make the following changes

In the doGet() method remove the line

String url = ldquoDisplayDivjsprdquo

Replace it with

String url = ldquoDisplayDivTagjsprdquo

Deploying the codeVAJ

1 Save the DisplayDivTagjsp in the Javaideproject resourcesIBM WebSphereTestEnvironmenthostsdefault_hostcraft folder

2 Bring up WebSphere Test Enviroment and start the servlet engine

3 Bring up a browser and type the following in the address line

httplocalhost8080craftservletController

ORION

1 Export HelloWorldServlet and DivisionTag to eservletscraftWEB-INFclasses

2 Save DisplayDivTagjsp in eservletscraft

3 Start Orion (eORIONjava ndashjar orionjar)

4 Bring up a browser and type the following in the address line

httplocalhostcraftservletController

58

Result

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

59

Lesson 11 - Model-View-Controller Design PatternBasicsIf you got this far and have understood the previous lessons then you can pat yourself onthe shoulder and say that yoursquore ready to put things together Actually you already haveWe just need to give what yoursquove been doing these past few lessons a catchy name andthat too is already done Over the years as java technology developed design patternsstarted to emerge As these patterns are recognized the most effective ones enduredand took on lives of their own One of these patterns which according to old-timers wasused to program Smalltalk applications is called Model-View-Controller or MVC for shortMVC is also called JSP Model 2 architecture Is there a Model 1 Yes there is and wersquollbriefly discuss the differences between the two models

JSP Model 1

This architecture puts the responsibility of acting on a user input accessing a db andmaintaining application state solely on a single JSP This may do for small applicationsbut not for complex ones The programmer will end up flooding the JSP with tons andtons of scriptlets and other java codes that should logically reside somewhere elseMoreover it is very difficult to coordinate the actions of all JSPs within the applicationsince they are not designed to communicate with each otherBelow is a ldquoreusedrdquo diagram of a JSP Model 1 architecture

JSP Model 2 (MVC)

This architecture extends the Model 1 concept by separating the content rendition (View)function from the application state (Model) and then adding a Controller that conducts theflow of processes within the application This provides for a clean separation ofresponsibilities between each component which results in a clearer definition of roles forweb designers and java programmers

60

Here is another ldquoreusedrdquo diagram and this time of a JSP Model 2 architecture

MVC is composed of obviously a model a view and a controller each of which havespecific functions which are described as follows

Model - represents the state of the application at any given point in time

View - renders the state of the application to the user It also receives user input andsend it to the controller for proper disposition

Controller - acts on a user input determines what action needs to be done delegatesthe action to the required business logic and invokes the Model to change itrsquos state asnecessary

There is no exercise for this lesson I thought Irsquod give you a break before we proceed withthe next one Think of this as the ldquocalm before the stormrdquoHowever letrsquos go through what yoursquove put together so far and try to match theservletsjsp against the MVC components

ControllerServlet (controller) - this contains the beginnings of a controller servlet Bytyping in the URL for this servlet on the browserrsquos address line we are asking it toperform a service for us Inside itrsquos doGet() method it knows that it needs to delegate thetask to HelloWorldServlet which performs the db access and creation of javabeans

HelloWorldServlet (model) - creates and maintains the Model for this little webapplication by storing the data in javabeanscollection It then notifies the View that theModel has changed and that it needs to render the new state

DisplayDivjsp (view) - this jsp page does not know what is happening inside theapplication All it knows is that it gets a notification from the Model that itrsquos state haschanged and that the View needs to re-render it

There we have a mini-MVC application running in our web container Of course it takesmore than a couple of servlets and a jsp to create a real-world web application and thatrsquos

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

61

what we aim to do in the next lessons Keeping this design pattern in mind we are thenready to make a quantum leap to using a framework called STRUTS that implementsthis design pattern I will save the discussion on STRUTS for the next lesson All youneed to know at this point is that STRUTS solves most of the problems (or I should saychallenges) that you will encounter when you try to build your own MVC applicationframework

6

Lesson 12 - Introduction to the Struts FrameworkApplications are generally composed of two major components business-specificcomponents and application services As an application programmer your focus tends tobe more on coding business components rather than application services since thedevelopment life-cycle is really all about gathering business requirements and creatingsystem solutions for them You will just want to be able to code your applicationrsquosbusiness functions and tie them together to create an entire process

Waawa

T

If yoursquore familiar or had worked on CICS applications then it will be easier to graspthe concept of frameworks and what they do to speed up application developmentWhen putting together a CICS application yoursquoll typically need the followingcomponents

1 Entries for CICS tables such asFile Control Table (FCT) ndash contains file aliases (tied to physical file names) to beaccessed in the CICS region (QSAM VSAM etc)

Program Control Table (PCT) ndash defines the relationships between programs andthe files they use

Program Properties Table (PPT) ndash defines the program names transaction idsand typeTerminal Control Table (TCT) ndash contains terminal definition that canaccess the CICS region

2 The symbolic and physical maps (mapsets) for the screen definitions3 CICS programs that contain the flow of the application and business logic

functions4 In the CICS startup jcl you need to put information such as load libraries (should

be in the correct order) of your programs

Once you correctly define and build these components CICS has the responsibility oftying these components together and making sure that when a user types aTransaction ID it will invoke the correct program for it and assign the correct files tothe program Unless you have too much time on your hands you do not want to findout how CICS performs these underlying processes to run your programs

2

ith application development using java programmers have had to build both businessnd application service layers for every application that they construct Most of thepplication services are so customized to the business that there is no way to reuse themith another application so programmers tend to solve the same problems over and overgain

he solution Enter frameworks

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

63

A couple of years back some genius named Craig McClanahan thought up a java-basedframework (Struts) using the MVC design pattern that is generic reusable andextensible (and of course free) It provides a lot of the application services needed toglue an application together while still giving application developers a lot of control overthe business-specific codes that they write Struts is an open source product available fordownload from wwwjakartaapachecomstruts It has a fairly big and activedeveloperuser community that can help beginners get up to speed in using Struts andanswer Struts-related questions that may not be mentioned in available documentation

Struts provides the following application services among other things

request routing errormessage handling generating client-side scripts tag libraries jdbc connection pooling xml parsing automatic population of java beans internationalization of prompts and messages validation menus page layouts

Struts ComponentsSTRUTS ESSENTIAL CLASSES

Struts employs what is called in J2EE lingo a Front Controller pattern wherein it has asingle servlet that receives all requests from the browser and forwards the processing tothe appropriate class handler In essence we do not need servlets other than the oneStruts provides We may sometimes need to extend the functionality of that servlet but inmost cases the vanilla version will do Below are the frequently used classes in theStruts framework with short descriptions

ActionServlet ndash This is the only servlet in the framework and itrsquos job is to receiverequests populate appropriate javabeans from the request delegate the process toanother class that contains business logic (Action) and forwards the process to the nextcomponent as defined in the mapping

Action ndash a class that performs a specific business function (can also dispatch to abusiness logic bean) and returns control back to the ActionServlet with correspondinginformation as to what to do next

ActionForm ndash a javabean that holds the state of the application Programmers writebeans that extend this class so that the ActionServlet can recognize it and populate itwith data from incoming requests

64

ActionForward ndash contains information that tells the ActionServlet the next componentthat will handle the current request

ActionMapping - contains information on Action classes ActionForms and resource filepaths It is read by the ActionServlet to determine which Action will process a request

ActionErrors ndash contains ActionError objects that may have been created whileprocessing a request The contents can then be rendered on an html page

ActionMessages ndash similar to ActionErrors Contains ActionMessage objects createdwhile processing a request The contents can also be rendered on an html page

JSP AND TAG LIBRARIES

In addition to the Struts classes the content rendition portion of the framework uses JSPand custom tags

Bean Tags ndash used to createcopy beans or render bean properties on the pageHtml Tags ndash used to render html form tagsLogic Tags ndash used to perform logical operations such as comparison andor to check forpresenceabsence of beans in the pageNested Tags ndash used to render nested bean properties on the pageTemplate Tags ndash used to render a composite of several jsp pages by pulling these insidea pre-defined layout

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

65

ldquoI canrsquot find the MVC pattern anywhererdquoOK so herersquos a diagram of the Struts Framework which shows how each of thepreviously discussed components work together

66

In MVC semantics the Controller would be the ActionServlet the Model is handled byAction and ActionForm classes and the View is handled by JSPs and tag librariesDid I mention that Struts works at the Presentation Layer of the application I guess notThis means that it does a swell job of conducting the process flow of programs thatinteract with the user (browser) but developers (thatrsquos you) will still need to come up withthe business objects and the data layer objects So in a bigger picture herersquos a diagramshowing where Struts lies

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

67

Below are UML representations of the different parts of the Struts framework

Action

68

Form

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

69

Message

70

Forward

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

71

Mapping

72

Config

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

73

DynaForm

74

Sequence Diagram for a request

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

75

76

The next lessons will walk you through the installation of the Struts framework in bothVAJavaWebSphere Test Environment and Orion We will also build a sample applicationthat uses most of the Struts features so you can get acquainted on the differentcomponents of Struts and how it fits into you web environment

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

77

Lesson 13 - Installing Struts 11b in VisualAge forJava 40WebSphere Test Environment 353This lesson walks you through the installation of Struts 11b in the WebSphere TestEnvironment in VisualAge for Java 40 It assumes that you already have VAJ 40installed in your workstation and that you have properly configured it using theinstructions in Lesson 2 To make sure that Struts is correctly configured you will need toinstall and run the sample application provided in this lesson

What is missing from this lesson is the explanation for the sample application codes Mygoal here is for the user to quickly setup the environment to run Struts so we can proceedwith the next lessons that discuss the different parts of Struts in greater detail

Installation and configuration1 In VAJ you will need to have the following projects present in your workspace

Servlet API ClassesJava Class LibrariesIBM WebSphere Test EnvironmentIBM Enterprise Extension LibrariesIBM XML Parser for Java

If any of the above is missing

select FileQuick Start from the menu select FeaturesAdd Features from the popup window and select the project

you need to import to your workspace

2 Downloadinstall the following

Note If you have projects in VAJ with the same name as the ones listed below be sureto version them first Then when importing the new packages make sure you selectoption create newscratch editions of versioned projectspackages

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract Xercesjar and import it in VAJava in the project XERCES

Xalan from httpxmlapacheorgxalan-jindexhtml

the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar and import them in VAJava in the project XALAN

78

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip

OPTIONAL

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and import these files to a COMMONS project in VAJava

OR

Recommended

Open the binary distribution of STRUTS and extract all commons jar files and importthem in the COMMONS project in VAJava

Struts 11b source from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1src

link is jakarta-struts-11-b1-srczip import the entire file to a STRUTS project in VAJava

Important

You will need to make some revisions to the Struts source code or you will get the following error Cannotremove Attribute from request scope in your browser I think this problem only occurs in WebSphere

In VAJ go to the orgapachestrutstaglibhtml package and open the FormTag class

Replace the following lines in the doEndTag() method in the FormTag class

pageContextremoveAttribute(ConstantsBEAN_KEY PageContextREQUEST_SCOPE)

pageContextremoveAttribute(ConstantsFORM_KEY PageContextREQUEST_SCOPE)

with the following

pageContextgetRequest()removeAttribute(ConstantsBEAN_KEY)pageContextgetRequest()removeAttribute(ConstantsFORM_KEY)

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

79

3 Open jakarta-struts-11-b1-srczip and extract the following files to eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF

struts-tld dtd xml

Note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 In the directory eappsprogram filesibmVisualAge for JavaideprojectresourcesIBM WebSphere Test Environmenthostsdefault_hostcraftWEB-INF create a file named struts-configxml file and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoISO-8859-1rdquo gtltDOCTYPE struts-config PUBLIC

ldquo-Apache Software FoundationDTD Struts Configuration 11ENrdquoldquohttpjakartaapacheorgstrutsdtdsstruts-config_1_1dtdrdquogt

ltstruts-configgtltform-beansgtltform-bean name=rdquoempFormrdquo type=rdquocomfficexamplestrutsEmployeeFormrdquo gt ltform-beansgtltaction-mappingsgtltaction path=rdquovalidateEmployeerdquo

type=rdquocomfficexamplestrutsValidateEmployeeActionrdquo name=rdquoempFormrdquo scope=rdquorequestrdquo input=rdquoInputContentjsprdquogt

ltforward name=rdquosuccessrdquo path=rdquoOutputContentjsprdquo gt ltactiongtltaction-mappingsgtltstruts-configgt

2 Open the webxml file and replace the contents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquoldquohttpjavasuncomdtdweb-app_2_3dtdrdquogtltweb-appgt

80

ltweb-appgt

Note This file is basically an empty file but we still need to provide this becausethe ActionServlet still looks for it somehow If it canrsquot find the file it throws aMalformedURLException exception

3 In the same directory create a file named apptld and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogtltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library 11ENrdquoldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogtlttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtdepartmentListltnamegtlttagclassgtcomfficexamplestrutsDepartmentTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaggt

ltnamegtskillsListltnamegtlttagclassgtcomfficexamplestrutsSkillsTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaglibgt

4 In VAJ create a project named STRUTS EXAMPLE Create a file namedApplicationResourcesproperties save it in a temporary folder and paste thecodes below in it Add it to the project that you just created (To do this click on theResources tab then right-click on the STRUTS EXAMPLE project and selectAddResource then look for the ApplicationResourceproperties file you just createdand click OK)

errormissingname=ltligtltfont colors ldquoredrdquogtPlease Enter the first nameltfontgtltligterrormissingdepartment=ltligtltfont colors ldquoredrdquogtPlease pick a departmentnameltfontgtltligterrormissingskills=ltligtltfont colors ldquoredrdquogtPlease select the relevant skillsltfontgtltligtpromptemployeename=ltbgtFirst Name ltbgtpromptemployeedepartment=ltbgtDepartment ltbgtpromptemployeeskills=ltbgtSkills ltbgt

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

81

5 Open the craftwebapp file located in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft and replace the contents with the followingcode

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegtltservletgt

ltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegtltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgtltinit-parametergt ltnamegtapplicationltnamegt

ltvaluegtApplicationResourcesltvaluegt ltinit-parametergt ltinit-parametergt

ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdebugltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdetailltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtvalidateltnamegt ltvaluegttrueltvaluegt

ltinit-parametergtltservletgt

ltservletgtltnamegtinvokerltnamegt

82

ltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegtltvaluegtindexhtmlltvaluegt

ltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

6 In VAJ create a project named STRUTS EXAMPLE and in it create a packagenamed comfficexamplestruts then create a class named EmployeeForm andpaste the following code in

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

83

Insert the typersquos description hereCreation date (1802 10946 PM)author Administrator import orgapachestrutsactionActionFormimport orgapachestrutsvalidatorValidatorForm

public class EmployeeForm extends ActionForm

private String name = ldquordquoprivate String department = ldquordquoprivate String[] skills

EmployeeForm constructor comment public EmployeeForm()

super()

public String getDepartment() return department public String getName() return name public String[] getSkills() return skills public void setDepartment(String department) thisdepartment = department public void setName(String name) thisname = name public void setSkills(String[] skills) thisskills = skills

7 In the same package create a class named DepartmentTag and paste the followingcode

84

Insert the typersquos description hereCreation date (1802 11513 PM)author Administrator

import javautilListimport javautilArrayListimport javaxservletjsptagextTagSupport public class DepartmentTag extends TagSupport

DepartmentTag constructor comment public DepartmentTag()

super()

public int doStartTag() List department = new ArrayList()departmentadd(ldquordquo)departmentadd(ldquoClient Serverrdquo)departmentadd(ldquoLegacyrdquo)departmentadd(ldquoEmerging Techrdquo)departmentadd(ldquoTech Supportrdquo)

pageContextsetAttribute(ldquodepartmentListrdquodepartment)return SKIP_BODY

8 Create a class named SkillsTag and paste the following code

Insert the typersquos description hereCreation date (1802 11910 PM)author Administrator import javautilimport javaxservletjsptagextTagSupport

public class SkillsTag extends TagSupport

SkillsTag constructor comment

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

85

public SkillsTag()

super()public int doStartTag()

List skills = new ArrayList()

skillsadd(ldquoEJBrdquo)skillsadd(ldquoJava Mailrdquo)skillsadd(ldquoJSPrdquo)skillsadd(ldquoHTMLrdquo)skillsadd(ldquoCOBOLrdquo)skillsadd(ldquoCICSrdquo)skillsadd(ldquoCrdquo)

pageContextsetAttribute(ldquoskillsListrdquoskills)return SKIP_BODY

9 Create a class named ValidateEmployeeAction and paste the following code

Insert the typersquos description hereCreation date (1802 125818 PM)author Administrator

import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

86

public class ValidateEmployeeAction extends orgapachestrutsactionAction

ValidateEmployeeAction constructor comment public ValidateEmployeeAction()

super()

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException ActionErrors errors = new ActionErrors()EmployeeForm empForm = (EmployeeForm) form

String name = empFormgetName()if(nametrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingnamerdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String department = empFormgetDepartment()if(departmenttrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingdepartmentrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String[] skills = empFormgetSkills()if(skills == null)

ActionError error = new ActionError(ldquoerrormissingskillsrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

if(errorssize() gt 0)

saveErrors(requesterrors)return new ActionForward(mappinggetInput())

return mappingfindForward(ldquosuccessrdquo)

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

87

10 In eappsprogram filesibmVisualAge for Javaideproject resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft create a file namedInputContentjsp and paste the following 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-INFapptld prefix=app gtlthtmlgt

ltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgtlthtmltext property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogtlttdgtlttdgtlthtmlselect property=rdquodepartmentrdquogtlthtmloptions name=rdquodepartmentListrdquogtlthtmlselectgtlttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogtltbeanmessage key=rdquopromptemployeeskillsrdquogtlttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoskillsListrdquogtlthtmlmultibox property=rdquoskillsrdquogtlt= currentSkill gtlthtmlmultiboxgtlt= currentSkill gt

88

ltbr gtltlogiciterategtlttdgtlttrgtlttrgtlttd colspan=rdquo2rdquo align=rdquocenterrdquogtlthtmlsubmit value=rdquoValidaterdquogtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

11 In the same folder create a file named OutputContentjsp and paste the followingcode

lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gtlttaglib uri=WEB-INFapptld prefix=app gt

lthtmlgtltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgt

ltbeanwrite name=rdquoempFormrdquo property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogt

lttdgt

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

89

lttdgt ltbeanwrite name=rdquoempFormrdquo property=rdquodepartmentrdquogt

lttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogt

ltbeanmessage key=rdquopromptemployeeskillsrdquogt

lttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoempFormrdquo property=rdquoskillsrdquogt

lt= currentSkill gtltbrgt

ltlogiciterategtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

12 Just to make sure that you have the craft application correctly configure make surethat the file defaultservlet_engine located in eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere Test Environmentpropertiescontains the following entry

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

13 In the end the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstrutsmdashconfigxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtld

90

struts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd|_ classes

Deploying and running the sample application1 Bring up the WebSphere Test Environment then click on Edit Class Path

click Select All enter the following text in the extra classpath area

EAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INFclassesEAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INF

click OK

2 Start the servlet engine

3 Once the servlet engine is started

bring up a browser enter the following URL httplocalhost8080craftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

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

91

Enter stuff in it and press Validate and

92

Lesson 14 - Installing Struts 11b in ORIONThis lesson walks you through the installation of Struts 11b in the Orion webserver Aswith the WebSphere installation you need to go through Lesson 1 to prepare yourenvironment Installation of the sample application relies heavily on the instructions inLesson 12 so it is assumed that you have already gone through that lesson Otherwisefollow the instructions for Installing the sample application in Lesson 12 to create thenecessary components

Installation and configuration1 Downloadinstall the following

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract the Xercesjar file and save it in EORIONservletscraftWEB-INFlib

Xalan from httpxmlapacheorgxalan-jindexhtml the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar save them in EORIONservletscraftWEB-

INFlib

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip extract Strutsjar and save it in EORIONservletscraftWEB-INFlib

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and save the commons-jar files toEORIONservletscraftWEB-INFlib

OR

Open the binary distribution of STRUTS and extract all commons jar files and save themin

eORIONservletscraftWEB-INFlib

2 Open jakarta-struts-11-b1zip and extract the following files toeORIONservletscraftWEB-INF

struts-tld ndash dtd ndash xml

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

93

note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 Copy the file struts-configxml from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF toeORIONservletscraftWEB-INF

2 Open the webxml file in eORIONservletscraftWEB-INF and replace thecontents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquo

ldquohttpjavasuncomj2eedtdsweb-app_2_3dtdrdquogt

ltweb-appgtltservletgt

ltservlet-namegtactionltservlet-namegtltservlet-classgtorgapachestrutsactionActionServletltservlet-classgtltinit-paramgt

ltparam-namegtapplicationltparam-namegtltparam-valuegtApplicationResourcesltparam-valuegt

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgtltservlet-mappinggt

ltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggtlttaglibgtlttaglib-urigtbeanlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-beantldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigthtmllttaglib-urigt

94

lttaglib-locationgtWEB-INFstruts-htmltldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtformlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-formtldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtlogiclttaglib-urigt

lttaglib-locationgtWEB-INFstruts-logictldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigttemplatelttaglib-urigtlttaglib-locationgtWEB-INFstruts-templatetldlttaglib-locationgtlttaglibgtlttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgt

lttaglibgtltweb-appgt

3 Copy the file apptld from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraftWEB-INF

4 Copy the file ApplicationResourcesproperties from eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftcomfficfincraftresource toeORIONservletscraftWEB-INFclasses

5 From VAJ export the class named EmployeeForm to

eORIONservletscraftWEB-INFclasses

Note the classes will be exported to the corresponding directory structurecomfficexamplestruts

6 From VAJ export the class named DepartmentTag toeORIONservletscraftWEB-INFclasses

7 From VAJ export the class named SkillsTag to eORIONservletscraftWEB-INFclasses

8 From VAJ export the class named ValidateEmployeeAction toeORIONservletscraftWEB-INFclasses

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

95

9 Copy the file InputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

10 Copy the file OutputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

11 Upon completion the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstruts-configxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtldstruts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd

|_ classesApplicationResourcesproperties|_com

|_ffic|_example

|_strutsValidateEmployeeActionclassDepartmentTagclassSkillsTagclassEmployeeFormclass

|_libstrutsjarXercesjarXalanjarxml-apisjartilesjarcommons-validatorjarcommons-servicesjarcommons-pooljar

96

commons-loggingjarcommons-digesterjarcommons-dbcpjarcommons-collectionsjarcommons-beanutilsjar

Deploying and running the sample application1 Start ORION (eorionjava -jar orionjar)

2 Once the ORION is started

bring up a browser enter the following URL

httplocalhostcraftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

Enter stuff in it and press Validate and the output should look something like the nextscreen

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

97

98

Lesson 15 - Struts ComponentsHere is a more detailed discussion on the commonly used classestaglibs in the Strutsframework To learn Struts I strongly suggest that you read this document a number oftimes revisit the example application andor hack it and most important of all ask lots ofquestions It takes more than just this document to help you understand and work withthe struts framework The last part of this document lists some very useful struts-relatedURLs that can supplement what yoursquove learned so far

Struts ComponentsThe classes described below are part of the Struts distribution package which youdownloaded in Lesson 13 In VAJ these are in the STRUTS project They may also befound in the strutsjar file that came with the binary distribution of struts

ActionServlet (orgapachestrutsactionActionServlet)

This class extends HttpServlet and is the only servlet in the Struts framework

Itrsquos main responsibilities are

receive request from the browser automatically populate any associated javabeans (ActionForms) with data from the

browser determine the class (Action) that will process the request receives notice of completion from the Action class to do either a a server-side or

client-side redirect

To configure the ActionServlet we need to enter information about this servlet in theapplication deployment descriptor just like any other servlets

In webxml (ORION)

ltservletgtltservlet-namegtactionltservlet-namegtltservlet-classgt

orgapachestrutsactionActionServletltservlet-classgt

This line tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-paramgtltparam-namegtapplicationltparam-namegtltparam-valuegt

ApplicationResourcesltparam-valuegt

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

99

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-mappinggtltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggt

In craftwebapp (VAJWebSphere Test Environment)

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgt

This tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-parametergt ltnamegtapplicationltnamegt ltvaluegt

ApplicationResourcesltvaluegt ltinit-parametergt

This tells the ActionServlet where to look for mapping information(ActionActionForm definitions)

ltinit-parametergt ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltservletgt

Yoursquoll notice that we sometimes override some initialization parameters for theActionServlet with our own values For a complete list of initialization parameters youcan go the jakartaapachecomstruts website For our purpose of building a simplestruts-based application these initialization parameters will suffice

100

ActionForm (orgapachestrutsactionActionForm)

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

public class DivisionBean extends orgapachestrutsactionActionForm

place your settersgetters etc here

Enter the form information in the struts-configxml file using ltform-beangt tags

ltform-beansgtltform-bean name=rdquoDivisionFormrdquo type=rdquocomffictrainingDivisionBeanrdquo gt

ltform-beansgt

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

ltaction-mappingsgtltaction path=rdquovalidateDivisionrdquo

type=rdquocomfficexamplestrutsValidateDivisionrdquoname=rdquoDivisionFormrdquoscope=rdquorequestrdquoinput=rdquoInputjsprdquogtltforward name=rdquosuccessrdquo path=rdquoDisplayDivisionjsprdquogt

ltactiongtltaction-mappingsgt

Action (orgapachestrutsactionAction)

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)

250

Complete code (comffictrainingLoginAction)

import orgapachestrutsactionimport orgapachestrutsvalidator

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

public class LoginAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws IOExceptionServletException

ActionErrors errors = new ActionErrors()

try

errors = ((DynaValidatorForm)form)validate(mappingrequest)if (errorsempty())

saveErrors(request errors) return new ActionForward(mappinggetInput())

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

251

5 We then need to define new validation rules for the dynamic form Open the filevalidationxml located in craftWEB-INF and add the following entries within theltformsetgt tags

ltform name=logonFormgtltfield property=userId depends=requiredgt

ltarg0 key=promptloginusergtltfieldgtltfield property=password depends=requiredmaskgt

ltarg0 key=promptloginpasswordgtltvargt

ltvar-namegtmaskltvar-namegtltvar-valuegt^[a-zA-Z]$ltvar-valuegt

ltvargtltfieldgt

ltformgt

The rules are the same as the entry for loginForm except that we donrsquot force the user to enter avalid email address in the userId field This tells us that this rule is what gets read when we validatethe login information in the DynaValidatorForm

Deploying the code (Part 2 ndash DynaValidatorForm 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

Result (Part 2 ndash DynaValidatorForm example)The result should look like the following screens below

The login form

252

Submitting the form without any data will result in the following screen

Entering a userid and an alphanumeric password will result in 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

253

Entering a userid and an alpha password will navigate the user to the welcome page

Since the user was not required to enter a valid email address for the userid we can besure that the new process is whatrsquos working behind the scenes to contain form data usingthe DynaValidatorForm and to perform the validation using struts-validator

254

Lesson 28 ndash Using tokensBasics A highly recommended way of keeping our transactions in synch is the use of tokens Atoken is a random number that gets stored in the users session a copy of which issupposed to be stored in the request If the session and request tokens are missing orare different then the transaction is out of synch To illustrate this if we have a processthat adds a record to a database using a jsp and an action class The user aftersubmitting the form and getting the confirmation that the record was successfully addedmay click on the dreaded BACK button and navigate back to the data entry screen andclick the SUBMIT button again to add the same record As a rule of thumb it is not safeto assume that users will follow instructions all the time ndash most will but there are a fewgremlins out there who will want to play around with the application We want to design asystem that deals with this type of situation The simplest way to address this is to use atoken that gets created when the entry form is displayed for the first time and theninvalidatedreset after the successful completion of the operation If the user tries to goback to the data entry screen the token will no longer be valid since it has already beenreset and therefore we can navigate the user to an error page where he canrsquot hurt himselfor the application

CodingInstead of creating a new process we will use the existing edit function to demonstratethe use of tokens in Struts

The flow of the new edit process will be as follows

Displayjsp will display all Division items Clicking on the ldquoeditrdquo link will invoke DivisionActionrsquos edit() method which will bring up

an edit page containing the selected Division item At this point a token will begenerated

The user makes changes to the division descripition (or not) and submits the formThe DivisionActionrsquos update() method will then be invoked In this method the tokenwill be validated and if valid the update will occur Otherwise the user will be thrownto the login page with the corresponding error message

1 In VAJ make the following changes to the edit() and update() methods of theDivisionAction class and the execute() method of the FindDivisionAction class

Add the following line of code within the try block just before returning an ActionForward

saveToken(request)

This code puts the token in the request which will be written in the output jsp as a hiddenfield inside the lthtmlformgt 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

255

2 Next is to make changes to the update() method of the DivisionAction class tovalidate the token and make the necessary decisions

In the try block change the following lines of code

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

to

if (isTokenValid(request))

resetToken(request)

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

else

ActionError error = new ActionError(errorduplicatesubmit)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

3 Since we created a new key for an error message in the previous step we need tomake an entry in the ApplicationResourcesproperties to assign a value to thiskey Add the following line of code in the ApplicationResourcesproperties file

errorduplicatesubmit=ltbgtltfont color=redgtDuplicate page submission session has beeninvalidate Please log in againltfontgtltbgt

4 There is also a new forward named loginpage in the update() method so add aforward named loginpage for the DivisionAction action-mapping entry in struts-configxml that maps to the login jsp

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

256

ltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

We have completed the coding changes at this point so letrsquos 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 Click on the Display Division link

ResultTo test out the use of the token just follow the screen sequence below

The list of division items will be displayed initially

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

257

Select an item to bring up an edit screen

258

After submitting the edit form the items will be redisplayed

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

259

Clickin on the browserrsquos back button will cause the screen to navigate back to the editpage

Since the token was already reset submitting that same form will trigger an exceptionand the screen will navigate to the login page with the corresponding error message

260

Lesson 29 ndash Implementing security in StrutsBasics

First some definitions

Authentication is the process by which a user submits a set of credentials to theapplication which then checks if the submitted credentials match those that are keptinternally

Authorization is the process of determining if a user authenticated or not is able toaccess a protected resource

J2EE standards provide for container-managed authentication and authorization usingentries in the application deployment descriptor (the deployment descriptor would be thecraftwebapp in VAJ and webxml in ORION) If you are not familiar with and want tolearn about configuring container-managed security form-based authentication inparticular go to this url for an overview ==gthttpwwwonjavacompubaonjava20010806webformhtml The implementation ofcontainer-managed security varies from webserver to webserver and we thereforecannot cover this in our lesson We however will be implementing the authenticationpiece using Policy Director (PD) which uses an LDAP to retrieve user infoauthorizationparameters We will then handle the implementation of the authorization piece withinStruts

Lets look at how our application will interact with PD to authenticate users

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

261

From the diagram above we can retrive the information from the HttpRequestrsquos headerusing the following codes

To retrieve the user name

String user = (String)reqgetHeader(IvUserHeaderKey)

To retrieve the groups to which the user is associated

String groups = reqgetHeader(IvGroupsHeaderKey)

Note that groups is defined as a String instead of a collection This is because theinformation retrieved from the header is a comma-delimited string so we need to providea convenience method to parse this information and place them in a collection

Upon successful authentication we need to save the user information off to a sessionobject so we can access this information anywhere within the application We then needto design a security framework around our application that will provide authorizationservices As mentioned before PD will provide the authentication service for ourapplication

Declarative security

Declarative security provides for setting security parameters outside the applicationcodes usually in an xml file the advantage of which is there is no need to recompile anyof the source codes to effect new security rules

Struts does not (yet) provide for declarative security and for good reason The frameworkneeds to be independent of any type of implementation for authenticationauthorizationfor the purpose of portability While it does not provide declarative security it does haveprovisions which enables developers to quickly develop their own mechanism fordeclarative security The next section will walk you through the steps in creating a simplebut effective security framework in Struts

Coding (Part 1 ndash protecting do classes)In this section we will create an abstract action class wersquoll call it BaseAction that willperform the necessary security checks This way we only have one place to make achange in case we need to enhance the code This class will then be extended by allother action classes

262

Below is a diagram that represents how our example application will look like at the endof this section

1 A ltset-propertygt tag can be used to define arbitrary parameters that will be passedto the action class using the ActionMapping object We will take advantage of thisfeature to declare our own security parameter In the struts-configxml file add thefollowing tag to the action classes that need to be protected

ltset-property property=isSecure value=true gt

Add this tag to the entries for the LoginAction DivisionAction and FindDivisionActionclasses

ltaction path=login type=comffictrainingLoginAction name=logonForm scope=requestinput=Loginjspgt

ltset-property property=isSecure value=falsegtltforward name=success path=welcomepagegt

ltactiongt

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

263

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

ltset-property property=secure value=truegt ltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

ltaction path=findDiv type=comffictrainingFindDivisionAction name=srchFormscope=request input=diveditpagegt

ltset-property property=secure value=truegtltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltexception key=errordivisionnotnumber type=javalangNumberFormatException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=loginpage path=Loginjspgt

ltactiongt

Note The parameter we defined above will cause Struts to invoke the setIsSecure() method ofthe ActionMapping object

2 To make sure that Struts reads the parameter we defined in the previous step weneed to define a variable in subclass of the ActionMapping class with thecorresponding accessorsmutators Create a subclass oforgapachestrutsactionActionMapping named FFICActionMapping in thepackage comffictraining

public class FFICActionMapping extends orgapachestrutsactionActionMapping

Declare a private variable for the parameter

private boolean isSecure = false

Define the settergetter that corresponds with the property attribute in the ltset-propertygt tag

public boolean getIsSecure() return isSecure

public void setIsSecure(boolean secure)

264

thisisSecure = isSecure

Complete code (comffictrainingFFICActionMapping)

Insert the types description here Creation date (6302 24414 PM) author Administrator public class FFICActionMapping extends orgapachestrutsactionActionMapping

private boolean secure = false

Construct a new instance of this class with the desired default form bean scope public FFICActionMapping()

super()

Insert the methods description here Creation date (6302 24740 PM) return boolean public boolean getSecure()

return secure Insert the methods description here Creation date (6302 24717 PM) param secure boolean public void setSecure(boolean secure)

thissecure = secureSystemoutprintln(security indicator set)

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

265

3 Now that weve can set security parameters in our config we need to create anaction class that uses this parameter To centralize the code for this create aabstract class named BaseAction which extends orgapachestrutsactionActionThis class will contain the logic that checks if an action class requires a user to belogged-in If so it then checks if the user is already logged in before it runs theexecuteAction() method of its subclass

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

The execute() method receives the FFICActionMapping object and we cast it here

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

Check if this action class requires the user to be logged-in based on the isSecurevariables value

if (requiresLogin(mapping1))

If log-in is required invoke a method that checks for the presence of the userKeyattribute in the session

if (isUserLoggedIn(request))

Execute the subclasss executeAction() method if user is logged-in

return executeAction(mapping1formrequestresponse)

else

If the user has not been authenticated create an ActionError object with thecorresponding error key and forward the user back to the login page

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

266

else

If no authentication is required that is if the isSecure parameter is not coded in theactionmapping invoke the subclass executeAction() method

return executeAction(mapping1formrequestresponse)

Create an unimplemented executeAction() method which will be implemented bysubclasses of BaseAction

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

This method checks if the user is logged-in to the application

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

This method retrieves the actions isSecure parameter to check if log-in is required

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

Complete code (comffictrainingBaseAction)

package comffictraining

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

267

import orgapachestrutsactionActionimport orgapachestrutsactionActionFormimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservlethttpHttpSessionimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

if (requiresLogin(mapping1))

Systemoutprintln(log-in required)

if (isUserLoggedIn(request))

return executeAction(mapping1formrequestresponse)

else

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

268

else

return executeAction(mapping1formrequestresponse)

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

4 Revise all the action classes - extend BaseAction instead of orgapachestrutsactionAction- change the signature of the execute() method

from

public ActionForward execute(ActionMapping mapping ActionFormform

HttpServletRequest requestHttpServletResponse response)

to

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

269

public ActionForward executeAction(FFICActionMapping mappingActionForm form

HttpServletRequest requestHttpServletResponse response)

So far we have the following action classes to change

FindDivisionAction LoginAction

5 The DispatchAction class which we discussed in previous lessons also needs toextend the BaseAction class to be able to implement the security framework

create a copy of orgapachestrutsactionDispatchAction which extendsBaseAction instead of Action in the package comffictraining

change the signature of comffictrainingDispatchActions execute() method

from

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

to

public ActionForward executeAction(FFICActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

6 Change the DivisionAction class that extendsorgapachestrutsactionDispatchAction to extend the newcomffictrainingDispatchAction

public class DivisionAction extends comffictrainingDispatchAction

7 Revise the LoginAction class to save the user information to a session objectnamed userKey This assumes that the user has been successfully authenticatedby PD and that our code has retrieved the user information from the HttpRequestrsquosheader

requestgetSession()setAttribute(userKey((DynaValidatorForm)form)get(userId))

8 Create a new entry in the ApplicationResourcesproperties file for the followingkeyvalue pair

270

errorusernotauthenticated=ltbgtltfont color=redgtYou have not been properlyauthenticatedplease log inltfontgtltbgt

9 Create the class LogoutAction in the package comffictraining so we caninvalidate the session and later on test the security framework

Create a regular action class

public class LogoutAction extends orgapachestrutsactionAction

In the execute() method just invalidate the session and forward the user to the loginpage

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)

throws Exception ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

Complete code (comffictrainingLogoutAction)

import orgapachestrutsaction

import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponse

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

271

import javaxservletServletException

import javaioIOException

import javasqlConnectionimport javasqlSQLException

import javautilCollection

Insert the types description here Creation date (12202 92827 AM) author Administrator public class LogoutAction extends orgapachestrutsactionAction LogoutAction constructor comment public LogoutAction()

super() Insert the methods description here Creation date (12202 94602 AM) return orgapachestrutsactionActionForward public ActionForward execute(ActionMapping mapping ActionForm form

HttpServletRequest request HttpServletResponse response)throws Exception

ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

272

10 Create an entry for the LogoutAction in struts-configxml

ltaction path=logout type=comffictrainingLogoutAction scope=request input=Loginjspgtltforward name=logoutpage path=logoutpagegt

ltactiongt

11 Create LogoutContentjsp in the craft folder

lttable width=100 height=100gtlttrgt lttd valign=center align=centergt lth2gtYou have been logged off lth2gt lttdgtlttrgtlttablegt

12 Open the file tilesDefinitionxml in craftWEB-INF and create a new definition forthe logout page

lt-- Extended definition for account display --gtltdefinition name=logoutpage extends=welcomepagegt

ltput name=body content=LogoutContentjspgtltdefinitiongt

13 Add a line in the menu-configxml for a link to the logout action class (in bold)

ltMenu name=MainMenu title=MainMenu gtltItem 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 gtltItem name=LogOut title=Log Out location=logoutdo gt

ltMenugt

14 Change the TileTemplatejsp in craft to include code that checks for the presence of theuserKey attribute to correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logic 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

273

Encapsulate the menu with logic tags that check for the presence of the userKey session attribute

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

Complete Code (TileTemplatejsp)

lt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFtilestld prefix=tiles gtlt taglib uri=WEB-INFstruts-logictld prefix=logic gt

ltHTMLgtltHEADgtltTITLEgtFiremans Fund Insurance CRAFTltTITLEgt

ltHEADgt

ltBODYgt ltscript language=JavaScript12 src=scriptscoolmenus3jsgtltscriptgtltscript src=scriptscoolmenu-configjsgtltscriptgt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

lttable width=100 border=0gt lttrgt lttd bgcolor=graygtltdiv align=centergtlth1gtMy Applicationlth1gtltdivgt lttdgt lttrgtlttablegt

lttable width=100 height=75 border=0gt

274

lttrgt lttd width=10 align=right valign=top bgcolor=ABABABgt

lttilesinsert attribute=menu gt

lttdgt lttd width=90 valign=center align=centergt

lttilesinsert name=bodygt lttdgt lttrgtlttablegt

lttable width=100 border=0gt lttrgt lttdgtltdiv align=centergt

ltfont size=-1gtCopyright 2002ltfontgtltdivgt

lttdgt lttrgtlttablegt

15 Change the Menujsp to include code that checks for the presence of the userKey attributeto correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logicgt

Encapsulate the menu with logic tags that check for the presence of the userKey sessionattribute

ltlogicpresent name=userKeygt

ltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

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

275

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

Add the following codes that provides a link to the log-in page Encapsulate this code withlogic tags that make the link appear only if the userKey is not present

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

Complete Code (Menujsp)

lt taglib uri=WEB-INFstruts-htmltld prefix=html gtlt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFstruts-logictld prefix=logicgt

lthtmlgtltheadgtltheadgtltbodygt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt

276

ltmenuuseMenuDisplayergt

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

ltbodygtlthtmlgt

Deploying the code (Part 1 ndash protecting do classes)

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

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

277

Result (Part 1 ndash protecting do classes)The login screen

The welcome page now shows a ldquoLog Outrdquo link which invalidates the session

278

Clicking on the ldquoDisplay Divisionrdquo link displays the division items as before No errors atthis point since the user was successfully authenticated during login

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

279

Clicking on the ldquoLog Outrdquo link will navigate the user to the page below It shows the ldquoLogInrdquo link which navigates the user to the login page when clicked

If instead of logging back in the user types a url(httplocalhost8080craftadminDivdomethod=view) on the address line (or uses abookmark) the application will determine that the user has not been authenticated andwill then be navigated to the login page which displays an error message

280

OK now we can prevent those gremlins from bookmarking our applicationrsquos urls Wehave one more thing to do though there are urls that map directly to our jsp pages and atthis point anyone can type a valid url to a particular jsp and can successfully bring up thepage without authenticating to the system There are two recommended ways ofprotecting the jsps

1 Place all jsps under the WEB-INF folder This folder per J2EE standardcan only be accessed from within an application and is not publiclyaccessible via urls typed in the browser

2 Create a custom tag that checks if the user has been authenticated similarto the code we placed in the BaseAction class and perform a redirect to thelogin page if the user has not properly logged in

For option 1 it works well with J2EE compliant application servers but since we are usingWebSphere 353 there is basically no WEB-INF folder to speak off We created a WEB-INF folder in our craft application but this is just to line up our directory structure withJ2EE standards We will therefore cover option 2 in the next section

Coding (Part 2 ndash protecting jsp pages)Unlike the example that we put together in part 1 of this lesson the custom tag that wewill create in this section unconditionally checks if the user has logged-in already Inshort there will be no logic in this custom tag that is equivalent to the code in therequiresLogin() method of BaseAction The MVC patternrsquos basic premise is that usersneed to interact with a controller at all times and not the view It therefore follows thatusers should not be able to bring up jsprsquos (view) directly without going to an action classfirst

1 As previously mentioned we will create a custom tag that checks if a user has loggedin already In the package comffictraining create a class named CheckLoginTag

Create the class by extending TagSupport

public final class CheckLoginTag extends TagSupport

Create an instance variable containing information for the login page

private String page = loginjsp

The doEndTag() is where we check for the presence of the ldquouserKeyrdquo The logic is similarto the BaseActionrsquos isUserLoggedIn() method

public int doEndTag() throws JspException

Is there a valid user logged on

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

281

boolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered

public int doStartTag() throws JspException

return (SKIP_BODY)

Complete Code

import javaioIOExceptionimport javaxservlethttpHttpSessionimport javaxservletjspJspExceptionimport javaxservletjspJspWriterimport javaxservletjspPageContextimport javaxservletjsptagextTagSupportimport orgapachestrutsactionimport orgapachestrutsutilMessageResourcesimport javaxservlethttpHttpServletRequest

Check for a valid User logged on in the current session If there is no such user forward control to the logon page

282

public final class CheckLoginTag extends TagSupport

The page to which we should forward for the user to log on private String page = loginjsp

Perform our logged-in user check by looking for the existence of a session scope bean under the specified name If this bean is not present control is forwarded to the specified logon page exception JspException if a JSP exception has occurred public int doEndTag() throws JspException

Is there a valid user logged onboolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered exception JspException if a JSP exception has occurred public int doStartTag() throws JspException

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

283

return (SKIP_BODY)

2 Open the file apptld in craftWEB-INF and add an entry for the new tag

lttaggtltnamegtcheckLoginltnamegtlttagclassgtcomffictrainingCheckLoginTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggt

3 Make changes to ALL the jsps that wersquove created so far

Add a directive for the apptld

lt taglib uri=WEB-INFapptld prefix=app gt

Place this line of code at the top of each jsp

ltappcheckLogin gt

Deploying the code (Part 2 ndash protecting jsp pages)

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

Result (Part 2 ndash protecting jsp pages)Log into the application then click on the ldquoLog Outrdquo link to make sure that whateversession you have in your browser has been invalidated

284

The screen below makes sure that you have been logged out

In the same page type in the url for the divisionrsquos search pagehttplocalhost8080craftdivSearchjsp

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

285

The checkLogin tag will check to see if the user has logged in or not Since the sessionhas been invalidated the checkLoginTag will perform a forward to the login page

Note Irsquom still working on getting the tag to write an error message similar to what theBaseAction does when it forwards to the login page if the user has not authenticated yet

  • Lesson 1 - ORION webserver configuration
    • Preparation
    • Installation
    • Configuration
    • Review
      • Lesson 2 - VisualAge for JAVAWebSphere Test Environment configuration
        • Installation
        • Configuration
        • Usage
          • Lesson 3 - Servlet primer
            • Basics
            • Your first servlet
            • Deploying the code
              • Lesson 4 - Database Connectivity
                • Preparation
                • Coding
                • Deploying the code
                  • Lesson 5 - ServletDatabase Connectivity
                    • Preparation
                    • Coding
                    • Deploying the code
                      • Lesson 6 - Servlet Redirection
                        • Basics
                        • Preparation
                        • Coding
                        • Deploying the code
                        • Result
                          • Lesson 7 - JavaBeans
                            • Basics
                            • Coding
                            • Deploying the code
                            • Result
                              • Lesson 8 - Object Scope
                                • Basics
                                • Coding
                                • Deploying the code
                                • Result
                                  • Lesson 9 - Java Server Pages (JSP)
                                    • Basics
                                    • Coding
                                    • Deploying the code
                                    • Result
                                      • Lesson 10 - Custom Tags
                                        • Basics
                                          • Anatomy of a Tag
                                          • Custom Tag components
                                            • Coding
                                            • Deploying the code
                                            • Result
                                              • Lesson 11 - Model-View-Controller Design Pattern
                                                • Basics
                                                  • Lesson 12 - Introduction to the Struts Framework
                                                    • Struts Components
                                                    • ldquoI canrsquot find the MVC pattern anywhererdquo
                                                      • Lesson 13 - Installing Struts 11b in VisualAge for Java 40WebSphere Test Environment 353
                                                        • Installation and configuration
                                                        • Installing the sample application
                                                        • Deploying and running the sample application
                                                        • Result
                                                          • Lesson 14 - Installing Struts 11b in ORION
                                                            • Installation and configuration
                                                            • Installing the sample application
                                                            • Deploying and running the sample application
                                                            • Result
                                                              • Lesson 15 - Struts Components
                                                                • Struts Components
                                                                • Tag Libraries
                                                                • Useful Links
                                                                  • Lesson 16 - Building a simple web application using Struts
                                                                    • Basics
                                                                    • Coding
                                                                    • Deploying the code
                                                                    • Result
                                                                      • Lesson 17 ndash Validating form values
                                                                        • Basics
                                                                        • Installation
                                                                        • Coding
                                                                        • Deploying the code
                                                                        • Results
                                                                          • Lesson 18 ndash Nested Beans
                                                                            • Basics
                                                                            • Installation
                                                                            • Coding
                                                                              • CODING PART 1
                                                                              • CODING PART 2
                                                                              • CODING PART 3
                                                                                  • Lesson 19 ndash Creating reusable screen components
                                                                                    • Basics
                                                                                    • Coding (Part 1)
                                                                                    • Deploying the code (Part 1)
                                                                                    • Results (Part 1)
                                                                                    • Coding (Part 2)
                                                                                    • Deploying the code (Part 2)
                                                                                    • Result (Part 2)
                                                                                    • Coding (Part 3)
                                                                                    • Deploying the code (Part 3)
                                                                                    • Result (Part 3)
                                                                                      • Lesson 20 ndash Creating reusable menu components
                                                                                        • Basics
                                                                                        • Installation
                                                                                          • Option 1
                                                                                          • Option 2
                                                                                            • Coding
                                                                                            • Deploying the code
                                                                                            • Result
                                                                                              • Lesson 21 ndash Connection Pooling
                                                                                                • Basics
                                                                                                • Coding
                                                                                                • Deploying the code
                                                                                                • Result
                                                                                                  • Lesson 22 ndash Creating a singleton to maintain the
                                                                                                    • Basics
                                                                                                    • Coding
                                                                                                    • Deploying the code
                                                                                                    • Result
                                                                                                      • Lesson 23 ndash Data Access Objects
                                                                                                        • Basics
                                                                                                        • Coding
                                                                                                        • Deploying the code
                                                                                                        • Result
                                                                                                          • Lesson 24 ndash Business Objects
                                                                                                            • Coding
                                                                                                            • Deploying the code
                                                                                                            • Result
                                                                                                              • Lesson 25 ndash Action subclasses
                                                                                                                • Coding
                                                                                                                • Deploying the code
                                                                                                                • Result
                                                                                                                  • Lesson 26 ndash Exception handling
                                                                                                                    • Basics
                                                                                                                      • Using nested ifrsquos
                                                                                                                      • Using trycatch blocks
                                                                                                                        • Coding (Part 1 ndash programmatic exception handlin
                                                                                                                        • Deploying the code (Part 1 ndash programmatic excep
                                                                                                                        • Result (Part 1 ndash programmatic exception handlin
                                                                                                                        • Coding (Part 2 ndash using declarative exception
                                                                                                                        • Deploying the code (Part 2 ndash using declarative
                                                                                                                        • Result (Part 2 ndash using declarative exception
                                                                                                                          • Lesson 27 ndash Creating dynamic forms
                                                                                                                            • Basics
                                                                                                                            • Coding (Part 1 ndash DynaActionForm example)
                                                                                                                            • Deploying the code (Part 1 ndash DynaActionForm exa
                                                                                                                            • Result (Part 1 ndash DynaActionForm example)
                                                                                                                            • Coding (Part 2 ndash DynaValidatorForm example)
                                                                                                                            • Deploying the code (Part 2 ndash DynaValidatorForm
                                                                                                                            • Result (Part 2 ndash DynaValidatorForm example)
                                                                                                                              • Lesson 28 ndash Using tokens
                                                                                                                                • Basics
                                                                                                                                • Coding
                                                                                                                                • Deploying the code
                                                                                                                                • Result
                                                                                                                                  • Lesson 29 ndash Implementing security in Struts
                                                                                                                                    • Basics
                                                                                                                                    • Coding (Part 1 ndash protecting do classes)
                                                                                                                                    • Deploying the code (Part 1 ndash protecting do cl
                                                                                                                                    • Result (Part 1 ndash protecting do classes)
                                                                                                                                    • Coding (Part 2 ndash protecting jsp pages)
                                                                                                                                    • Deploying the code (Part 2 ndash protecting jsp pag
                                                                                                                                    • Result (Part 2 ndash protecting jsp pages)

6

ConfigurationCreate a J2EE compliant directory structure To do this follow the steps

1 Create the following directory Eservletscraft This will be your applicationrsquos rootdirectory

2 Under the craft folder create the following directory structure

craft|___images|___WEB-INF

|___classes|___libFolder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

3 Create a file named webxml and save it in eservletscraftWEB-INF then pastethe following code

ltxml version=10gtltDOCTYPE web-app PUBLIC -Sun Microsystems IncDTD Web Application22EN httpjavasuncomdtdweb-app_2_2dtdgt

ltweb-appgt

ltweb-appgt

This file contains the applicationrsquos configuration information Right now itrsquos empty but thewebserver still expects to find this file or else it wonrsquot startup the application

4 To let ORION know about your new application (the one you just created above) youneed to enter some stuff in the ORION xml files To do this

go to EORIONCONFIG open applicationxml using a text editor enter the following information (in bold) right after the tag ltweb-module

id=rdquodefaultWebApprdquo path=rdquodefault-web-apprdquo gt

lt-- --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

7

ltweb-module id=rdquoCRAFTrdquo path=rdquoEservletscraftrdquo gtlt-- --gtltpersistence path=rdquopersistencerdquo gt

save and exit the file open default-web-sitexml again using a text editor enter the following information (in bold)

lt-- The default web-app for this site bound to the root --gtltdefault-web-app application=rdquodefaultrdquo name=rdquodefaultWebApprdquo gt

lt-- --gtlt-- get name from applicationxml ltweb-module id=rdquothis will be the namerdquopath=rdquocrdquogt --gtltweb-app application=rdquodefaultrdquo name=rdquoCRAFTrdquo root=rdquocraftrdquo gt

lt-- --gt

saveexit the file

5 Go to the command prompt and go to eorion

6 Start the server by typing java -jar orionjar on the command line

7 If everything was setup properly you should see the message Orion152 initialized

8 Create an html file named pagehtml and save it in Eservletscraft then pastethe following code

lthtmlgtltheadgt ltheadgtltbodygtltdiv align=centergtlth1gtHELLO WORLDlth1gtltdivgtltbodygtlthtmlgt

9 To test your webserver

bring up a browser (IE or NS) type in httplocalhostcraftpagehtml You should see proverbial HELLO

WORLD on your browser

8

(Hint While Windows itself is not case-sensitive unlike AIX the URL should thatyou type in the browserrsquos address line should match the entry in the xml file)

10 Congratulations yoursquore a survivor

ReviewThe following information is worth rememberingDIRECTORY STRUCTURE

craft|___images|___WEB-INF

|___classes|___lib

Folder descriptions

craft - root directoryimages - where image files are stored (images can actually be stored in the rootbut this is best practice)WEB-INF - contains xml files (webxml struts-xml) and taglib descriptors (tld)wersquoll cover these laterclasses - where programmer-written java codes are storeddeployedlib - contains 3rd party java codes (usually in jar files)

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

9

Lesson 2 - VisualAge for JAVAWebSphere TestEnvironment configurationThis is a minimalist instruction on how to configure your WebSphere Test Environment(WTE) in VAJava to start serving web applications It walks you through the steps increating a CRAFT application and testing the setup to make sure that is runs It shouldtake an hour (or more) to complete this exercise

InstallationInstall VAJava 40 (easy to say huh) You should already have it in your workstationCheck that the WebSphere Test environment is installed in VAJ By selectingWorkspaceToolsWebSphere Test Environment VAJ should tell you if itrsquos there or not If not

Select FileQuick StartSelect FeaturesAdd FeatureSelect WebSphere Test Environment 353 from the list and click OK

Configuration1 Create the following directory structure under eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_host (whew)

craft|_images|_WEB-INF

|_classes

Folder Descriptions

craft - root directorycontains html and jsp filesimages - contains image filesWEB-INF - is not automatically recognized by WebSphere but wersquoll create this so wecan create a pseudo-J2EE directory structureclasses - again not automatically recognized by WebSphere wersquoll create this for thesame reason as the previous folder

2 Create a file craftwebapp and put the following text in the file

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegt

10

ltservletgtltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtinvokerltnamegtltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegt

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

11

ltvaluegtindexhtmlltvaluegtltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

3 To let WTE know about your new application go to the directory eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmentproperties and open the file defaultservlet_engine using a text editorAdd the following text

Look for this tag ltwebsphere-servlet-host name=rdquodefault_hostrdquogt and paste the followingtext right after it

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

UsageThis section will walk you through how to test if your WTE configuration is correctly setup1 Create a file named indexhtml and save it in eappsprogram

filesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft then paste the following code

ltHTMLgtltHEADgtltMETA NAME=GENERATOR Content=NetObjects ScriptBuilder 30gtltTITLEgtWebSphere Test Environment Index PageltTITLEgtltHEADgtltBODYgtlth1gtThis is the index page for the WebSphere Test Environmentlth1gtltBODYgtltHTMLgt

2 Bring up VAJava

3 Select WorkspaceToolsWebSphere Test Environment

4 Click on Start Servlet Engine

12

5 When the message at the lower left says ldquoServlet engine is startedrdquo bring up abrowser

6 Type in this URL httplocalhost8080craft

If the installation is successful yoursquoll get the following message on your browser This is the index page for the WebSphere Test Environmentif not wersquoll take a look at your problem

7 Thatrsquos itnow on to greater 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

13

Lesson 3 - Servlet primerHerersquos the next installment on the web-application development crash-course You willcreate your first servlet which will hopefully give you a basic understanding of whatservlets are and how they work I gave examples on how to deploy the code both in VAJWTE and in Orion so you can continuously compare the two web environments This willgo on for the next few lessons and then when we get to Struts wersquoll just retain theWebSphere Test Environment which is where we should be developing our codes

BasicsServlet

body of java code that extends a java-enabled serverrsquos functionality listens to requests and usually sends back a response to the client Can also pass

processing on to other servlets does not have a main() method so it cannot run outside of the servlet container to create a servlet we generally extend the class HttpServlet which is a subclass of

GenericServlet HttpServlet makes use of the HTTP protocol

Servlet life-cycle

An HttpServlet contains the following methods

init() doGet()doPost() destroy()

When a servlet is first invoked the servlet container calls the servletrsquos init() method thenit calls either the doGet() or doPost() method

For subsequent requests only the doGet() or doPost() method is called A separatethread is created for every doGet()doPost() invocation so different requests will not runinto each other We place the majority of our code in either of these methods

When the servlet container is shutdown it calls the servletrsquos destroy() method

RequestResponse paradigm

Uses HTTP which is a stateless protocol

In itrsquos simplest form

client sends a request and servlet receives request (and response) object which mayhave objects attached to it (parameters or attributes RemoteUser etc)

14

servlet processes the request (access a db contruct an html response forward toanother servlet etc)

client receives some form of response from the servlet and renders the output to the browser

Your first servletIn VAJ

1 Create a project named TRAINING2 Create a package named comffictraining3 Create a class named HelloWorldServlet4 Add these codes to HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

Code Walkthrough

1 To make HelloWorldServlet a servlet it needs to extend HttpServlet

public class HelloWorldServlet extends HttpServlet

2 We will then need to implement one of the following methods

doGet()doPost()

In this example we implemented the doGet() method

public void doGet(HttpServletRequest 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

15

3 Inside the doGet()

we set the content type for the response to texthtml since we intend to send back anhtml response

responsesetContentType(ldquotexthtmlrdquo)

4 We then retrieve the PrintWriter from the response so we can start writing our outputto it

PrintWriter out = responsegetWriter()

5 Lastly we start writing our output

outprintln(ldquolth1gtHello worldlth1gtrdquo)

After executing the last line of code the servlet returns control back to the web containerwhich sends the response back to the client Since we added stuff in the response theclientrsquos browser will attempt to render it

Deploying the codeVAJava (WebSphere Test Environment)

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (this can be the last entry just beforethe

ltwebappgt tag)

ltservletgtltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

Orion

16

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgtltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in ldquoHello Worldrdquo being displayed on your browser

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

17

Lesson 4 - Database ConnectivityBefore we move on to other web components we need to briefly go through the topic onconnecting to a database and retrieving information from the tables This will make thenext few topics a lot more interesting since you will be displaying data on the browser thatwere retrieved straight off of the db instead of flooding your servlet with ldquoset-this set-thatvaluerdquo lines of codes

After going through this exercise it will become more obvious that this is not the real-world way of creating and maintaining connections to a database Creating a connectionfor each sql to be executed is a pretty expensive operation In later exercises we willexplore how to create a pool of connections using DataSource and the methods withwhich this datasource is maintained and accessed (the FFIC way of course)This section discusses the java code required to connect to a database and execute sqlto retrieve data

Preparation1 You should have the IOU database information entered in your UDB-client with the

following details

DB Alias = IOUODBC entry = IOU (not really needed in this exercise but check it anyway)

2 We will be using the DB2 driver to create the connection to our database If youhavenrsquot done so import the db2javazip file into your VAJ ide

create a DB2 DRIVER project import db2javazip from EAPPSSQLLIBjava into your newly created project

using the following option ldquoimport as a Jar filerdquo

3 For ORION copy the file db2javazip to EservletsORIONcraftWEB-INFliband rename it to db2javajar

CodingIn your TRAINING project create a class JDBCSample in the comffictraining packageand paste the following code in it

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcapp

18

import javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(ldquoDivision ldquo + ldquoCoderdquo + ldquo ldquo + ldquoDescriptionrdquo) while (rsnext())

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

19

String s = rsgetString(1)String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

CODE WALKTHROUGH

1 We need to import the following packages so the program can load the necessaryjdbc classesdrivers

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

2 We define variables for the sql to execute and the useridpassword needed to accessthe database Obviously you must change the userpassword if you have a differentone We also specify here the driver that we will use to create a connection to thedatabase (DB2 in this case)

String query = ldquoSELECT FROM IOUDIVISIONrdquoConnection conn = nullStatement stmt = nullString user = ldquoiccw0t00rdquoString password = ldquoiccw0t00rdquoString driver = ldquoCOMibmdb2jdbcappDB2Driverrdquo

3 This trycatch block attempts to load the database driver and create a connection

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)

20

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)

4 When a connection is successfully created the next trycatch block creates aStatement from the connection and executes the sql that we defined earlier

try 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 )

stmtclose()conclose()

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

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 JDBCSample class and select Run

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

21

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 JDBCSample 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

The output should look similar to the following

loading driverconnectingtojdbcdb2IOUconnectedDivision Code Description1 CID Involuntary 2 CID Voluntary 3 PID 4 CID Specialty 10 National Accounts 11 Jefferson Insurance 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

22

END

NEXTLetrsquos try what we just learned using our servlet example

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

23

Lesson 5 - ServletDatabase Connectivity From the last two lessons you learned to a) construct a simple servlet and b) create ajava program that retrieves data from a database Now we will combine the two andcome up with a servlet that accesses the database and displays the result (ResultSet) ona browser

PreparationRemember your two previous programs If not here are the source codes

HelloWorldServlet

import javaioimport javaxservletimport javaxservlethttp

public class HelloWorldServlet extends HttpServletpublic void doGet(HttpServletRequest request

HttpServletResponse response)throws IOExceptionServletException

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

JDBCSample

Insert the typersquos description hereCreation date (71301 15545 PM)author Administrator import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

24

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

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

try 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 )

stmtclose()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

25

catch(SQLException ex) Systemerrprintln(ldquoSQLException ldquo + exgetMessage())

Before you proceed briefly review how each of the programs work so it will be mucheasier to understand the codes belowthatrsquos all

CodingWith a little tweak (additional codes) the code below shows a combined version of thetwo programs we previously created You can cut and paste it in your HelloWorldServletin VAJ

The blue portion is the HelloWorldServlet while the red portion shows theJDBCSample

You will also notice that there are codes in green These lines of codes were added toaccomodate the codes for JDBCSample and to properly display the output to thebrowser

import javaioimport javaxservletimport javaxservlethttp

import javasqlimport COMibmdb2jdbcappimport javautil

import javasqlSQLExceptionimport javasqlConnectionimport javaxsqlDataSource

public class HelloWorldServlet extends HttpServletString query = SELECT FROM IOUDIVISIONConnection conn = nullStatement stmt = nullString user = iccw0t00String password = iccw0t00String driver = COMibmdb2jdbcappDB2Driver

HelloWorldServlet constructor comment

26

public HelloWorldServlet()

super()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() outprintln(lth1gtHello worldlth1gt)

try

stmt = concreateStatement()ResultSet rs = stmtexecuteQuery(query)

Systemoutprintln(Division Code + + Description) outprintln(lth2gtDivisionlth2gt) outprintln(lth3gtCode Descriptionlth3gt)

while (rsnext()) String s = rsgetString(1)

String ln = rsgetString(2) Systemoutprintln(s + + ln )

outprintln(lth3gt + s +ampnbspampnbspampnbspampnbspampnbspampnbspampnbsp + ln + lth3gt)

stmtclose()

conclose()

catch(SQLException ex) Systemerrprintln(SQLException + exgetMessage())

Insert the methods description here Creation date (42402 22142 PM) public void init()

try Systemoutprintln(loading driver) ClassforName(driver) String url = jdbcdb2IOU Systemoutprintln(connectingto + url) conn = DriverManagergetConnection(urluserpassword) Systemoutprintln(connected)

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

27

try catch(ClassNotFoundException ex) Systemoutprintln(Couldnt load jdbc driver) Systemoutprintln(ex) catch(SQLException ex) Systemoutprintln(Database Problem) Systemoutprintln(ex) catch(Exception ex) Systemoutprintln(Some other problem) Systemoutprintln(ex)

CODE WALKTHROUGH

Irsquove pretty much gone through the codes line by line in the previous lessons What needs to be mentioned here is that a method called init() was added and the codesthat load the DB2 driver and create the connection were added here

Insert the methodrsquos description hereCreation date (42402 22142 PM) public void init()

trySystemoutprintln(ldquoloading driverrdquo)ClassforName(driver)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)

28

Systemoutprintln(ex)

When a servlet starts up the first thing it looks for is an init() method and it executes thismethod once within itrsquos lifetime It is good practice to place initialization stuff in thismethod especially when we only need to run these once A good example is creating aconnection to the database and this is just what we did with this exampleNote As with the init() method a servlet also has a destroy() method which is calledwhen it shuts down

Deploying the codeDeploying the code to VAJ and ORION is the same as in the servlet lesson I listed ithere again just in case you donrsquot have that lesson anymore

Open the craftwebapp file using WordPad It is located in

eappsProgram FilesIbmVisualAge for Javaideproject_resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft)

add the following entry in the craftwebapp file (can be the last entry just before the ltwebappgt tag)

ltservletgt

ltnamegtHelloWorldltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomffictrainingHelloWorldServletltcodegtltautostartgttrueltautostartgtltservletgt

bring up WTE and start the servlet engine make sure the project TRAINING is in the class path If not add it using ldquoEdit Class

Pathrdquo bring up a browser and type the following URL in the address line

httplocalhost8080craftservletHelloWorld

From VAJ export HelloWorldServlet to the eservletscraftWEB-INFclassesfolder using the following options

export as a directoryselect class files only

add the following entry to webxml (this is located in eservletscraftWEB-INF)

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

29

ltservletgt

ltservlet-namegtHelloWorldltservlet-namegtltservlet-classgtcomffictrainingHelloWorldServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

start Orion (eorionjava -jar orionjar on the command line) bring up a browser and type the following in the address line

httplocalhostcraftservletHelloWorld

Both should result in the following output on your browser

30

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

31

Lesson 6 - Servlet RedirectionThis lesson briefly covers one of the more important features of servlets which isforwarding or redirecting In simple terms redirection is passing control to another entitywhich can be a servlet html or jsp at the same logical level It works pretty much like anxctl in CICS with some differences There are two types of redirection client-side andserver-side and these are described in the following section

BasicsClient-side redirection

The redirection happens at the client-side and the URL on the browserrsquos address linechanges to the URL that was sent to it User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and sends a message

(redirect) to the browser containing a URL which the browser will load The browser receives the redirect from the servlet and loads the URL that was sent

to it

Note The URL in the redirect can be another servlet html or a jsp file

To illustrate this process

BROWSER==gtservlet==gtBROWSER==gtresult(jsphtmlservlet)

Client-side redirection is useful when after a servlet processes you want to navigate theuser to another page where even if he reloads that result page will not cause the servletto re-execute In other words the user is navigated to a safe place where he canrsquot hurthimself or the application

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoresponsesendRedirect(url)

if you want to retrieve the original URL to redirect the servlet to itself do this

String url = requestgetRequestURI()responsesendRedirect(url)

Note the getRequestURI() method leaves out the parameters if any that wereincluded in the original URL You can use the requestgetParameter() to retrieve theparameters and attach them to the url

32

Server-side redirection

The redirection happens only at the server-side and the browser does not know anythingabout it The URL on the browserrsquos address line does not change

User enters a URL on the browserrsquos address line that invokes a servlet The servlet receives the request performs processing and forwards itrsquos output to

another servlet jsp or html The receiving sevlet jsp or html renders the output to the browser

To illustrate this process

BROWSER==gtservlet==gtresult(jsphtmlservlet)

Server-side redirection is used to combine several operations to make them appear asone without involving the clientrsquos browser This cuts down traffic between the server andthe browser The browser will receive the result only after the last of the processes hasreleased the output to the web container

Code snippet

within a servlet

String url = ldquoconfirmjsprdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

PreparationThis exercise involves server-side redirection The idea is to have one servlet receive therequest from the browser and perform a redirect to another servlet which will retrieve datafrom a db and construct the html output to be rendered on the browserWe will need the HelloWorldServlet servlet for this exercise which will act as the receivingservlet All we need to contruct is the servlet that will forward the processing toHelloWorldServlet

CodingIn VAJ create a new class called ControllerServlet in the package comffictraining andpaste the following code to it

import javaioimport javaxservletimport javaxservlethttp

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

33

public class ControllerServlet extends HttpServletpublic void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionString url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

1 We define ControllerServlet as a servlet by extending HttpServlet

public class ControllerServlet extends HttpServlet

2 These lines construct the URL of the receiving servlet and performs the redirection

String url = ldquoservletHelloWorldrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtControllerltnamegtltdescriptiongtDB access servletltdescriptiongtltcodegtcomffictrainingControllerServletltcodegtltautostartgttrueltautostartgt

ltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

34

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtControllerltservlet-namegtltservlet-classgt

comffictrainingControllerServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

35

You can verify that the servlet did a server-side redirect if the URL on the browserrsquosaddress line did not change It should still show

httplocalhost8080craftservletController for WTE

or

httplocalhostcraftservletController for ORION

WATCH OUT NEXT FORJAVA BEANS

36

Lesson 7 - JavaBeansUp to this point we have been dealing mostly with webserver configuration andprocedural java codes In this lesson we will start to incorporate object orientation in ourexamples using javabeans

BasicsIn our example programs we created data in our servlet by retrieving information fromthe database and by assigning values to variables There will be times when we want topass this data around and manipulate them before we send them to the browser fordisplay A convenient way of doing this is to encapsulate all these related informationhide them in an object and provide methods to access each value To accomplish thiswe create a java class called javabean or bean that contains only private variables andsettergetter methods for each of these variables For instance we can create a bean called divisionBean and store each row that weretrieve from the database to a divisionBean instance We can then put all these beansinside a collection object that we can pass around and eventually render to the browserSounds confusing Letrsquos do an example then

Coding1 In VAJ create a class called DivisionBean in comffictraining package and paste the

following in it

public class DivisionBean private String divNoprivate String divDesc

public String getDivDesc()return divDescpublic String getdivNo()return divNopublic void setDivDesc(String divDesc)thisdivDesc = divDescpublic void setDivNo(String divNo) thisdivNo = divNo

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

37

2 Open your HelloWorldServlet and make the following changes

Add the following code right after the class declaration

ArrayList divList = new ArrayList()

In the doGet() method

delete the following lines or better yet just comment them out (ie put a beforeeach line)

String s = rsgetString(1)

String ln = rsgetString(2)Systemoutprintln(s + ldquo ldquo + ln )outprintln(ldquolth3gtrdquo + s + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + ln + ldquolth3gtrdquo)

add the following lines within the while loop

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

after the while loop add the following lines of code

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

Code Walkthrough

DivisionBean

1 We defined the two variables divNo and divDesc as private to prevent them frombeing accessed directly (ie divisionBeandivNo)

private String divNoprivate String divDesc

38

2 We then define getters and setters for the two variables

public String getDivDesc()

return divDesc

public String getdivNo()

return divNo

public void setDivDesc(String divDesc)

thisdivDesc = divDesc

public void setDivNo(String divNo)

thisdivNo = divNo

HelloWorldServlet

1 We defined an Arraylist (called divList) which part of the java collections to containthe instances of the beans that we create

ArrayList divList = new ArrayList()

2 In the while loop we instantiate a new divisionBean and set itrsquos variables to thevalues that we retrieve from the db The we add that instance to divList

DivisionBean divisionBean = new DivisionBean()

divisionBeansetDivNo(rsgetString(1))divisionBeansetDivDesc(rsgetString(2))divListadd(divisionBean)

3 After wersquove gone through the entire resultset we loop through divList and create anhtml output for each instance of the bean in the ArrayList The code provided here ispretty much boiler plate code

retrieve an interator from divList (all collections have an interator)

Iterator iterator = divListiterator()

the interator has methods that loop through the ArrayList object (hasNext()) andto retrieve each item (next())

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

39

while (iteratorhasNext())

when an item is retrieved it has to be cast back to the original object In thiscase we cast the item back to DivisionBean

DivisionBean divbean = (DivisionBean) iteratornext() outprintln(ldquolth3gtrdquo +divbeangetDivNo() + ampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +divbeangetDivDesc() + ldquolth3gtrdquo)

Enhancement idea

You may ask ldquoWhy put more code that does the same thing as the originalrdquo

The answer is that creating beans and storing them in collections (or even if you justhave a single bean) enables you to attach this object to for example the request object(ie requestsetAttribute(ldquodivisionListrdquodivList)) and perform a forward to another servletthat contains code (such as the while loop with the iterator) that performs the creation ofthe output to the browser In this case the components can be further divided into thefollowing

ControllerServlet - receives the request from the browser and forwards it toHelloWorldServlet

HelloWorldServlet - retrieves data from the db stores the results inbeanscollection attaches the collection to the request object then performs aserver-side redirect to another servletjsp which we can call DisplayServletDisplayServlet - retrieves the collection from the request object and builds thehtml output while iterating through the collection

This approach enables you as the programmer to assign specific tasks to eachcomponent and keep them loosely coupled so that you can easily change onecomponent without making massive changes to the rest of your application As anexample you can change HelloWorldServlet to access another database (other thanDB2) without affecting the two other servlets in the chain

Deploying the codeVAJ

1 Bring up WTE and start the servlet engine

2 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

40

ORION

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Start ORION (eORIONjava -jar orionjar)

3 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

41

42

Lesson 8 - Object ScopeThis lesson is a sidetrip to learning the concept of object scope We need to cover thisimportant topic before we head on to JSPrsquos (are we there yet)

BasicsIn the previous lesson we learned to create javabeans and put them in a collection(called divList) to be processed by another set of codes within the same servlet We alsotoyed with the idea of creating another servlet (DisplayServlet) that will construct the htmloutput from this collection Since we want to pass the collection from HelloWorldServletto DisplayServlet we need to somehow associate the collection object with a particularscope When we perform a server-side redirect the request and response objects arepassed as arguments in the forward method Before we actually forward the process toanother servlet we make sure that we associate the collection object to the requestobject so that the receiving servlet can access that collection This is an example of anobject scope and in this instance we defined the collection to be in the request scope

A simple definition of Object Scope is the level of availabilityvisibility of an object withinthe application

It can be any of the following

page - object is visible in the page that created itrequest - object is visible in the request to which is belongssession - object is visible in the same session where it was created application - object is visible within the entire application Any servlet regardless of

what session created them can access the object in this scope

To associate an object to a particular scope we use the setAttribute() method If we want to say make the divList collection available to a userrsquos session we use thefollowing code

HttpSession session = requestgetSession(true)sessionsetAttribute(ldquodivListrdquodivList)

so long as the session still exists we can extract that collection at any point within theapplication with the following code

HttpSession session = requestgetSession(true)ArrayList divList = (ArrayList) sessiongetAttribute(ldquodivListrdquo)

Note We have to cast the collection back to itrsquos original form which is an ArrayList

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

43

Letrsquos create the DisplayServlet that we discussed in the previous lesson

1 Create a class called DisplayServlet in your TRAINING project in the packagecomffictraining and paste the following

import javaioimport javaxservletimport javaxservlethttp

import javautilpublic class DisplayServlet extends HttpServlet

ArrayList divList = new ArrayList()public void doGet(HttpServletRequest request HttpServletResponse response) throws

IOExceptionServletExceptionresponsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCodeDescriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() +ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

2 Open HelloWorldServlet and make the following changes

comment out the following lines of code in the doGet() method

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()outprintln(ldquolth1gtHello worldlth1gtrdquo)

outprintln(ldquolth2gtDivisionlth2gtrdquo) outprintln(ldquolth3gtCode Descriptionlth3gtrdquo)

Iterator iterator = divListiterator()while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo +

44

divbeangetDivDesc() + ldquolth3gtrdquo)

add the following lines of code after the stmtclose() line

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquoRequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Code Walkthrough

Display Servlet

1 We define DisplayServlet by extending HttpServlet

public class DisplayServlet extends HttpServlet

3 Define an ArrayList to contain the collection that this servlet will receive fromHelloWorldServlet

ArrayList divList = new ArrayList()

4 Set the content type and get the output writer from the response so we can startwriting output data to it

responsesetContentType(ldquotexthtmlrdquo)PrintWriter out = responsegetWriter()

5 Retrieve the divList collection from the request object and cast it back to an ArrayList

divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)

6 Create the html output while iterating through the collection

Iterator iterator = divListiterator()while (iteratorhasNext())

DivisionBean divbean = (DivisionBean) iteratornext()outprintln(ldquolth3gtrdquo + divbeangetDivNo() + ldquoampnbspampnbspampnbspampnbspampnbspampnbspampnbsprdquo + divbeangetDivDesc() + ldquolth3gtrdquo)

HelloWorldServlet

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

45

1 The lines that we removed from this servlet were transferred to DisplayServlet

2 In the lines that we added we associate the divList collection with the request objectand then do a server-side redirect to DisplayServlet

requestsetAttribute(ldquodivListrdquodivList)String url = ldquoservletDisplayrdquo

RequestDispatcher rd = requestgetRequestDispatcher(url)rdforward(request response)

Deploying the codeVAJ

1 Open the file craftwebapp and paste the following

ltservletgtltnamegtDisplayltnamegtltdescriptiongtDisplay Outputltdescriptiongt

ltcodegtcomffictrainingDisplayServletltcodegtltautostartgttrueltautostartgtltservletgt

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

1 From VAJ export the ControllerServlet to eservletscraftWEB-INFclasses as aclass file

2 Open the file webxml (located in eservletscraftWEB-INF) and paste thefollowing

ltservletgtltservlet-namegtDisplayltservlet-namegtltservlet-classgt

comffictrainingDisplayServletltservlet-classgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

3 Start ORION (eORIONjava -jar orionjar)

46

4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

47

Lesson 9 - Java Server Pages (JSP)BasicsIn the previous lessons we had been constructing our html response within the servletitself It works well with simple html outputs but later on as your webpages get morecomplicated you will find (or you may already have) that this will not work for real-worlddevelopment Java Server Pages (JSP) technology was introduced to make life easier forus programmers and for web designers How If yoursquore familiar with HTML JSP isbasically an html page with little (thatrsquos the plan) java code You get to construct your htmlpage as you normally would and start putting in java logic to a) iterate through acollection of beans b) to include output from another jsp and more To create a jsp filefrom a static html file simply change the filersquos extension from html to jsp and yoursquoreready to go But wait therersquos moreBefore we move on also remember that a jsp is first converted and compiled into aservlet by the web container before it is executed so it will have a similar life cycle as thatof a servlet Inside the jsp file we can put java codes to create dynamic output on thebrowser We accomplish this by using scriptlets expressions declarations and directiveswhich are described below

Scriptlet lt

Scriptlets are regular java codes that are automatically executed by the jsp containerwhen the jsp is invoked so they should be syntactically correct

lt String i = ldquofoordquoSystemoutprintln(i)

gt

Expression lt=

Expressions evaluate to a value that is directly displayed on the browserlt= i gt

The example is converted to outprintln(i) by the jsp container and the value of ldquoirdquo isdisplayed on the browser

Declarations lt

Declarations are java codes that are not automatically executed by the jsp container butmay be invoked if you call it from a scriptlet

lt static printName (String name) Systemoutprintln(name)

gt

48

You can invoke this by writing a scriptlet such as

lt printName(ldquoMyNamerdquo) gt

Directives lt

Directives desribe the necessary components of a jsp

lt page import=rdquojavautilcomffictrainingrdquo gt ==gt imports necessary packageslt taglib uri=rdquobeanrdquo prefix=rdquobeanrdquo gt ==gt declares a taglib referencelt include file=rdquoextraInfojsprdquo gt ==gt includes output from another jsp file

Coding

Suppose the web designer (if there is one) hands you this html file (DisplayDivhtml) lthtmlgtltbodygtlttable border=1gt

lttr align=left gtltthgtDivision IDltthgtltthgtDescriptionltthgtlttrgtlttr align=leftgtlttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgtlttdgt2lttdgtlttdgtCID Voluntarylttdgtlttrgt

lttablegtltbodygtlthtmlgt

The browser output looks like this

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

49

So you the java programmer need to convert this layout to a dynamically generated htmlfile

KNOWN

The data will come from the IOUDIVISION table You already have the servlets (ControllerServlet and HelloWorldServlet) necessary to

perform data retrieval from the db You have a DisplayServlet servlet that creates html output but you want to use a jsp

since you already have the html code and you just need to insert the necessary javacodes to render the dynamic output correctly

HINT We created javabeans (DivisionBean instances) containing Division information and

put them in a collection (divList) that is associated with the request object In our jsp file we can retrieve this collection and iterate through them pretty much the

same way we did with DisplayServlet So most of the codes that we have inDisplayServlet can be reused in the jsp file

Code Walkthrough

1 If you saved the above code in DisplayDivhtml simply rename it to DisplayDivjsp tomake it a jsp file

2 At the topmost portion paste the following code

lt page import=rdquojavautilcomffictrainingrdquo gt

This tells the jsp page that your scriptlets will be looking for necessary classes in thesepackages

3 To display the division code and description we have to insert codes that iteratethrough the collection and render them inside the table

Just after the table header definition (The ones with the ltthgt ltthgt tags) make thefollowing changes

delete the following lines of codes since these are just representations of what thedynamic portion of the page are

lttr align=leftgt

lttdgt1lttdgtlttdgtCID Involuntarylttdgtlttrgtlttr align=leftgt

lttdgt2lttdgt

50

lttdgtCID Voluntarylttdgtlttrgt

insert the following codes

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()gt

Notice that this is strikingly similar to the code in DisplayServlet Thatrsquos because we justcut and paste it from there Even though the loop is not yet complete we terminated these lines of code with a ldquogtrdquo because we need to pasteregular html tags or non-java codes right after it

4 Once the above code starts iterating through the collection we need additional codesto render the details so paste the following code right after it

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

Here we used expressions to execute the ldquogetrdquo methods of the DivisionBean instance toretrieve the division code and description

5 Now this is where most beginners get bit We need to properly terminate the ldquowhilerdquoloop that we started in the previous steps To do this paste the following code rightafter the previous step

lt End whilegt

The completed code looks like the following

lt page import=rdquojavautilcomffictrainingrdquo gtlthtmlgtltbodygtlttable border=1gt

lttr align=leftgtltthgtDivision IDltthgtltthgtDescriptionltthgt

lttrgt

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

51

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext()) DivisionBean divBean = (DivisionBean) inext()

gtlttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End whilegt

lttablegtltbodygtlthtmlgt

HelloWorldServlet

Open HelloWorldServlet and make the following changes

1 Remove the following line of code

String url = ldquoservletDisplayrdquo

2 Replace it with the following line of code to forward the process to DisplayDivjspinstead of DisplayServlet

String url = ldquoDisplayDivjsprdquo

Deploying the codeVAJ

1 Be sure to save DisplayDivjsp in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft

2 Bring up WTE and start the servlet engine

3 Bring up a browser and enter the following URL on the address line

httplocalhost8080craftservletController

ORION

52

1 From VAJ export the HelloWorldServlet to eservletscraftWEB-INFclasses asa class file

2 Save the DisplayDivjsp file in eservletscraft3 Start ORION (eORIONjava -jar orionjar)4 Bring up a browser and enter the following URL on the address line

httplocalhostcraftservletController

ResultThe output for both code deployment should be something 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

53

Lesson 10 - Custom TagsBasicsIn Lesson 9 you learned how to create a JSP to handle content rendition in place of aservlet Wersquove seen how the same codes that we used in the servlet can be re-appliedinside the JSP using scriptlets expressions declarations and directives Again as yourJSPs get more complicated you will want to reduce the amount of java codes in themespecially codes or logic that are candidates for re-use in other JSPs In our exampleprogram if you want the logic that displays the Division information in more than oneJSPs you may want to put that body of code in a central place where you can just call itfrom different JSPs Otherwise you will end up copyingpasting the same codes in everyJSP that needs these codes

Starting with JSP 11 a feature was introduced wherein java codes can be encapsulatedand represented on the JSP using custom tags Custom tags are not unlike HTML tags(ie lthtmlgt ltformgt lttablegt etc) except that we provide the logic that makes the tagswork An example is to replace the scriptlets in your JSP with one tag such asltapplistDivision gt and this will take care of displaying the list of division codes anddescriptions JSP 12 introduced more enhancements to the custom tag feature such asIterationTag but we wonrsquot cover it here since FFIC still uses JSP 11 in WebSphere

Anatomy of a Tag

ltmytaggtvalueltmytaggt

ltmytaggt - opening tagvalue - body of the tagltmytaggt - closing tag

Custom Tag components

1 Developer-provided class that extends the classjavaxservletjsptagextTagSupport TagSupport is a helper class that implementsthe Tag interface When you write your custom tag you will need to implement atleast one of the two most used methods

doStartTag()

triggered when the opening tag is encountered return SKIP_BODY if you donrsquot want to evaluate the body of the tag return EVAL_PAGE_INCLUDE to evaluate the body of the tag

doEndTag()

triggered when the closing tag is encountered return EVAL_PAGE to continue processing the rest of the JSP

54

return SKIP_PAGE to halt processing of the JSP

2 TagLib Descriptor An XML file that describes the custom tag and the class thatimplements the logic

Example

You can save this in a file named apptldltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomfficexamplestrutsDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

3 WEBXML appWEBAPP entry ndash describes the location of your taglib descriptorand assigns a URI to be used in your JSP

Example

lttaglibgtlttaglib-urigtcraftlttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 JSP Directive ltndash tells your JSP that you will be using a custom tag what itrsquos URIis and how you will reference it in your page (using a prefix)

Example

Place this at the top of your JSP

lttaglib uri=WEB-INFapptld prefix=app gt

With these components in place you can start using custom tags in your JSPs

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

55

CodingNow letrsquos create a custom tag out of the scriptlets that we have in DisplayDivjsp

1 In VAJ in the package comffictraining create a class named DivisionTag andpaste the following codes

Insert the typersquos description here Creation date (1802 11910 PM) author Administrator

import javautilimport javaxservletjsptagextTagSupportimport javaxservletjsp

public class DivisionTag extends TagSupportHere we used the doEndTag() method to start evaluating after the body In thiscase there is no bodypublic int doEndTag() throws JspException We retrieve the collection (divList) from the request that is forwarded byHelloWorldServletArrayList divList = (ArrayList)pageContextgetRequest()getAttribute(ldquodivListrdquo)

We then iterate through the collection as we did before and write the output tothe outputstream of the pagetry Iterator iterator = divListiterator()

while (iteratorhasNext()) DivisionBean divbean = (DivisionBean) iteratornext()pageContextgetOut()print(ldquolttr align=leftgtlttdgtrdquo + divbeangetDivNo() +ldquolttdgtlttdgtrdquo + divbeangetDivDesc() + ldquolttdgtlttrgtrdquo)

pageContextgetOut()print(ldquolth3gthelplth3gtrdquo) catch (Exception e) throw new JspException(etoString())

We return eval page to tell the JSP to continue processing the rest of thepage if anyreturn EVAL_PAGE

2 We then need to create a taglib descriptor for this new class Create a file namedapptld and paste the following code

56

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogt

ltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library11ENrdquo ldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogt

lttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtlistDivisionltnamegtlttagclassgtcomffictrainingDivisionTaglttagclassgtltbodycontentgtemptyltbodycontentgtlttaggt

lttaglibgt

3 We then need to tell the webserver about this taglib descriptor In the webxml file(only for Orion) lttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgtlttaglibgt

4 Copy the DisplayDivjsp to a new JSP file named DisplayDivTagjsp and make thefollowing changes

Remove the following lines of code

lt page import=rdquojavautilcomffictrainingrdquo gt

ltArrayList divList = (ArrayList) requestgetAttribute(ldquodivListrdquo)Iterator i = divListiterator()while(ihasNext())

DivisionBean divBean = (DivisionBean) inext()gt

lttr align=leftgtlttdgtlt= divBeangetDivNo() gtlttdgtlttdgtlt= divBeangetDivDesc() gtlttdgtlttrgt

lt End while(ihasNext())

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

57

gt

At the top of the jsp add the following

lttaglib uri=WEB-INFapptld prefix=app gt

This tells the JSP to use apptld and that we will reference this as app allthroughout the page

Just below the table heading tags add the following line of code

ltapplistDivision gt

This invokes the DivisionTag class and starts writing the output to the page

5 Finally open HelloWorldServlet and make the following changes

In the doGet() method remove the line

String url = ldquoDisplayDivjsprdquo

Replace it with

String url = ldquoDisplayDivTagjsprdquo

Deploying the codeVAJ

1 Save the DisplayDivTagjsp in the Javaideproject resourcesIBM WebSphereTestEnvironmenthostsdefault_hostcraft folder

2 Bring up WebSphere Test Enviroment and start the servlet engine

3 Bring up a browser and type the following in the address line

httplocalhost8080craftservletController

ORION

1 Export HelloWorldServlet and DivisionTag to eservletscraftWEB-INFclasses

2 Save DisplayDivTagjsp in eservletscraft

3 Start Orion (eORIONjava ndashjar orionjar)

4 Bring up a browser and type the following in the address line

httplocalhostcraftservletController

58

Result

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

59

Lesson 11 - Model-View-Controller Design PatternBasicsIf you got this far and have understood the previous lessons then you can pat yourself onthe shoulder and say that yoursquore ready to put things together Actually you already haveWe just need to give what yoursquove been doing these past few lessons a catchy name andthat too is already done Over the years as java technology developed design patternsstarted to emerge As these patterns are recognized the most effective ones enduredand took on lives of their own One of these patterns which according to old-timers wasused to program Smalltalk applications is called Model-View-Controller or MVC for shortMVC is also called JSP Model 2 architecture Is there a Model 1 Yes there is and wersquollbriefly discuss the differences between the two models

JSP Model 1

This architecture puts the responsibility of acting on a user input accessing a db andmaintaining application state solely on a single JSP This may do for small applicationsbut not for complex ones The programmer will end up flooding the JSP with tons andtons of scriptlets and other java codes that should logically reside somewhere elseMoreover it is very difficult to coordinate the actions of all JSPs within the applicationsince they are not designed to communicate with each otherBelow is a ldquoreusedrdquo diagram of a JSP Model 1 architecture

JSP Model 2 (MVC)

This architecture extends the Model 1 concept by separating the content rendition (View)function from the application state (Model) and then adding a Controller that conducts theflow of processes within the application This provides for a clean separation ofresponsibilities between each component which results in a clearer definition of roles forweb designers and java programmers

60

Here is another ldquoreusedrdquo diagram and this time of a JSP Model 2 architecture

MVC is composed of obviously a model a view and a controller each of which havespecific functions which are described as follows

Model - represents the state of the application at any given point in time

View - renders the state of the application to the user It also receives user input andsend it to the controller for proper disposition

Controller - acts on a user input determines what action needs to be done delegatesthe action to the required business logic and invokes the Model to change itrsquos state asnecessary

There is no exercise for this lesson I thought Irsquod give you a break before we proceed withthe next one Think of this as the ldquocalm before the stormrdquoHowever letrsquos go through what yoursquove put together so far and try to match theservletsjsp against the MVC components

ControllerServlet (controller) - this contains the beginnings of a controller servlet Bytyping in the URL for this servlet on the browserrsquos address line we are asking it toperform a service for us Inside itrsquos doGet() method it knows that it needs to delegate thetask to HelloWorldServlet which performs the db access and creation of javabeans

HelloWorldServlet (model) - creates and maintains the Model for this little webapplication by storing the data in javabeanscollection It then notifies the View that theModel has changed and that it needs to render the new state

DisplayDivjsp (view) - this jsp page does not know what is happening inside theapplication All it knows is that it gets a notification from the Model that itrsquos state haschanged and that the View needs to re-render it

There we have a mini-MVC application running in our web container Of course it takesmore than a couple of servlets and a jsp to create a real-world web application and thatrsquos

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

61

what we aim to do in the next lessons Keeping this design pattern in mind we are thenready to make a quantum leap to using a framework called STRUTS that implementsthis design pattern I will save the discussion on STRUTS for the next lesson All youneed to know at this point is that STRUTS solves most of the problems (or I should saychallenges) that you will encounter when you try to build your own MVC applicationframework

6

Lesson 12 - Introduction to the Struts FrameworkApplications are generally composed of two major components business-specificcomponents and application services As an application programmer your focus tends tobe more on coding business components rather than application services since thedevelopment life-cycle is really all about gathering business requirements and creatingsystem solutions for them You will just want to be able to code your applicationrsquosbusiness functions and tie them together to create an entire process

Waawa

T

If yoursquore familiar or had worked on CICS applications then it will be easier to graspthe concept of frameworks and what they do to speed up application developmentWhen putting together a CICS application yoursquoll typically need the followingcomponents

1 Entries for CICS tables such asFile Control Table (FCT) ndash contains file aliases (tied to physical file names) to beaccessed in the CICS region (QSAM VSAM etc)

Program Control Table (PCT) ndash defines the relationships between programs andthe files they use

Program Properties Table (PPT) ndash defines the program names transaction idsand typeTerminal Control Table (TCT) ndash contains terminal definition that canaccess the CICS region

2 The symbolic and physical maps (mapsets) for the screen definitions3 CICS programs that contain the flow of the application and business logic

functions4 In the CICS startup jcl you need to put information such as load libraries (should

be in the correct order) of your programs

Once you correctly define and build these components CICS has the responsibility oftying these components together and making sure that when a user types aTransaction ID it will invoke the correct program for it and assign the correct files tothe program Unless you have too much time on your hands you do not want to findout how CICS performs these underlying processes to run your programs

2

ith application development using java programmers have had to build both businessnd application service layers for every application that they construct Most of thepplication services are so customized to the business that there is no way to reuse themith another application so programmers tend to solve the same problems over and overgain

he solution Enter frameworks

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

63

A couple of years back some genius named Craig McClanahan thought up a java-basedframework (Struts) using the MVC design pattern that is generic reusable andextensible (and of course free) It provides a lot of the application services needed toglue an application together while still giving application developers a lot of control overthe business-specific codes that they write Struts is an open source product available fordownload from wwwjakartaapachecomstruts It has a fairly big and activedeveloperuser community that can help beginners get up to speed in using Struts andanswer Struts-related questions that may not be mentioned in available documentation

Struts provides the following application services among other things

request routing errormessage handling generating client-side scripts tag libraries jdbc connection pooling xml parsing automatic population of java beans internationalization of prompts and messages validation menus page layouts

Struts ComponentsSTRUTS ESSENTIAL CLASSES

Struts employs what is called in J2EE lingo a Front Controller pattern wherein it has asingle servlet that receives all requests from the browser and forwards the processing tothe appropriate class handler In essence we do not need servlets other than the oneStruts provides We may sometimes need to extend the functionality of that servlet but inmost cases the vanilla version will do Below are the frequently used classes in theStruts framework with short descriptions

ActionServlet ndash This is the only servlet in the framework and itrsquos job is to receiverequests populate appropriate javabeans from the request delegate the process toanother class that contains business logic (Action) and forwards the process to the nextcomponent as defined in the mapping

Action ndash a class that performs a specific business function (can also dispatch to abusiness logic bean) and returns control back to the ActionServlet with correspondinginformation as to what to do next

ActionForm ndash a javabean that holds the state of the application Programmers writebeans that extend this class so that the ActionServlet can recognize it and populate itwith data from incoming requests

64

ActionForward ndash contains information that tells the ActionServlet the next componentthat will handle the current request

ActionMapping - contains information on Action classes ActionForms and resource filepaths It is read by the ActionServlet to determine which Action will process a request

ActionErrors ndash contains ActionError objects that may have been created whileprocessing a request The contents can then be rendered on an html page

ActionMessages ndash similar to ActionErrors Contains ActionMessage objects createdwhile processing a request The contents can also be rendered on an html page

JSP AND TAG LIBRARIES

In addition to the Struts classes the content rendition portion of the framework uses JSPand custom tags

Bean Tags ndash used to createcopy beans or render bean properties on the pageHtml Tags ndash used to render html form tagsLogic Tags ndash used to perform logical operations such as comparison andor to check forpresenceabsence of beans in the pageNested Tags ndash used to render nested bean properties on the pageTemplate Tags ndash used to render a composite of several jsp pages by pulling these insidea pre-defined layout

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

65

ldquoI canrsquot find the MVC pattern anywhererdquoOK so herersquos a diagram of the Struts Framework which shows how each of thepreviously discussed components work together

66

In MVC semantics the Controller would be the ActionServlet the Model is handled byAction and ActionForm classes and the View is handled by JSPs and tag librariesDid I mention that Struts works at the Presentation Layer of the application I guess notThis means that it does a swell job of conducting the process flow of programs thatinteract with the user (browser) but developers (thatrsquos you) will still need to come up withthe business objects and the data layer objects So in a bigger picture herersquos a diagramshowing where Struts lies

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

67

Below are UML representations of the different parts of the Struts framework

Action

68

Form

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

69

Message

70

Forward

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

71

Mapping

72

Config

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

73

DynaForm

74

Sequence Diagram for a request

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

75

76

The next lessons will walk you through the installation of the Struts framework in bothVAJavaWebSphere Test Environment and Orion We will also build a sample applicationthat uses most of the Struts features so you can get acquainted on the differentcomponents of Struts and how it fits into you web environment

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

77

Lesson 13 - Installing Struts 11b in VisualAge forJava 40WebSphere Test Environment 353This lesson walks you through the installation of Struts 11b in the WebSphere TestEnvironment in VisualAge for Java 40 It assumes that you already have VAJ 40installed in your workstation and that you have properly configured it using theinstructions in Lesson 2 To make sure that Struts is correctly configured you will need toinstall and run the sample application provided in this lesson

What is missing from this lesson is the explanation for the sample application codes Mygoal here is for the user to quickly setup the environment to run Struts so we can proceedwith the next lessons that discuss the different parts of Struts in greater detail

Installation and configuration1 In VAJ you will need to have the following projects present in your workspace

Servlet API ClassesJava Class LibrariesIBM WebSphere Test EnvironmentIBM Enterprise Extension LibrariesIBM XML Parser for Java

If any of the above is missing

select FileQuick Start from the menu select FeaturesAdd Features from the popup window and select the project

you need to import to your workspace

2 Downloadinstall the following

Note If you have projects in VAJ with the same name as the ones listed below be sureto version them first Then when importing the new packages make sure you selectoption create newscratch editions of versioned projectspackages

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract Xercesjar and import it in VAJava in the project XERCES

Xalan from httpxmlapacheorgxalan-jindexhtml

the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar and import them in VAJava in the project XALAN

78

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip

OPTIONAL

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and import these files to a COMMONS project in VAJava

OR

Recommended

Open the binary distribution of STRUTS and extract all commons jar files and importthem in the COMMONS project in VAJava

Struts 11b source from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1src

link is jakarta-struts-11-b1-srczip import the entire file to a STRUTS project in VAJava

Important

You will need to make some revisions to the Struts source code or you will get the following error Cannotremove Attribute from request scope in your browser I think this problem only occurs in WebSphere

In VAJ go to the orgapachestrutstaglibhtml package and open the FormTag class

Replace the following lines in the doEndTag() method in the FormTag class

pageContextremoveAttribute(ConstantsBEAN_KEY PageContextREQUEST_SCOPE)

pageContextremoveAttribute(ConstantsFORM_KEY PageContextREQUEST_SCOPE)

with the following

pageContextgetRequest()removeAttribute(ConstantsBEAN_KEY)pageContextgetRequest()removeAttribute(ConstantsFORM_KEY)

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

79

3 Open jakarta-struts-11-b1-srczip and extract the following files to eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF

struts-tld dtd xml

Note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 In the directory eappsprogram filesibmVisualAge for JavaideprojectresourcesIBM WebSphere Test Environmenthostsdefault_hostcraftWEB-INF create a file named struts-configxml file and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoISO-8859-1rdquo gtltDOCTYPE struts-config PUBLIC

ldquo-Apache Software FoundationDTD Struts Configuration 11ENrdquoldquohttpjakartaapacheorgstrutsdtdsstruts-config_1_1dtdrdquogt

ltstruts-configgtltform-beansgtltform-bean name=rdquoempFormrdquo type=rdquocomfficexamplestrutsEmployeeFormrdquo gt ltform-beansgtltaction-mappingsgtltaction path=rdquovalidateEmployeerdquo

type=rdquocomfficexamplestrutsValidateEmployeeActionrdquo name=rdquoempFormrdquo scope=rdquorequestrdquo input=rdquoInputContentjsprdquogt

ltforward name=rdquosuccessrdquo path=rdquoOutputContentjsprdquo gt ltactiongtltaction-mappingsgtltstruts-configgt

2 Open the webxml file and replace the contents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquoldquohttpjavasuncomdtdweb-app_2_3dtdrdquogtltweb-appgt

80

ltweb-appgt

Note This file is basically an empty file but we still need to provide this becausethe ActionServlet still looks for it somehow If it canrsquot find the file it throws aMalformedURLException exception

3 In the same directory create a file named apptld and paste the following code

ltxml version=rdquo10rdquo encoding=rdquoUTF-8rdquogtltDOCTYPE taglib PUBLIC ldquo-Sun Microsystems IncDTD JSP Tag Library 11ENrdquoldquohttpjavasuncomj2eedtdsweb-jsptaglibrary_1_1dtdrdquogtlttaglibgtlttlibversiongt10lttlibversiongtltjspversiongt11ltjspversiongtltshortnamegtUserltshortnamegtltinfogtThis tag library contains employee tag extensionsltinfogt

lttaggtltnamegtdepartmentListltnamegtlttagclassgtcomfficexamplestrutsDepartmentTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaggt

ltnamegtskillsListltnamegtlttagclassgtcomfficexamplestrutsSkillsTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggtlttaglibgt

4 In VAJ create a project named STRUTS EXAMPLE Create a file namedApplicationResourcesproperties save it in a temporary folder and paste thecodes below in it Add it to the project that you just created (To do this click on theResources tab then right-click on the STRUTS EXAMPLE project and selectAddResource then look for the ApplicationResourceproperties file you just createdand click OK)

errormissingname=ltligtltfont colors ldquoredrdquogtPlease Enter the first nameltfontgtltligterrormissingdepartment=ltligtltfont colors ldquoredrdquogtPlease pick a departmentnameltfontgtltligterrormissingskills=ltligtltfont colors ldquoredrdquogtPlease select the relevant skillsltfontgtltligtpromptemployeename=ltbgtFirst Name ltbgtpromptemployeedepartment=ltbgtDepartment ltbgtpromptemployeeskills=ltbgtSkills ltbgt

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

81

5 Open the craftwebapp file located in eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft and replace the contents with the followingcode

ltxml version=rdquo10rdquogtltwebappgt

ltnamegtcraftltnamegtltdescriptiongtcraft Applicationltdescriptiongtlterror-pagegtErrorReporterlterror-pagegtltservletgt

ltnamegtErrorReporterltnamegtltdescriptiongtDefault error reporter servletltdescriptiongtltcodegtcomibmservletenginewebappDefaultErrorReporterltcodegtltservlet-pathgtErrorReporterltservlet-pathgtltautostartgttrueltautostartgtltservletgt

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegtltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgtltinit-parametergt ltnamegtapplicationltnamegt

ltvaluegtApplicationResourcesltvaluegt ltinit-parametergt ltinit-parametergt

ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdebugltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtdetailltnamegt ltvaluegt2ltvaluegt

ltinit-parametergt ltinit-parametergt

ltnamegtvalidateltnamegt ltvaluegttrueltvaluegt

ltinit-parametergtltservletgt

ltservletgtltnamegtinvokerltnamegt

82

ltdescriptiongtAuto-registration servletltdescriptiongtltcodegtcomibmservletenginewebappInvokerServletltcodegtltservlet-pathgtservletltservlet-pathgtltautostartgttrueltautostartgt

ltservletgtltservletgt

ltnamegtjspltnamegtltdescriptiongtJSP support servletltdescriptiongtltcodegtcomibmivjjspjasperruntimeJspDebugServletltcodegtltinit-parametergt

ltnamegtworkingDirltnamegtltvaluegt$server_root$tempdefault_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtjspemEnabledltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtscratchdirltnamegtltvaluegt$server_root$tempJSP1_1default_appltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtkeepgeneratedltnamegtltvaluegttrueltvaluegt

ltinit-parametergtltautostartgttrueltautostartgtltservlet-pathgtjspltservlet-pathgt

ltservletgtltservletgt

ltnamegtfileltnamegtltdescriptiongtFile serving servletltdescriptiongtltcodegtcomibmservletenginewebappSimpleFileServletltcodegtltservlet-pathgtltservlet-pathgtltinit-parametergt

ltnamegtltnamegtltvaluegtltvaluegt

ltinit-parametergtltinit-parametergt

ltnamegtdefaultpageltnamegtltvaluegtindexhtmlltvaluegt

ltinit-parametergt

ltautostartgttrueltautostartgtltservletgt

ltwebappgt

6 In VAJ create a project named STRUTS EXAMPLE and in it create a packagenamed comfficexamplestruts then create a class named EmployeeForm andpaste the following code in

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

83

Insert the typersquos description hereCreation date (1802 10946 PM)author Administrator import orgapachestrutsactionActionFormimport orgapachestrutsvalidatorValidatorForm

public class EmployeeForm extends ActionForm

private String name = ldquordquoprivate String department = ldquordquoprivate String[] skills

EmployeeForm constructor comment public EmployeeForm()

super()

public String getDepartment() return department public String getName() return name public String[] getSkills() return skills public void setDepartment(String department) thisdepartment = department public void setName(String name) thisname = name public void setSkills(String[] skills) thisskills = skills

7 In the same package create a class named DepartmentTag and paste the followingcode

84

Insert the typersquos description hereCreation date (1802 11513 PM)author Administrator

import javautilListimport javautilArrayListimport javaxservletjsptagextTagSupport public class DepartmentTag extends TagSupport

DepartmentTag constructor comment public DepartmentTag()

super()

public int doStartTag() List department = new ArrayList()departmentadd(ldquordquo)departmentadd(ldquoClient Serverrdquo)departmentadd(ldquoLegacyrdquo)departmentadd(ldquoEmerging Techrdquo)departmentadd(ldquoTech Supportrdquo)

pageContextsetAttribute(ldquodepartmentListrdquodepartment)return SKIP_BODY

8 Create a class named SkillsTag and paste the following code

Insert the typersquos description hereCreation date (1802 11910 PM)author Administrator import javautilimport javaxservletjsptagextTagSupport

public class SkillsTag extends TagSupport

SkillsTag constructor comment

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

85

public SkillsTag()

super()public int doStartTag()

List skills = new ArrayList()

skillsadd(ldquoEJBrdquo)skillsadd(ldquoJava Mailrdquo)skillsadd(ldquoJSPrdquo)skillsadd(ldquoHTMLrdquo)skillsadd(ldquoCOBOLrdquo)skillsadd(ldquoCICSrdquo)skillsadd(ldquoCrdquo)

pageContextsetAttribute(ldquoskillsListrdquoskills)return SKIP_BODY

9 Create a class named ValidateEmployeeAction and paste the following code

Insert the typersquos description hereCreation date (1802 125818 PM)author Administrator

import orgapachestrutsactionActionFormimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

86

public class ValidateEmployeeAction extends orgapachestrutsactionAction

ValidateEmployeeAction constructor comment public ValidateEmployeeAction()

super()

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

throws IOExceptionServletException ActionErrors errors = new ActionErrors()EmployeeForm empForm = (EmployeeForm) form

String name = empFormgetName()if(nametrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingnamerdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String department = empFormgetDepartment()if(departmenttrim()equals(ldquordquo))

ActionError error = new ActionError(ldquoerrormissingdepartmentrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

String[] skills = empFormgetSkills()if(skills == null)

ActionError error = new ActionError(ldquoerrormissingskillsrdquo)errorsadd(ActionErrorsGLOBAL_ERRORerror)

if(errorssize() gt 0)

saveErrors(requesterrors)return new ActionForward(mappinggetInput())

return mappingfindForward(ldquosuccessrdquo)

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

87

10 In eappsprogram filesibmVisualAge for Javaideproject resourcesIBMWebSphere Test Environmenthostsdefault_hostcraft create a file namedInputContentjsp and paste the following 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-INFapptld prefix=app gtlthtmlgt

ltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgtlthtmltext property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogtlttdgtlttdgtlthtmlselect property=rdquodepartmentrdquogtlthtmloptions name=rdquodepartmentListrdquogtlthtmlselectgtlttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogtltbeanmessage key=rdquopromptemployeeskillsrdquogtlttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoskillsListrdquogtlthtmlmultibox property=rdquoskillsrdquogtlt= currentSkill gtlthtmlmultiboxgtlt= currentSkill gt

88

ltbr gtltlogiciterategtlttdgtlttrgtlttrgtlttd colspan=rdquo2rdquo align=rdquocenterrdquogtlthtmlsubmit value=rdquoValidaterdquogtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

11 In the same folder create a file named OutputContentjsp and paste the followingcode

lttaglib uri=WEB-INFstruts-beantld prefix=bean gtlttaglib uri=WEB-INFstruts-htmltld prefix=html gtlttaglib uri=WEB-INFstruts-logictld prefix=logic gtlttaglib uri=WEB-INFapptld prefix=app gt

lthtmlgtltheadgtlttitlegtlttitlegtltheadgt

ltbodygtlthtmlerrorsgtltappdepartmentListgtltappskillsListgtlthtmlform action=rdquovalidateEmployeedordquogt

lttablegtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeenamerdquogtlttdgtlttdgt

ltbeanwrite name=rdquoempFormrdquo property=rdquonamerdquogtlttdgt

lttrgtlttrgt

lttd align=rdquorightrdquogtltbeanmessage key=rdquopromptemployeedepartmentrdquogt

lttdgt

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

89

lttdgt ltbeanwrite name=rdquoempFormrdquo property=rdquodepartmentrdquogt

lttdgtlttrgtlttrgtlttd align=rdquorightrdquo valign=rdquotoprdquogt

ltbeanmessage key=rdquopromptemployeeskillsrdquogt

lttdgtlttdgtltlogiciterate id=rdquocurrentSkillrdquo name=rdquoempFormrdquo property=rdquoskillsrdquogt

lt= currentSkill gtltbrgt

ltlogiciterategtlttdgtlttrgt

lttablegtlthtmlformgtlthtmlgt

12 Just to make sure that you have the craft application correctly configure make surethat the file defaultservlet_engine located in eappsprogram filesibmVisualAgefor Javaideproject resourcesIBM WebSphere Test Environmentpropertiescontains the following entry

ltwebsphere-webgroup name=rdquocraftrdquogtltdescriptiongtCRAFT Webgroupltdescriptiongtltdocument-rootgt$approot$ltdocument-rootgtltclasspathgt$approot$ltclasspathgtltroot-urigtcraftltroot-urigtltauto-reload enabled=rdquotruerdquo polling-interval=rdquo3000rdquogtltshared-contextgtfalseltshared-contextgt

ltwebsphere-webgroupgt

13 In the end the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstrutsmdashconfigxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtld

90

struts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd|_ classes

Deploying and running the sample application1 Bring up the WebSphere Test Environment then click on Edit Class Path

click Select All enter the following text in the extra classpath area

EAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INFclassesEAppsProgram FilesIbmVisualAge for Javaideproject_resourcesIBM WebpshereTest Environmenthostsdefault_hostcraftWEB-INF

click OK

2 Start the servlet engine

3 Once the servlet engine is started

bring up a browser enter the following URL httplocalhost8080craftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

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

91

Enter stuff in it and press Validate and

92

Lesson 14 - Installing Struts 11b in ORIONThis lesson walks you through the installation of Struts 11b in the Orion webserver Aswith the WebSphere installation you need to go through Lesson 1 to prepare yourenvironment Installation of the sample application relies heavily on the instructions inLesson 12 so it is assumed that you have already gone through that lesson Otherwisefollow the instructions for Installing the sample application in Lesson 12 to create thenecessary components

Installation and configuration1 Downloadinstall the following

Xerces from httpxmlapacheorgdistxerces-j the link is Xerces-J-bin144zip extract the Xercesjar file and save it in EORIONservletscraftWEB-INFlib

Xalan from httpxmlapacheorgxalan-jindexhtml the link is xalan-j_2_3_1-binzip extract Xalanjar and xml-apisjar save them in EORIONservletscraftWEB-

INFlib

Struts 11b binary from httpjakartaapacheorgbuildsjakarta-strutsreleasev11-b1 link is jakarta-struts-11-b1zip extract Strutsjar and save it in EORIONservletscraftWEB-INFlib

Struts commons (binary)The latest commons libraries are in httpjakartaapacheorgbuildsjakarta-commonsrelease

Download all commons zip files and save the commons-jar files toEORIONservletscraftWEB-INFlib

OR

Open the binary distribution of STRUTS and extract all commons jar files and save themin

eORIONservletscraftWEB-INFlib

2 Open jakarta-struts-11-b1zip and extract the following files toeORIONservletscraftWEB-INF

struts-tld ndash dtd ndash xml

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

93

note the DTDs in this folder are for reference only Struts uses an internal copyof the dtdrsquos to validate the xml files

Installing the sample applicationThese steps will walk you through the creation installation and testing of a smallapplication that runs on Struts It is the same example in Chapter 18 of Beginning JSPWeb Development published by Wrox (Irsquoll provide my own later)

1 Copy the file struts-configxml from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftWEB-INF toeORIONservletscraftWEB-INF

2 Open the webxml file in eORIONservletscraftWEB-INF and replace thecontents with the following code

ltxml version=rdquo10rdquogtltDOCTYPE web-app PUBLIC ldquo-Sun Microsystems IncDTD Web Application 23ENrdquo

ldquohttpjavasuncomj2eedtdsweb-app_2_3dtdrdquogt

ltweb-appgtltservletgt

ltservlet-namegtactionltservlet-namegtltservlet-classgtorgapachestrutsactionActionServletltservlet-classgtltinit-paramgt

ltparam-namegtapplicationltparam-namegtltparam-valuegtApplicationResourcesltparam-valuegt

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgtltservlet-mappinggt

ltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggtlttaglibgtlttaglib-urigtbeanlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-beantldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigthtmllttaglib-urigt

94

lttaglib-locationgtWEB-INFstruts-htmltldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtformlttaglib-urigt

lttaglib-locationgtWEB-INFstruts-formtldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigtlogiclttaglib-urigt

lttaglib-locationgtWEB-INFstruts-logictldlttaglib-locationgtlttaglibgt

lttaglibgtlttaglib-urigttemplatelttaglib-urigtlttaglib-locationgtWEB-INFstruts-templatetldlttaglib-locationgtlttaglibgtlttaglibgt

lttaglib-urigtapplttaglib-urigtlttaglib-locationgtWEB-INFapptldlttaglib-locationgt

lttaglibgtltweb-appgt

3 Copy the file apptld from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraftWEB-INF

4 Copy the file ApplicationResourcesproperties from eappsprogramfilesibmVisualAge for Javaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraftcomfficfincraftresource toeORIONservletscraftWEB-INFclasses

5 From VAJ export the class named EmployeeForm to

eORIONservletscraftWEB-INFclasses

Note the classes will be exported to the corresponding directory structurecomfficexamplestruts

6 From VAJ export the class named DepartmentTag toeORIONservletscraftWEB-INFclasses

7 From VAJ export the class named SkillsTag to eORIONservletscraftWEB-INFclasses

8 From VAJ export the class named ValidateEmployeeAction toeORIONservletscraftWEB-INFclasses

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

95

9 Copy the file InputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

10 Copy the file OutputContentjsp from eappsprogram filesibmVisualAge forJavaideproject resourcesIBM WebSphere TestEnvironmenthostsdefault_hostcraft to eORIONservletscraft

11 Upon completion the craft directory structure should look something like this

craft|_WEB-INF

apptldstruts-beantldstruts-configxmlstruts-config_1_0dtdstruts-config_1_1dtdstruts-htmltldstruts-logictldstruts-nestedtldstruts-templatetldtilestldtiles-configdtdwebxmlweb-app_2_2dtdweb-app_2_3dtd

|_ classesApplicationResourcesproperties|_com

|_ffic|_example

|_strutsValidateEmployeeActionclassDepartmentTagclassSkillsTagclassEmployeeFormclass

|_libstrutsjarXercesjarXalanjarxml-apisjartilesjarcommons-validatorjarcommons-servicesjarcommons-pooljar

96

commons-loggingjarcommons-digesterjarcommons-dbcpjarcommons-collectionsjarcommons-beanutilsjar

Deploying and running the sample application1 Start ORION (eorionjava -jar orionjar)

2 Once the ORION is started

bring up a browser enter the following URL

httplocalhostcraftInputContentjsp

ResultYou should see the following on your browser (thatrsquos if everything went fine)

Enter stuff in it and press Validate and the output should look something like the nextscreen

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

97

98

Lesson 15 - Struts ComponentsHere is a more detailed discussion on the commonly used classestaglibs in the Strutsframework To learn Struts I strongly suggest that you read this document a number oftimes revisit the example application andor hack it and most important of all ask lots ofquestions It takes more than just this document to help you understand and work withthe struts framework The last part of this document lists some very useful struts-relatedURLs that can supplement what yoursquove learned so far

Struts ComponentsThe classes described below are part of the Struts distribution package which youdownloaded in Lesson 13 In VAJ these are in the STRUTS project They may also befound in the strutsjar file that came with the binary distribution of struts

ActionServlet (orgapachestrutsactionActionServlet)

This class extends HttpServlet and is the only servlet in the Struts framework

Itrsquos main responsibilities are

receive request from the browser automatically populate any associated javabeans (ActionForms) with data from the

browser determine the class (Action) that will process the request receives notice of completion from the Action class to do either a a server-side or

client-side redirect

To configure the ActionServlet we need to enter information about this servlet in theapplication deployment descriptor just like any other servlets

In webxml (ORION)

ltservletgtltservlet-namegtactionltservlet-namegtltservlet-classgt

orgapachestrutsactionActionServletltservlet-classgt

This line tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-paramgtltparam-namegtapplicationltparam-namegtltparam-valuegt

ApplicationResourcesltparam-valuegt

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

99

ltinit-paramgtltload-on-startupgt2ltload-on-startupgt

ltservletgt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-mappinggtltservlet-namegtactionltservlet-namegtlturl-patterngtdolturl-patterngt

ltservlet-mappinggt

In craftwebapp (VAJWebSphere Test Environment)

ltservletgtltnamegtactionltnamegtltdescriptiongtAction ServletltdescriptiongtltcodegtorgapachestrutsactionActionServletltcodegt

This tells the webserver that any URL request ending in a do will be processedby the ActionServlet

ltservlet-pathgtdoltservlet-pathgtltautostartgttrueltautostartgt

This tells the ActionServlet where to look for message keyvalue pairs forpromptsmessages

ltinit-parametergt ltnamegtapplicationltnamegt ltvaluegt

ApplicationResourcesltvaluegt ltinit-parametergt

This tells the ActionServlet where to look for mapping information(ActionActionForm definitions)

ltinit-parametergt ltnamegtconfigltnamegt ltvaluegtWEB-INFstruts-configxmlltvaluegt

ltinit-parametergt ltservletgt

Yoursquoll notice that we sometimes override some initialization parameters for theActionServlet with our own values For a complete list of initialization parameters youcan go the jakartaapachecomstruts website For our purpose of building a simplestruts-based application these initialization parameters will suffice

100

ActionForm (orgapachestrutsactionActionForm)

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

public class DivisionBean extends orgapachestrutsactionActionForm

place your settersgetters etc here

Enter the form information in the struts-configxml file using ltform-beangt tags

ltform-beansgtltform-bean name=rdquoDivisionFormrdquo type=rdquocomffictrainingDivisionBeanrdquo gt

ltform-beansgt

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

ltaction-mappingsgtltaction path=rdquovalidateDivisionrdquo

type=rdquocomfficexamplestrutsValidateDivisionrdquoname=rdquoDivisionFormrdquoscope=rdquorequestrdquoinput=rdquoInputjsprdquogtltforward name=rdquosuccessrdquo path=rdquoDisplayDivisionjsprdquogt

ltactiongtltaction-mappingsgt

Action (orgapachestrutsactionAction)

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)

250

Complete code (comffictrainingLoginAction)

import orgapachestrutsactionimport orgapachestrutsvalidator

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

public class LoginAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws IOExceptionServletException

ActionErrors errors = new ActionErrors()

try

errors = ((DynaValidatorForm)form)validate(mappingrequest)if (errorsempty())

saveErrors(request errors) return new ActionForward(mappinggetInput())

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

251

5 We then need to define new validation rules for the dynamic form Open the filevalidationxml located in craftWEB-INF and add the following entries within theltformsetgt tags

ltform name=logonFormgtltfield property=userId depends=requiredgt

ltarg0 key=promptloginusergtltfieldgtltfield property=password depends=requiredmaskgt

ltarg0 key=promptloginpasswordgtltvargt

ltvar-namegtmaskltvar-namegtltvar-valuegt^[a-zA-Z]$ltvar-valuegt

ltvargtltfieldgt

ltformgt

The rules are the same as the entry for loginForm except that we donrsquot force the user to enter avalid email address in the userId field This tells us that this rule is what gets read when we validatethe login information in the DynaValidatorForm

Deploying the code (Part 2 ndash DynaValidatorForm 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

Result (Part 2 ndash DynaValidatorForm example)The result should look like the following screens below

The login form

252

Submitting the form without any data will result in the following screen

Entering a userid and an alphanumeric password will result in 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

253

Entering a userid and an alpha password will navigate the user to the welcome page

Since the user was not required to enter a valid email address for the userid we can besure that the new process is whatrsquos working behind the scenes to contain form data usingthe DynaValidatorForm and to perform the validation using struts-validator

254

Lesson 28 ndash Using tokensBasics A highly recommended way of keeping our transactions in synch is the use of tokens Atoken is a random number that gets stored in the users session a copy of which issupposed to be stored in the request If the session and request tokens are missing orare different then the transaction is out of synch To illustrate this if we have a processthat adds a record to a database using a jsp and an action class The user aftersubmitting the form and getting the confirmation that the record was successfully addedmay click on the dreaded BACK button and navigate back to the data entry screen andclick the SUBMIT button again to add the same record As a rule of thumb it is not safeto assume that users will follow instructions all the time ndash most will but there are a fewgremlins out there who will want to play around with the application We want to design asystem that deals with this type of situation The simplest way to address this is to use atoken that gets created when the entry form is displayed for the first time and theninvalidatedreset after the successful completion of the operation If the user tries to goback to the data entry screen the token will no longer be valid since it has already beenreset and therefore we can navigate the user to an error page where he canrsquot hurt himselfor the application

CodingInstead of creating a new process we will use the existing edit function to demonstratethe use of tokens in Struts

The flow of the new edit process will be as follows

Displayjsp will display all Division items Clicking on the ldquoeditrdquo link will invoke DivisionActionrsquos edit() method which will bring up

an edit page containing the selected Division item At this point a token will begenerated

The user makes changes to the division descripition (or not) and submits the formThe DivisionActionrsquos update() method will then be invoked In this method the tokenwill be validated and if valid the update will occur Otherwise the user will be thrownto the login page with the corresponding error message

1 In VAJ make the following changes to the edit() and update() methods of theDivisionAction class and the execute() method of the FindDivisionAction class

Add the following line of code within the try block just before returning an ActionForward

saveToken(request)

This code puts the token in the request which will be written in the output jsp as a hiddenfield inside the lthtmlformgt 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

255

2 Next is to make changes to the update() method of the DivisionAction class tovalidate the token and make the necessary decisions

In the try block change the following lines of code

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

to

if (isTokenValid(request))

resetToken(request)

DivisionBean divisionBean = (DivisionBean) form

DivisionBO divisionBO = new DivisionBO()divisionBOupdate(divisionBean)

return mappingfindForward(success)

else

ActionError error = new ActionError(errorduplicatesubmit)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

3 Since we created a new key for an error message in the previous step we need tomake an entry in the ApplicationResourcesproperties to assign a value to thiskey Add the following line of code in the ApplicationResourcesproperties file

errorduplicatesubmit=ltbgtltfont color=redgtDuplicate page submission session has beeninvalidate Please log in againltfontgtltbgt

4 There is also a new forward named loginpage in the update() method so add aforward named loginpage for the DivisionAction action-mapping entry in struts-configxml that maps to the login jsp

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

256

ltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

We have completed the coding changes at this point so letrsquos 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 Click on the Display Division link

ResultTo test out the use of the token just follow the screen sequence below

The list of division items will be displayed initially

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

257

Select an item to bring up an edit screen

258

After submitting the edit form the items will be redisplayed

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

259

Clickin on the browserrsquos back button will cause the screen to navigate back to the editpage

Since the token was already reset submitting that same form will trigger an exceptionand the screen will navigate to the login page with the corresponding error message

260

Lesson 29 ndash Implementing security in StrutsBasics

First some definitions

Authentication is the process by which a user submits a set of credentials to theapplication which then checks if the submitted credentials match those that are keptinternally

Authorization is the process of determining if a user authenticated or not is able toaccess a protected resource

J2EE standards provide for container-managed authentication and authorization usingentries in the application deployment descriptor (the deployment descriptor would be thecraftwebapp in VAJ and webxml in ORION) If you are not familiar with and want tolearn about configuring container-managed security form-based authentication inparticular go to this url for an overview ==gthttpwwwonjavacompubaonjava20010806webformhtml The implementation ofcontainer-managed security varies from webserver to webserver and we thereforecannot cover this in our lesson We however will be implementing the authenticationpiece using Policy Director (PD) which uses an LDAP to retrieve user infoauthorizationparameters We will then handle the implementation of the authorization piece withinStruts

Lets look at how our application will interact with PD to authenticate users

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

261

From the diagram above we can retrive the information from the HttpRequestrsquos headerusing the following codes

To retrieve the user name

String user = (String)reqgetHeader(IvUserHeaderKey)

To retrieve the groups to which the user is associated

String groups = reqgetHeader(IvGroupsHeaderKey)

Note that groups is defined as a String instead of a collection This is because theinformation retrieved from the header is a comma-delimited string so we need to providea convenience method to parse this information and place them in a collection

Upon successful authentication we need to save the user information off to a sessionobject so we can access this information anywhere within the application We then needto design a security framework around our application that will provide authorizationservices As mentioned before PD will provide the authentication service for ourapplication

Declarative security

Declarative security provides for setting security parameters outside the applicationcodes usually in an xml file the advantage of which is there is no need to recompile anyof the source codes to effect new security rules

Struts does not (yet) provide for declarative security and for good reason The frameworkneeds to be independent of any type of implementation for authenticationauthorizationfor the purpose of portability While it does not provide declarative security it does haveprovisions which enables developers to quickly develop their own mechanism fordeclarative security The next section will walk you through the steps in creating a simplebut effective security framework in Struts

Coding (Part 1 ndash protecting do classes)In this section we will create an abstract action class wersquoll call it BaseAction that willperform the necessary security checks This way we only have one place to make achange in case we need to enhance the code This class will then be extended by allother action classes

262

Below is a diagram that represents how our example application will look like at the endof this section

1 A ltset-propertygt tag can be used to define arbitrary parameters that will be passedto the action class using the ActionMapping object We will take advantage of thisfeature to declare our own security parameter In the struts-configxml file add thefollowing tag to the action classes that need to be protected

ltset-property property=isSecure value=true gt

Add this tag to the entries for the LoginAction DivisionAction and FindDivisionActionclasses

ltaction path=login type=comffictrainingLoginAction name=logonForm scope=requestinput=Loginjspgt

ltset-property property=isSecure value=falsegtltforward name=success path=welcomepagegt

ltactiongt

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

263

ltaction path=adminDiv type=comffictrainingDivisionAction scope=request name=divFormparameter=method input=diveditpagegt

ltset-property property=secure value=truegt ltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=searchpage path=divsearchpagegtltforward name=success path=adminDivdomethod=viewgtltforward name=displaypage path=divdisplaypagegtltforward name=loginpage path=Loginjspgt

ltactiongt

ltaction path=findDiv type=comffictrainingFindDivisionAction name=srchFormscope=request input=diveditpagegt

ltset-property property=secure value=truegtltexception key=errordivisionnotfound type=comffictrainingFindException

path=divsearchpagegtltexception key=errordivisionnotnumber type=javalangNumberFormatException

path=divsearchpagegtltforward name=editpage path=diveditpagegtltforward name=loginpage path=Loginjspgt

ltactiongt

Note The parameter we defined above will cause Struts to invoke the setIsSecure() method ofthe ActionMapping object

2 To make sure that Struts reads the parameter we defined in the previous step weneed to define a variable in subclass of the ActionMapping class with thecorresponding accessorsmutators Create a subclass oforgapachestrutsactionActionMapping named FFICActionMapping in thepackage comffictraining

public class FFICActionMapping extends orgapachestrutsactionActionMapping

Declare a private variable for the parameter

private boolean isSecure = false

Define the settergetter that corresponds with the property attribute in the ltset-propertygt tag

public boolean getIsSecure() return isSecure

public void setIsSecure(boolean secure)

264

thisisSecure = isSecure

Complete code (comffictrainingFFICActionMapping)

Insert the types description here Creation date (6302 24414 PM) author Administrator public class FFICActionMapping extends orgapachestrutsactionActionMapping

private boolean secure = false

Construct a new instance of this class with the desired default form bean scope public FFICActionMapping()

super()

Insert the methods description here Creation date (6302 24740 PM) return boolean public boolean getSecure()

return secure Insert the methods description here Creation date (6302 24717 PM) param secure boolean public void setSecure(boolean secure)

thissecure = secureSystemoutprintln(security indicator set)

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

265

3 Now that weve can set security parameters in our config we need to create anaction class that uses this parameter To centralize the code for this create aabstract class named BaseAction which extends orgapachestrutsactionActionThis class will contain the logic that checks if an action class requires a user to belogged-in If so it then checks if the user is already logged in before it runs theexecuteAction() method of its subclass

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

The execute() method receives the FFICActionMapping object and we cast it here

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

Check if this action class requires the user to be logged-in based on the isSecurevariables value

if (requiresLogin(mapping1))

If log-in is required invoke a method that checks for the presence of the userKeyattribute in the session

if (isUserLoggedIn(request))

Execute the subclasss executeAction() method if user is logged-in

return executeAction(mapping1formrequestresponse)

else

If the user has not been authenticated create an ActionError object with thecorresponding error key and forward the user back to the login page

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

266

else

If no authentication is required that is if the isSecure parameter is not coded in theactionmapping invoke the subclass executeAction() method

return executeAction(mapping1formrequestresponse)

Create an unimplemented executeAction() method which will be implemented bysubclasses of BaseAction

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

This method checks if the user is logged-in to the application

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

This method retrieves the actions isSecure parameter to check if log-in is required

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

Complete code (comffictrainingBaseAction)

package comffictraining

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

267

import orgapachestrutsactionActionimport orgapachestrutsactionActionFormimport orgapachestrutsactionActionErrorsimport orgapachestrutsactionActionErrorimport orgapachestrutsactionActionForwardimport orgapachestrutsactionActionMappingimport orgapachestrutsactionActionServlet

import javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponseimport javaxservlethttpHttpSessionimport javaxservletServletException

import javaioIOExceptionimport javautilListimport javaio

abstract class BaseAction extends orgapachestrutsactionAction

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest requestHttpServletResponse response)throws Exception

FFICActionMapping mapping1 = (FFICActionMapping) mapping

ActionErrors errors = new ActionErrors()

if (requiresLogin(mapping1))

Systemoutprintln(log-in required)

if (isUserLoggedIn(request))

return executeAction(mapping1formrequestresponse)

else

ActionError error = new ActionError(errorusernotauthenticated)errorsadd(ActionErrorsGLOBAL_ERROR error)saveErrors(request errors)

return mappingfindForward(loginpage)

268

else

return executeAction(mapping1formrequestresponse)

protected ActionForward executeAction(FFICActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception

return null

public boolean isUserLoggedIn(HttpServletRequest request)

HttpSession session = requestgetSession()

if (sessiongetAttribute(userKey) == null || session == null) return false

else return true

public boolean requiresLogin(FFICActionMapping mapping1)

return mapping1getSecure()

4 Revise all the action classes - extend BaseAction instead of orgapachestrutsactionAction- change the signature of the execute() method

from

public ActionForward execute(ActionMapping mapping ActionFormform

HttpServletRequest requestHttpServletResponse response)

to

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

269

public ActionForward executeAction(FFICActionMapping mappingActionForm form

HttpServletRequest requestHttpServletResponse response)

So far we have the following action classes to change

FindDivisionAction LoginAction

5 The DispatchAction class which we discussed in previous lessons also needs toextend the BaseAction class to be able to implement the security framework

create a copy of orgapachestrutsactionDispatchAction which extendsBaseAction instead of Action in the package comffictraining

change the signature of comffictrainingDispatchActions execute() method

from

public ActionForward execute(ActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

to

public ActionForward executeAction(FFICActionMapping mappingActionForm formHttpServletRequest requestHttpServletResponse response)

6 Change the DivisionAction class that extendsorgapachestrutsactionDispatchAction to extend the newcomffictrainingDispatchAction

public class DivisionAction extends comffictrainingDispatchAction

7 Revise the LoginAction class to save the user information to a session objectnamed userKey This assumes that the user has been successfully authenticatedby PD and that our code has retrieved the user information from the HttpRequestrsquosheader

requestgetSession()setAttribute(userKey((DynaValidatorForm)form)get(userId))

8 Create a new entry in the ApplicationResourcesproperties file for the followingkeyvalue pair

270

errorusernotauthenticated=ltbgtltfont color=redgtYou have not been properlyauthenticatedplease log inltfontgtltbgt

9 Create the class LogoutAction in the package comffictraining so we caninvalidate the session and later on test the security framework

Create a regular action class

public class LogoutAction extends orgapachestrutsactionAction

In the execute() method just invalidate the session and forward the user to the loginpage

public ActionForward execute(ActionMapping mapping ActionForm formHttpServletRequest request HttpServletResponse response)

throws Exception ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

Complete code (comffictrainingLogoutAction)

import orgapachestrutsaction

import javaxservlethttpHttpServletimport javaxservlethttpHttpServletRequestimport javaxservlethttpHttpServletResponse

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

271

import javaxservletServletException

import javaioIOException

import javasqlConnectionimport javasqlSQLException

import javautilCollection

Insert the types description here Creation date (12202 92827 AM) author Administrator public class LogoutAction extends orgapachestrutsactionAction LogoutAction constructor comment public LogoutAction()

super() Insert the methods description here Creation date (12202 94602 AM) return orgapachestrutsactionActionForward public ActionForward execute(ActionMapping mapping ActionForm form

HttpServletRequest request HttpServletResponse response)throws Exception

ActionErrors errors = new ActionErrors()

try

requestgetSession()invalidate()

return mappingfindForward(logoutpage)

catch (Throwable e) eprintStackTrace()ActionError error = new ActionError(egetMessage())errorsadd(ActionErrorsGLOBAL_ERROR error)

saveErrors(request errors)return new ActionForward(mappinggetInput())

272

10 Create an entry for the LogoutAction in struts-configxml

ltaction path=logout type=comffictrainingLogoutAction scope=request input=Loginjspgtltforward name=logoutpage path=logoutpagegt

ltactiongt

11 Create LogoutContentjsp in the craft folder

lttable width=100 height=100gtlttrgt lttd valign=center align=centergt lth2gtYou have been logged off lth2gt lttdgtlttrgtlttablegt

12 Open the file tilesDefinitionxml in craftWEB-INF and create a new definition forthe logout page

lt-- Extended definition for account display --gtltdefinition name=logoutpage extends=welcomepagegt

ltput name=body content=LogoutContentjspgtltdefinitiongt

13 Add a line in the menu-configxml for a link to the logout action class (in bold)

ltMenu name=MainMenu title=MainMenu gtltItem 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 gtltItem name=LogOut title=Log Out location=logoutdo gt

ltMenugt

14 Change the TileTemplatejsp in craft to include code that checks for the presence of theuserKey attribute to correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logic 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

273

Encapsulate the menu with logic tags that check for the presence of the userKey session attribute

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

Complete Code (TileTemplatejsp)

lt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFtilestld prefix=tiles gtlt taglib uri=WEB-INFstruts-logictld prefix=logic gt

ltHTMLgtltHEADgtltTITLEgtFiremans Fund Insurance CRAFTltTITLEgt

ltHEADgt

ltBODYgt ltscript language=JavaScript12 src=scriptscoolmenus3jsgtltscriptgtltscript src=scriptscoolmenu-configjsgtltscriptgt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=CoolMenubundle=orgapachestrutsactionMESSAGEgt ltmenudisplayMenu name=MainMenu gtltmenuuseMenuDisplayergtltlogicpresentgt

lttable width=100 border=0gt lttrgt lttd bgcolor=graygtltdiv align=centergtlth1gtMy Applicationlth1gtltdivgt lttdgt lttrgtlttablegt

lttable width=100 height=75 border=0gt

274

lttrgt lttd width=10 align=right valign=top bgcolor=ABABABgt

lttilesinsert attribute=menu gt

lttdgt lttd width=90 valign=center align=centergt

lttilesinsert name=bodygt lttdgt lttrgtlttablegt

lttable width=100 border=0gt lttrgt lttdgtltdiv align=centergt

ltfont size=-1gtCopyright 2002ltfontgtltdivgt

lttdgt lttrgtlttablegt

15 Change the Menujsp to include code that checks for the presence of the userKey attributeto correctly display the menu options

Add the directive for the logic taglib

lt taglib uri=WEB-INFstruts-logictld prefix=logicgt

Encapsulate the menu with logic tags that check for the presence of the userKey sessionattribute

ltlogicpresent name=userKeygt

ltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

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

275

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

Add the following codes that provides a link to the log-in page Encapsulate this code withlogic tags that make the link appear only if the userKey is not present

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

Complete Code (Menujsp)

lt taglib uri=WEB-INFstruts-htmltld prefix=html gtlt taglib uri=WEB-INFstruts-menutld prefix=menugtlt taglib uri=WEB-INFstruts-logictld prefix=logicgt

lthtmlgtltheadgtltheadgtltbodygt

ltlogicpresent name=userKeygtltmenuuseMenuDisplayer name=Simplerepository=comfgmwebmenuMENU_REPOSITORY gt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt

276

ltmenuuseMenuDisplayergt

ltmenuuseMenuDisplayer name=DropDownrepository=comfgmwebmenuMENU_REPOSITORYgt lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt ltmenudisplayMenu name=MainMenugt lttdgtlttrgt lttablegt ltmenuuseMenuDisplayergt

ltbrgtltpgtltbrgtltpgtltbrgtltpgt

ltlogicpresentgt

ltlogicnotPresent name=userKeygt

lttable cellpadding=3 cellspacing=3gt lttrgtlttdgt lta href=LoginjspgtLog Inltagt lttdgtlttrgt lttablegt

ltlogicnotPresentgt

ltbodygtlthtmlgt

Deploying the code (Part 1 ndash protecting do classes)

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

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

277

Result (Part 1 ndash protecting do classes)The login screen

The welcome page now shows a ldquoLog Outrdquo link which invalidates the session

278

Clicking on the ldquoDisplay Divisionrdquo link displays the division items as before No errors atthis point since the user was successfully authenticated during login

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

279

Clicking on the ldquoLog Outrdquo link will navigate the user to the page below It shows the ldquoLogInrdquo link which navigates the user to the login page when clicked

If instead of logging back in the user types a url(httplocalhost8080craftadminDivdomethod=view) on the address line (or uses abookmark) the application will determine that the user has not been authenticated andwill then be navigated to the login page which displays an error message

280

OK now we can prevent those gremlins from bookmarking our applicationrsquos urls Wehave one more thing to do though there are urls that map directly to our jsp pages and atthis point anyone can type a valid url to a particular jsp and can successfully bring up thepage without authenticating to the system There are two recommended ways ofprotecting the jsps

1 Place all jsps under the WEB-INF folder This folder per J2EE standardcan only be accessed from within an application and is not publiclyaccessible via urls typed in the browser

2 Create a custom tag that checks if the user has been authenticated similarto the code we placed in the BaseAction class and perform a redirect to thelogin page if the user has not properly logged in

For option 1 it works well with J2EE compliant application servers but since we are usingWebSphere 353 there is basically no WEB-INF folder to speak off We created a WEB-INF folder in our craft application but this is just to line up our directory structure withJ2EE standards We will therefore cover option 2 in the next section

Coding (Part 2 ndash protecting jsp pages)Unlike the example that we put together in part 1 of this lesson the custom tag that wewill create in this section unconditionally checks if the user has logged-in already Inshort there will be no logic in this custom tag that is equivalent to the code in therequiresLogin() method of BaseAction The MVC patternrsquos basic premise is that usersneed to interact with a controller at all times and not the view It therefore follows thatusers should not be able to bring up jsprsquos (view) directly without going to an action classfirst

1 As previously mentioned we will create a custom tag that checks if a user has loggedin already In the package comffictraining create a class named CheckLoginTag

Create the class by extending TagSupport

public final class CheckLoginTag extends TagSupport

Create an instance variable containing information for the login page

private String page = loginjsp

The doEndTag() is where we check for the presence of the ldquouserKeyrdquo The logic is similarto the BaseActionrsquos isUserLoggedIn() method

public int doEndTag() throws JspException

Is there a valid user logged on

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

281

boolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered

public int doStartTag() throws JspException

return (SKIP_BODY)

Complete Code

import javaioIOExceptionimport javaxservlethttpHttpSessionimport javaxservletjspJspExceptionimport javaxservletjspJspWriterimport javaxservletjspPageContextimport javaxservletjsptagextTagSupportimport orgapachestrutsactionimport orgapachestrutsutilMessageResourcesimport javaxservlethttpHttpServletRequest

Check for a valid User logged on in the current session If there is no such user forward control to the logon page

282

public final class CheckLoginTag extends TagSupport

The page to which we should forward for the user to log on private String page = loginjsp

Perform our logged-in user check by looking for the existence of a session scope bean under the specified name If this bean is not present control is forwarded to the specified logon page exception JspException if a JSP exception has occurred public int doEndTag() throws JspException

Is there a valid user logged onboolean valid = falseHttpSession session = pageContextgetSession()if (sessiongetAttribute(userKey) == null || session == null) valid = false else

valid = true

Forward control based on the resultsif (valid) return (EVAL_PAGE)else try

pageContextforward(page) catch (Exception e)

throw new JspException(etoString()) return (SKIP_PAGE)

Defer our checking until the end of this tag is encountered exception JspException if a JSP exception has occurred public int doStartTag() throws JspException

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

283

return (SKIP_BODY)

2 Open the file apptld in craftWEB-INF and add an entry for the new tag

lttaggtltnamegtcheckLoginltnamegtlttagclassgtcomffictrainingCheckLoginTaglttagclassgtltbodycontentgtemptyltbodycontentgt

lttaggt

3 Make changes to ALL the jsps that wersquove created so far

Add a directive for the apptld

lt taglib uri=WEB-INFapptld prefix=app gt

Place this line of code at the top of each jsp

ltappcheckLogin gt

Deploying the code (Part 2 ndash protecting jsp pages)

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

Result (Part 2 ndash protecting jsp pages)Log into the application then click on the ldquoLog Outrdquo link to make sure that whateversession you have in your browser has been invalidated

284

The screen below makes sure that you have been logged out

In the same page type in the url for the divisionrsquos search pagehttplocalhost8080craftdivSearchjsp

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

285

The checkLogin tag will check to see if the user has logged in or not Since the sessionhas been invalidated the checkLoginTag will perform a forward to the login page

Note Irsquom still working on getting the tag to write an error message similar to what theBaseAction does when it forwards to the login page if the user has not authenticated yet

  • Lesson 1 - ORION webserver configuration
    • Preparation
    • Installation
    • Configuration
    • Review
      • Lesson 2 - VisualAge for JAVAWebSphere Test Environment configuration
        • Installation
        • Configuration
        • Usage
          • Lesson 3 - Servlet primer
            • Basics
            • Your first servlet
            • Deploying the code
              • Lesson 4 - Database Connectivity
                • Preparation
                • Coding
                • Deploying the code
                  • Lesson 5 - ServletDatabase Connectivity
                    • Preparation
                    • Coding
                    • Deploying the code
                      • Lesson 6 - Servlet Redirection
                        • Basics
                        • Preparation
                        • Coding
                        • Deploying the code
                        • Result
                          • Lesson 7 - JavaBeans
                            • Basics
                            • Coding
                            • Deploying the code
                            • Result
                              • Lesson 8 - Object Scope
                                • Basics
                                • Coding
                                • Deploying the code
                                • Result
                                  • Lesson 9 - Java Server Pages (JSP)
                                    • Basics
                                    • Coding
                                    • Deploying the code
                                    • Result
                                      • Lesson 10 - Custom Tags
                                        • Basics
                                          • Anatomy of a Tag
                                          • Custom Tag components
                                            • Coding
                                            • Deploying the code
                                            • Result
                                              • Lesson 11 - Model-View-Controller Design Pattern
                                                • Basics
                                                  • Lesson 12 - Introduction to the Struts Framework
                                                    • Struts Components
                                                    • ldquoI canrsquot find the MVC pattern anywhererdquo
                                                      • Lesson 13 - Installing Struts 11b in VisualAge for Java 40WebSphere Test Environment 353
                                                        • Installation and configuration
                                                        • Installing the sample application
                                                        • Deploying and running the sample application
                                                        • Result
                                                          • Lesson 14 - Installing Struts 11b in ORION
                                                            • Installation and configuration
                                                            • Installing the sample application
                                                            • Deploying and running the sample application
                                                            • Result
                                                              • Lesson 15 - Struts Components
                                                                • Struts Components
                                                                • Tag Libraries
                                                                • Useful Links
                                                                  • Lesson 16 - Building a simple web application using Struts
                                                                    • Basics
                                                                    • Coding
                                                                    • Deploying the code
                                                                    • Result
                                                                      • Lesson 17 ndash Validating form values
                                                                        • Basics
                                                                        • Installation
                                                                        • Coding
                                                                        • Deploying the code
                                                                        • Results
                                                                          • Lesson 18 ndash Nested Beans
                                                                            • Basics
                                                                            • Installation
                                                                            • Coding
                                                                              • CODING PART 1
                                                                              • CODING PART 2
                                                                              • CODING PART 3
                                                                                  • Lesson 19 ndash Creating reusable screen components
                                                                                    • Basics
                                                                                    • Coding (Part 1)
                                                                                    • Deploying the code (Part 1)
                                                                                    • Results (Part 1)
                                                                                    • Coding (Part 2)
                                                                                    • Deploying the code (Part 2)
                                                                                    • Result (Part 2)
                                                                                    • Coding (Part 3)
                                                                                    • Deploying the code (Part 3)
                                                                                    • Result (Part 3)
                                                                                      • Lesson 20 ndash Creating reusable menu components
                                                                                        • Basics
                                                                                        • Installation
                                                                                          • Option 1
                                                                                          • Option 2
                                                                                            • Coding
                                                                                            • Deploying the code
                                                                                            • Result
                                                                                              • Lesson 21 ndash Connection Pooling
                                                                                                • Basics
                                                                                                • Coding
                                                                                                • Deploying the code
                                                                                                • Result
                                                                                                  • Lesson 22 ndash Creating a singleton to maintain the
                                                                                                    • Basics
                                                                                                    • Coding
                                                                                                    • Deploying the code
                                                                                                    • Result
                                                                                                      • Lesson 23 ndash Data Access Objects
                                                                                                        • Basics
                                                                                                        • Coding
                                                                                                        • Deploying the code
                                                                                                        • Result
                                                                                                          • Lesson 24 ndash Business Objects
                                                                                                            • Coding
                                                                                                            • Deploying the code
                                                                                                            • Result
                                                                                                              • Lesson 25 ndash Action subclasses
                                                                                                                • Coding
                                                                                                                • Deploying the code
                                                                                                                • Result
                                                                                                                  • Lesson 26 ndash Exception handling
                                                                                                                    • Basics
                                                                                                                      • Using nested ifrsquos
                                                                                                                      • Using trycatch blocks
                                                                                                                        • Coding (Part 1 ndash programmatic exception handlin
                                                                                                                        • Deploying the code (Part 1 ndash programmatic excep
                                                                                                                        • Result (Part 1 ndash programmatic exception handlin
                                                                                                                        • Coding (Part 2 ndash using declarative exception
                                                                                                                        • Deploying the code (Part 2 ndash using declarative
                                                                                                                        • Result (Part 2 ndash using declarative exception
                                                                                                                          • Lesson 27 ndash Creating dynamic forms
                                                                                                                            • Basics
                                                                                                                            • Coding (Part 1 ndash DynaActionForm example)
                                                                                                                            • Deploying the code (Part 1 ndash DynaActionForm exa
                                                                                                                            • Result (Part 1 ndash DynaActionForm example)
                                                                                                                            • Coding (Part 2 ndash DynaValidatorForm example)
                                                                                                                            • Deploying the code (Part 2 ndash DynaValidatorForm
                                                                                                                            • Result (Part 2 ndash DynaValidatorForm example)
                                                                                                                              • Lesson 28 ndash Using tokens
                                                                                                                                • Basics
                                                                                                                                • Coding
                                                                                                                                • Deploying the code
                                                                                                                                • Result
                                                                                                                                  • Lesson 29 ndash Implementing security in Struts
                                                                                                                                    • Basics
                                                                                                                                    • Coding (Part 1 ndash protecting do classes)
                                                                                                                                    • Deploying the code (Part 1 ndash protecting do cl
                                                                                                                                    • Result (Part 1 ndash protecting do classes)
                                                                                                                                    • Coding (Part 2 ndash protecting jsp pages)
                                                                                                                                    • Deploying the code (Part 2 ndash protecting jsp pag
                                                                                                                                    • Result (Part 2 ndash protecting jsp pages)