JSP™andXMLIntegratingXMLandWeb
ServicesinYourJSP™Application
ByCaseyKochmer,EricaFrandsen
Publisher :AddisonWesley
PubDate :March19,2002
ISBN :0-672-32354-0
Pages :592
ThefirstInternetrevolutionwasallaboutdelivering
informationtopeople.Wearenowinthesecond
revolution,whichfocusesondeliveringinformationto
systems.XMListhetoolthatmakesthisnewrevolutiona
reality,andWebservicesarethemethodsbywhich
Tableof businesseswilldrivesystem-to-systemcommunication.
•
Contents JSP(TM)andXMLtakesyoubeyondthebasics,giving
youpracticaladviceandin-depthcoverage.Inthebook,
• Index
you'lllearnthetechnologiesandtechniquesneededto
createyourownWebservicesforuseinJSPapplications.
Writtenbyprogrammersforprogrammers,thebookwill
helpyousuccessfullyutilizetheseexcitingtechnologies
withminimalhassleandmaximumspeed.
777
Copyright
AbouttheAuthors
Acknowledgments
Introduction
OnXML
OnWebServices
OntheStructureoftheBook
AWordaboutSourceCode
HowtoUsetheBook
ConventionsUsedinThisBook
AFinalNote
PartI.Data,XML,andWebServicesIntroduction
Chapter1.IntegratingJSPandData
UsingJSPwithaDatabase
OtherConsiderations
BasicDesignConcepts
Summary
Chapter2.IntroductiontoXML/XSL
WhatIsXML?
RulesofXML
OntoUsingXML
XSL
Summary
Chapter3.UnderstandingWebServices
WhatIsaWebService?
CrystalBallReadings
TheABCsofWebServices
HowtoUseaWebService
Summary
PartII.IntegratingJSPandXML
Chapter4.AQuickStarttoJSPandXMLTogether
TheRelationshipBetweenXMLandJSP
JavaXML/XSLAPIs
Summary
Chapter5.UsingDOM
WhatIstheDOM?
NodesandTreeStructure
ProgrammingwithDOM
JDOM,dom4j,andDeferredDOM
Summary
Chapter6.ProgrammingSAX
WhatIsSAX?
TheWorkingsofSAX
Summary
Chapter7.SuccessfullyUsingJSPandXMLinanApplication
UsingaJavaRepresentationofanXMLDocument
WhyNotJustUseSAXorDOM?
InstallingJDOManddom4j
WhyBothJDOManddom4j?
CommonWaystoUseXML
UsingaDatabasewithXML
PullinginXMLFiles
Summary
Chapter8.IntegratingJSPandWebServices
ThinkinginJSPandWebServices
IntegratingaWebServiceintoaJSPPage
WhenShouldYouBuildYourOwnWebService?
BuildingaCorporateWebService
ApacheSOAPHelp
Summary
Chapter9.AdvancedJSPandXMLTechniques
AccessingWebServicesfromaBrowser
HandlingLargeXMLDocuments
HandlingSpecialCharactersandEncoding
UsingXMLTagLibraries
Summary
PartIII.BuildingJSPSitestoUseXML
Chapter10.UsingXSL/JSPinWebSiteDesign
HandlingXMLFilesDirectly
BuildinganXMLServletHandler
Summary
Chapter11.UsingXMLinReportingSystems
ArchitectureofReportingSystems
WhentoUseXMLwithReports
DataSourceforReports
ResultSettoXML
BringingItAllTogether
TheSortingTableStylesheet
TheCrossTabStylesheet
Summary
Chapter12.AdvancedXMLinReportingSystems
Multiple-PageReports
ReportsonDatawithOne-to-ManyRelationships
Real-WorldReportingSystems
Well-FormedDocumentsRevisited
Summary
Chapter13.BrowserConsiderationswithXML
Client-SideXMLandBrowserSupport
Client-SideJavaScriptandXML
Client-SideTransformationsandXML
Summary
Chapter14.BuildingaWebService
DesigningaWebService
BuildingtheWebService
CreatingaWSDLFile
RegisteringWithinUDDI
UsingJavatoAccessaWSDLDocument
Summary
Chapter15.AdvancedApplicationDesign
DynamicJSP
SOAPServerSecurityConcerns
QuickTakes
Summary
PartIV.Appendixes
AppendixA.SettingUp
InstallingtheJSPEnvironment
NetBeans
TheMySQLDatabaseServer
Summary
AppendixB.IntroductiontoJSPandHowThingsWork
JSPBasics
JSPActions,Directives,andImplicitObjects
AMoreRobustJSPExample
AdditionalInformationAboutJSP
Summary
AppendixC.TagLibrary
TagLibraryOverview
WhatIsaTagLibrary?
TheSixStepstoBuildingTagLibraries
TagLibraryConcepts
BuildingaTagLibrary
GeneralNotes
Summary
AppendixD.XSLReference
XSLTandXPath
Reference
Index
Copyright
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheir
productsareclaimedastrademarks.Wherethosedesignationsappearinthis
book,andAddison-Wesleywereawareofatrademarkclaim,thedesignations
havebeenprintedininitialcapitallettersorinallcapitals.
Theauthorandpublisherhavetakencareinthepreparationofthisbook,but
makenoexpressedorimpliedwarrantyofanykindandassumenoresponsibility
forerrorsoromissions.Noliabilityisassumedforincidentalorconsequential
damagesinconnectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Thepublisheroffersdiscountsonthisbookwhenorderedinquantityforspecial
sales.
Formoreinformation,pleasecontact:
PearsonEducationCorporateSalesDivision
201W.103rdStreet
Indianapolis,IN46290
(800)428-5331
VisitAWontheWeb:www.awl.com/cseng/
Copyright©2002byPearsonEducation
Allrightsreserved.Nopartofthispublicationmaybereproduced,storedina
retrievalsystem,ortransmitted,inanyformorbyanymeans,electronic,
mechanical,photocopying,recording,orotherwise,withoutthepriorconsentof
thepublisher.PrintedintheUnitedStatesofAmerica.Publishedsimultaneously
inCanada.
050403024321
FirstPrinting:March2002
Credits
ExecutiveEditor
RochelleJ.Kronzek
AcquisitionsEditor
MichelleNewcomb
DevelopmentEditor
MarkRay
ManagingEditor
MattPurcell
ProjectEditor
ChristinaSmith
ProductionEditors
SethKerney
RhondaTinch-Mize
MattWynalda
Indexer
MandieFrank
Proofreader
SuzanneThomas
TechnicalEditor
CraigPfeifer
TeamCoordinator
PamaleeNelson
InteriorDesigner
GaryAdair
CoverDesigner
AlanClements
PageLayout
RebeccaHarmon
MichelleMitchell
Dedications
Writingthisbookwasalongprocess.Asinallchoices,thisprojecthadits
rewardsanditsconsequences.Intheend,themostimportantlessonIlearned
wasoneoflife,notJSP.Icansharemythoughtsinthispoem.Idedicatethe
booktoanyonewhotakesamomenttoreadmypoetry.
DaysofWonderHeavenandHellarenotafterlifeHeavenandHellarepartof
lifeIt'sinlifewemakeourjoyIt'sinlifewebuildourwallsToanyonewho
readsthismayyoufindyourownheavenmayyoufindyourownpoemsBreak
freeofyourchainsJumpyourwallsLivelifeasifinheavenanddon'tmakelife
hellWehaveonlyonelifetoreliveoveragainininfinityDon'tregretasyou
moveforwardSincethepastisonlyformemoriesThesecrettolifeissimplyto
betruetoyourselfandsmilethenyouwillbeabletolookuponeachnewday
withthewonderitdeservesIt'sallanyonecaneverdo—CaseyKochmer
Idedicatethisbooktomyfamily:Jim,Judy,Kristina,andmyfriends.Youhave
mademewhatIamtoday,andforthatIthankyou.
Lifeisnotmeasuredbythenumberofbreathswetake,butbythemomentsthat
takeourbreathaway.
—EricaFrandsen
AbouttheAuthors
CaseyKochmerisacofounderoftheJSPInsiderWebsite.Aspresidentof
AmberJackSoftware,CaseyisaJavaServerPages(JSP),HTML,XHTML,
XML,DHTML,andWebservicespecialist.Hewaspreviouslyasenior
programmer,trainer,andInternetexpertforStarlingConsulting,wherehe
mentoredusersinJavaServerPages,ActiveServerPages(ASP),XMLusage,
andInternetpractices.Hisjobwastohelpcustomersintegratethelatest
technologyatanappropriatetimerelativetotheneedsofaproject.Hismantrais
thataprojectshouldimplementusableandmaintainabletechnologyratherthan
usingthelatesttechnologyfortechnology'ssake.Caseycodesandbuilds
specializedapplicationsusingJSP,ASP,andvariousdatabasesdependingon
customerneeds.Hehascoauthoredseveralbooks,includingProfessionalJSP,
SecondEditionandBeginningJSPWebDevelopment.
EricaFrandsenisanXML,ASP,andSQLServerexpert.Experiencedin
TCP/IPnetworking,sheisafounderofSoundHomeNetworks.Whileworking
asanetworkconsultant,sheinstalls,configures,andmaintainsnetworksfor
clients.Previously,EricaworkedasaprogrammerandconsultantforStarling
Consulting,whereshedesignedASPandSQLsystemsusingXML.Earlierin
hercareer,sheusedthesesametechnologiestocreateanonlinetaxpaying
systemforbusinessesinthestateofWashington.ShealsowastheWebmaster
forseveralsites.Inherfreetime,Ericabrewsbeer,playswithcomputer
hardware,andcreatesWebsitesforworthycauses.
Acknowledgments
IwouldliketothankMichelle,Mark,andMattfortheirexcellentwork.Without
theirperseverancethisbookwouldneverhavehappened.Thankyou,guys!
Also,IpaytributetoMariNowitzandNathanHamilton.Withoutmymost
excellentneighbors,Imighthavediedofstarvationandlackofinfluencefrom
therealworld.ThanksforbeingtherewhenIneededyou!
IwouldalsoliketothankSteveandBradatKundalinifortheirexcellentcoffee.
—EricaFrandsen
Introduction
ThepurposeofthisbookistoteachyouhowtoimplementXMLandWeb
serviceswithinaJSPWebapplicationorsite.Thebookwillstartverysimply
andthenworkitswayupincomplexity.Thiswillmakethebookaccessibletoa
widerangeofreaders.
ThetargetaudienceincludesnewandintermediateJSPprogrammers.However,
thisbookwillbeusefulforanyJSPprogrammerwhowantstoexpandhisorher
XMLorWebserviceimplementationknowledge.Thebookisalsogeared
towardshelpingaJSPprogrammerthinkintermsofthecombinationofJSP,
XML,andWebservices.Thegoalistoshowhowtousefullyintegratethese
technologiesintoyourprojectsandsharethelessonswehavelearnedinbuilding
Webapplications.
OnXML
WeareprogrammerswhospendquiteabitoftimebuildingWebapplications.
Overthepastfewyears,wehavebeenimplementingXMLinourprojects.
However,implementingXMLiseasiersaidthandoneattimes.Evenworse,
manytimesXMLisimplementedinwaysthatcanbeharmfultoaproject.You
shouldneveruseXMLforXML'ssake.Thisbookisareflectionofourordeals
inlearningthevarioustoolsandthemethodsofincorporatingXMLinauseful
wayintoaWebsite.
Theproblemfordevelopershasn'tbeenaboutfindinginformationonXML,but
aboutusingXMLsuccessfullywithinWebapplications.Whilethereareplenty
ofsolidXMLtitles,notitlereallyfocusesonhowtointegrateXMLintoyour
JSPproject.ThisbookiswrittenwiththeJSPdeveloperinmind.Wewantto
helpteachXML,XSL,XPath,andtheentirealphabetsoupthatgoesalongwith
XML.ByshowinghowtouseXMLwithinaJSPframework,weintendtohelp
makeimplementingXMLbotheasyandadvantageousfortheJSPdeveloper.
OnWebServices
Webservicesarethelatestfad.Theyaresonewthatmanyoftheaccompanying
toolsarestillinbetaorareonlynowbeingreleasedintothemarketplace.It'sstill
veryearlytolearnWebservices.Webservicesaretoonewforanyonetotrulybe
anexpertinthefield.ThismakeslearningWebservicesbothanexcitinganda
strangeexperience.OurintentionistoteachyouhowtoincorporateWeb
servicesintoJSP.WewillremovetheconfusionthatsurroundsWebservicesand
giveaclearpathtolearningthebasics.Thisbookwillshowthevariouselements
thatconstituteaWebservice.
OntheStructureoftheBook
Thebookisdividedintofourparts.PartIisdesignedtointroduceyoutoeachof
thetechnologiesexemplifiedthroughoutthisbook.PartIIdrillsdeeplyintothe
varioustoolsforeachofthesetechnologies.PartIIIshowshowtosuccessfully
combineallthesetechnologiestomakeyourprojecteasierandfasterto
implement.PartIVcontainsappendixesthatprovidereferencematerial.
PartI:Data,XML,andWebServicesIntroduction
Thispartisintendedtogroundyou.Wedonotassumethatyoualreadyknowa
greatdealaboutJSP,XML,orWebservices;thesethreetopicsareintroducedin
Chapters1–3.
Chapter1:IntegratingJSPandData
ThischaptershowshowtouseJSPandadatabasetogether.Thechapterserves
togroundyouinJSPandshowyouhowtoperformbasicdatabaseconnectivity.
Chapter2:IntroductiontoXML/XSL
ThischapterisawhirlwindtourofXMLandXSL.Itintroduceseachofthe
majorconceptsthatareneededforXMLandbeginsteachingXSLandXPath.
Chapter3:UnderstandingWebServices
Chapter3introducestheconceptsofWebservices.Webservicesareaconfusing
topic,andthechapterfocusesonthebasicconceptsyouwillneedtousethem.
PartII:IntegratingJSPandXML
PartIIisareviewofthetools,APIs,andlogicrequiredtosuccessfully
implementXMLandWebservices.Thesechaptersintroducethevarious
conceptsofWebservicesandthevariousparsersforXML.Onceyou'vestudied
thesechapters,youwillhaveenoughknowledgetobeginusingXMLandWeb
servicessuccessfully.
Chapter4:AQuickStarttoJSPandXMLTogether
ThischaptergivesyouaquickstarttomixingJSPandXMLtogether.The
chapterreviewsthebasicXMLAPIsandworksthroughsomeexamplesof
mergingJSPandXML.
Chapter5:UsingDOM
ThischapterteachestheimportantaspectsoftheDOMAPI.TheDOMisthe
standardsupportedbytheW3CforworkingwithanXMLfileprogrammatically.
Chapter6:ProgrammingSAX
ThischapterteachesyoutheinsandoutsoftheSAXAPI.SAXisprobablythe
mostcommonAPIusedtoreadinanXMLfile.Mostofthetime,SAXisused
automaticallybyotherXMLAPIs.However,thischapterisveryimportant
becauseunderstandingSAXiscriticalforhandlingmorecomplicatedXMLbasedprocesses.
Chapter7:SuccessfullyUsingJSPandXMLinanApplication
ThischapterintroducestheothermajorJavaXMLAPIs:JDOManddom4j.This
chapterproducesanintegratedexampleshowinghowtoworkwithJSP,XML,
andadatabase.Thegoalofthischapteristobeginwalkingyouthroughthe
integrationofXMLinanaturalwaywithinyourJSPapplication.
Chapter8:IntegratingJSPandWebServices
Chapter8examineshowtouseaWebservicewithinyourJSPsite.Thischapter
coverstwoimportantWebservicestopics.ThefirstisusingaWebservice;the
chaptershowsthemostefficientwaytouseaWebservicewithinyourJSP
application.ThesecondtopicisbuildingaWebservice;thechapterwalks
throughthecreationofaWebservicethatcanbeusedbyotherapplications.
Chapter9:AdvancedJSPandXMLTechniques
ThischapterexploresXMLconceptsthataren'tdiscussedinotherchapters.
TopicsincludeaccessingaWebservicefromanHTMLpage,XMLencoding
issues,waysofprocessinglargeXMLdocuments,andXMLtaglibraries.
PartIII:BuildingJSPSitestoUseXML
BuildingaJSPsiterequiresfarmorethanjustknowinghowtouseJSP.It
requirestheabilitytothinkintermsofbuildingaWebapplication.Web
applicationdesignisafineartthatinvolvesintegratingmanydifferenttoolsasa
seamlessunitwithinaJSPproject.Tothisend,PartIIIcoversthe
implementationofXMLandWebservicesfromanapplicationpointofview.
Thechaptersinthispartcovermanytopics,fromWebservicesecurityto
buildingXMLreportingsystems.WeshowmanydifferentfacetsofWeb
applicationdesign,fromtheservertotheoften-overlookedbrowserclient.
Chapter10:UsingXSL/JSPinWebSiteDesign
ThischapterexamineswhatispossiblebygoingbacktotherootsofJSP—or
morespecificallybyusingservlets.Thegoalofthechapteristoexaminegeneric
XMLhandling.ThismeansthattheinitialprocessingofanXMLdocumentcan
happenattheapplicationlevelratherthanatthepagelevel.Thechaptershows
howtocapturetheprocessingofanXMLpageandrouteitdirectlytoaservlet.
Chapter11:UsingXMLinReportingSystems
NomatterwhattheWebapplication,it'sasafebetthattherewillbesome
reportinginvolved.Thischapterexamineshowreportingsystemscanbenefit
fromtheappropriateplacementanduseofXML.
Chapter12:AdvancedXMLinReportingSystems
ThischapterbuildsontheexamplesinChapter11.Additionalconceptsand
topicstoenhanceanXML-basedreportingsystemareshowninthischapter's
examples.Amongtheexamplesisonethatshowshowtocreatereportsthat
showaone-to-manyrelationshipinthedatabase.
Chapter13:BrowserConsiderationswithXML
JSPdevelopersoftenoverlookclient-sideXMLprocessing.Thisisaserious
oversight,asbrowsersareagrowingandimprovingXMLclient-sidetool.This
chapterexamineshowusingthebrowsercanenhancehandlingofXMLdataand
reduceWebserverload.
Chapter14:BuildingaWebService
Inthischapter,webuildaWebservicesystemfornewsdelivery.Thecode
withinthischapterisbasedonaWebservicewithinaproductionenvironment.
ThegoalistoshowthedesignandfullintegrationofacompleteWebservice.
Chapter15:AdvancedApplicationDesign
Thischaptercoverstwotopics.First,we'llshowyouhowtobuildJSPpagesthat
updatethemselves.ThisadvancedcapabilitypermitsJSPsitestobemore
flexibleandtoexpandwhatispossiblewithXML,Webservices,andJSP.The
secondmaintopicissecurity;thechapterexamineshowtosecureyourWeb
services.
Appendixes
Theappendixessupportthematerialpresentedinthemainpartofthebook.
Theircontentsarebrieflydescribedhere.
AppendixA:SettingUp
ThisappendixcoversbasicinformationaboutsettinguptheJSPcontainerand
introducesNetBeansforthecreationofallyourJSPpages.
AppendixB:IntroductiontoJSPandHowThingsWork
FornewJSPusers,thisappendixoffersacrashcourseonJSPandhowitworks.
AppendixC:TagLibrary
ThisbookusesJSPtaglibrariesasmuchaspossible.Foruserswhoarenewto
JSP,thisappendixquicklycovershowtobuildanduseaJSPtaglibrary.
AppendixD:XSLReference
XSLisusedextensivelyinthisbook.AppendixDisareferencetothemost
commonlyusedXSLtagsandXPathfunctions.
AWordaboutSourceCode
Allthesourcecodefromthelistingsandprogramsincludedinthisbookis
availableviadownloadfromtheSamsPublishingWebsiteat
www.samspublishing.com.
Throughoutthebook,wecreatesampleclassfilesandJSPsandthenbuildon
themlaterinthesameoranotherchapter.Wheneverwedoso,weclearly
indicatewheretheoriginalfilecanbefound.Linesofcodethatshouldbeadded
orchangedareindicatedinboldfacetype.
HowtoUsetheBook
Aswementionedearlier,thisbookisgearedtowardnewandintermediateJSP
programmers.Howyouusethebook,andwhereyoubeginreading,willdepend
onyourexperiencelevel.Hereareafewtipstogetyoustarted.
ForAllUsers
Ifpossible,werecommendcodingtheexamples.Inprogramming,thebestway
tolearnisbycoding,andtheexampleshavebeengearedtoenableyoutodoso.
IfyouhaveanyquestionsaboutinitiallysettinguptheJSPcontaineror
NetBeanstocreateJSPs,refertoAppendixA.Otherwise,thefirsttimeaspecific
componentisused,itwillbereferencedforinstallationatthattime.
Inmanyrespects,codingtheexamplesisveryimportantbecausethisbook
exploresmanydifferentconcepts.Ifyoudon'twritethecode,manyofthe
conceptsarelikelytoslipbyornotsinkinasdeeplyastheyshould.Wealso
encourageyoutoexpandandtweaktheexamples.Trytobreakthecodeandfind
outwhyitbreaks.Asprogrammers,welearnbestbycodingandbyfixing
brokencode.Codingisbestlearnedbyexperience;don'tshyawayfromthis
reality.
ForNewJSPUsers
WearenotgoingtoassumethatyoualreadyknowJSPlikethebackofyour
hand.SomeonewithlittleornoJSPexperiencecanpickupthisbookandlearn
howtouseJSPandXML.Thecodeandtopicsarebuiltinalogicalandeasy
mannertohelpshowwhatisrequiredinusingXMLwithinyourJSPprojects.
BeginningJSPprogrammerswillwanttostudythechaptersinPartIclosely.The
examplesaresimpleenoughthattheywillbeagreatlearningaid.NewJSP
readerswillalsobenefitfromreadingAppendixB.
ForIntermediateJSPUsers
Thebeststartingplacewilldependonyourskills.Foruserswhoare
inexperiencedinXMLorWebservices,PartIisstillyourbestbet.Otherwise,
werecommendskimmingthefirstsection,asthereisquiteabitofinformation
withineachchapter.Thesechaptershavesomeinformationthatcanbenefitmore
experiencedreaders.However,ifyoufindthatyoualreadyknowthePartI
material,skipaheadtoPartII.
ConventionsUsedinThisBook
Thefollowingtypographicconventionsareusedinthisbook:
Codelines,commands,statements,variables,andanytextyoutypeorsee
onscreenappearsinamonotypeface.
Placeholdersinsyntaxdescriptionsappearinanitalicmono
typeface.Replacetheplaceholderwiththeactualfilename,parameter,or
whateverelementitrepresents.
Italicshighlighttechnicaltermswhenthey'rebeingintroducedanddefined.
ThebookalsocontainsNotestohelpyouspotimportantoruseful
informationmorequickly.
AFinalNote
ThisbookwaswrittenasareferenceforJSP,XML,andWebservices.Learning
thismaterialonourownwasalongprocess,andourgoalistohelpgiveJSP
developerssomeinsightsintobuildingJSPWebapplications.Thefactis,XML
andWebservicesarebothfastbecomingessentialtoolstomostJSP
applications.Theproblemistryingtolearneverythingatonce.Ourgoalwasto
provideintegratedexamplesofpracticalJSP,XML,andWebservice
implementations.Wehopethatyoubenefitfromreadingthebookasmuchaswe
benefitedfromwritingit.
PartI:Data,XML,andWebServices
Introduction
INTHISPART
1IntegratingJSPandData
2IntroductiontoXML/XSL
3UnderstandingWebServices
CONTENTS
Chapter1.IntegratingJSPandData
INTHISCHAPTER
UsingJSPwithaDatabase
OtherConsiderations
BasicDesignConcepts
Summary
Oneofthemostimportantconceptsinbuildinganyapplicationistheconceptof
data.Ourapplicationsaredrivenbydata,andthetoolsthatspecializeinthe
handlingofdataformacentralpartofanyapplication.XMLisaspecification
thatisgearedtohandledata.However,inusingXML,itquicklybecomes
importanttohaveaccesstoseveralothertools.Usuallyadatabaseisthefirst
toolthatwillbeusedalongsideXML.Oftentimes,thedataforourXMLfiles
willcomedirectlyfromadatabase.Inaddition,itwillbeimportanttoimport
datafromanXMLfileintoadatabase.Usingadatabaseisimportantenough
thatthisfirstchapterisdedicatedtoshowinghowtoaccessandsubmitdatatoa
database.
Thischapterhastwogoals.Thefirstistoshowyouhowtoaccessadatabase
fromJSP.IfyouarealreadyfamiliarwithusingadatabasewithinJSP,it's
advisablethatyouproceedtoChapter2,"IntroductiontoXML/XSL."It's
importanttonotethatseveralchaptersinthisbookwilluseadatabaseinthe
examples.Thismakessettingupatestdatabaseveryimportant.Instructionsfor
settinguptheMySQLtestdatabaseusedinalltheexamplescanbefoundin
AppendixA,"SettingUp."
ThesecondgoalistoensurethatnewerJSPprogrammershaveachancetoget
morefamiliarwithJSPbeforemovingfurtherintothebook.Thischapteris
intendedtobeextremelyaccessibletonewerJSPprogrammersregardlessof
theircurrentskilllevel.Thismeansthatthechapterisverybasic;moreadvanced
JSPprogrammerswillonlywanttoskimthischapterquickly.Programmerswho
arejuststartingtolearnaboutJSPareencouragedtofirstreadAppendix
B,"IntroductiontoJSPandHowThingsWork."
UsingJSPwithaDatabase
Thissectionwillnotcoverhowtobuildormaintainadatabase.Inaddition,due
tothevastnumberofdatabases,itwouldbeimpossibletocoverspecial
database-specificdetails.Thismeanstheexamplesherewillbekeptasgeneric
aspossibletohelpeasetheprocessofportingcodefromdatabasetodatabase.
TheexamplesinthischapterwillbeusingtheMySQLdatabase.
Tomakelifesimple,wearegoingtobuildseveralexamples.Thefirstexample
willbeusedtoenterdataintothedatabase.Thesecondexamplewillbeusedto
viewthedatainthedatabase.Thelogicintheseexamplesassumesthatthe
BannerAdstablehasbeencreatedaccordingtotheinstructionsforsettingupthe
MySQLdatabasefoundinAppendixA.
EnteringtheData
TheactualprocessofenteringdatashouldbesplitacrossseveralJSPpages.One
pagewillbeadatainputpage.Thispagewillonlyconcernitselfwithgathering
thedata.ThesecondpagewillbeanactionpagethatwillrunontheJSPserver
toprocesstheresultscreatedthroughtheinputpage.It'sagoodideatosplit
logicacrossseveralJSPpages.Thisisaperfectexampleofacaseinwhichthis
istrue.It'spossibletobuildasinglepagetoperformallthetasksoftheinputand
actionpages.Usingonepagewouldleavethecodeentangledanddifficultto
maintainwithtoomuchhappeningforasinglepage.Thisisespeciallytruewith
morecomplicateddatabasepages.Usingtwopagesmakesthelogicmoreclosely
matchtheprocessandmakesiteasierforotherprogrammerstounderstandwhat
isgoingonwithinthepages.
Theinputpage,showninListing1.1,gathersdatafromtheuserandshouldbe
savedas
webapps/xmlbook/chapter1/UpdateTableForm.jsp.
Listing1.1UpdateTableForm.jsp
<%@pagecontentType="text/html"%>
<html>
<head><title>UpdateTableForm</title></head>
<body>
<table>
<tr>
<td>Name</td>
<td>
</tr>
<tr>
<td>LinkText</td>
<td>
</tr>
<tr>
<td>Link</td>
<td>
</tr>
<tr><td>Action</td>
<td>
</td>
</tr>
<tr><td><inputtype="SUBMIT"value="Submit"/>
</tr>
</table>
</form>
</body>
</html>
Thisdoesn'tneedtobeaJSPpage.ItcouldbekeptasastraightHTMLpage.
However,we'vekeptitasaJSPpageoutofhabit.Typically,aninputpagesuch
asthiswouldhaveotheractivefeaturessuchassecurityvalidation,whichwould
requireittousesomeJSPprocessing.
Nowit'stimetobuildanactionpage.Thispage,whosecodeisshowninListing
1.2,willreceivethedatafromtheinputpageandthenupdatethedatabase.Save
thisfileas
webapps/xmlbook/chapter1/UpdateTableAction.jsp.
Listing1.2UpdateTableAction.jsp
<%@pageimport="java.sql.*"%>
<%
/*Step1)Getthedatafromtheform*/
Stringls_name=request.getParameter("name");
Stringls_link=request.getParameter("link");
Stringls_linktext=request.getParameter("linktext"
Stringls_action=request.getParameter("Action");
/*Step2)InitializeVariables*/
Stringls_result="Databasewasupdated";
Stringls_query="";
Stringls_dburl="jdbc:mysql://localhost/xmlboo
Stringls_dbdriver="org.gjt.mm.mysql.Driver";
/*Step3)Createaquery*/
if(ls_action.equals("new"))
{ls_query="insertintoBannerAds(name,link,
ls_query+="values(";
ls_query+="'"+ls_name+"',";
ls_query+="'"+ls_link+"',";
ls_query+="'"+ls_linktext+"')";
}