JavafortheWebwithServlets,JSP,and
EJB:ADeveloper'sGuidetoJ2EE
Solutions
ByBudiKurniawan
Publisher :NewRidersPublishing
PubDate :April12,2002
ISBN :0-7357-1195-X
Pages :976
JavafortheWebwithServlets,JSPandEJBistheonebookyou
needtomasterJavawebprogramming.Itcoversallthe
technologiesneededtoprogramwebapplicationsinJavausing
Servlets2.3,JSP1.2,EJB2.0andclient-sideprogrammingwith
JavaScript.Thesetechnologiesareexplainedinthecontextof
real-worldprojects,suchasane-commerceapplication,a
documentmanagementprogram,fileuploadandprogrammable
filedownload,andanXML-basedonlinebookproject.
Tableof
•
Contents Inadditiontoexcellentcontent,thisbookincludeslicensesto
• Examples twoJavawebcomponentsfromBrainySoftware.com.You
receiveafulllicenseoftheProgrammableFileDownload
componentforcommercialandnon-commercialdeployment.
Youarealsograntedtoalicensetodeploytheauthor'spopular
FileUploadbeanfornon-commercialuse,whichhasbeen
licensedbytheFortune500companyCommerceOneand
purchasedbymajorcorporationssuchasSaudiBusiness
Machine,Ltd.andBaxterHealthcareCorporation.
777
Copyright
AbouttheAuthor
AbouttheTechnicalReviewers
Acknowledgments
TellUsWhatYouThink
Introduction
TheHypertextTransferProtocol(HTTP)
SystemArchitecture
Java2,EnterpriseEdition(J2EE)
DevelopingWebApplicationsinJava
OverviewofPartsandChapters
PartI:BuildingJavaWebApplications
Chapter1.TheServletTechnology
TheBenefitsofServlets
ServletApplicationArchitecture
HowaServletWorks
TheTomcatServletContainer
SixStepstoRunningYourFirstServlet
Summary
Chapter2.InsideServlets
Thejavax.servletPackage
AServlet'sLifeCycle
ObtainingConfigurationInformation
PreservingtheServletConfig
TheServletContext
SharingInformationAmongServlets
RequestsandResponses
TheGenericServletWrapperClass
CreatingThread-SafeServlets
Summary
Chapter3.WritingServletApplications
TheHttpServletClass
TheHttpServletRequestInterface
HttpServletResponse
SendinganErrorCode
SendingSpecialCharacters
BufferingtheResponse
PopulatingHTMLElements
RequestDispatching
Summary
Chapter4.AccessingDatabaseswithJDBC
Thejava.sqlPackage
FourStepstoGettingtotheDatabase
ADatabase-BasedLoginServlet
TheSingleQuoteFactor
InsertingDataintoaTablewithRegistrationServlet
DisplayingAllRecords
SearchPage
AnOnlineSQLTool
ShouldIKeeptheConnectionOpen?
Transactions
ConnectionPooling
Summary
Chapter5.SessionManagement
WhatIsSessionManagement?
URLRewriting
HiddenFields
Cookies
SessionObjects
KnowingWhichTechniquetoUse
Summary
Chapter6.ApplicationandSessionEvents
ListeningtoApplicationEvents
ListeningtoHttpSessionEvents
Summary
Chapter7.ServletFiltering
AnOverviewoftheAPI
ABasicFilter
MappingaFilterwithaURL
ALoggingFilter
FilterConfiguration
AFilterthatChecksUserInput
FilteringtheResponse
FilterChain
Summary
Chapter8.JSPBasics
What'sWrongwithServlets?
RunningYourFirstJSP
HowJSPWorks
TheJSPServletGeneratedCode
TheJSPAPI
TheGeneratedServletRevisited
ImplicitObjects
Summary
Chapter9.JSPSyntax
Directives
ScriptingElements
StandardActionElements
Comments
ConvertingintoXMLSyntax
Summary
Chapter10.DevelopingJSPBeans
CallingYourBeanfromaJSPPage
ABriefTheoryofJavaBeans
MakingaBeanAvailable
AccessingPropertiesUsingjsp:getPropertyandjsp:setProperty
SettingaPropertyValuefromaRequest
JavaBeansCodeInitialization
TheSQLToolBeanExample
Summary
Chapter11.UsingJSPCustomTags
WritingYourFirstCustomTag
TheRoleoftheDeploymentDescriptor
TheTagLibraryDescriptor
TheCustomTagSyntax
TheJSPCustomTagAPI
TheLifeCycleofaTagHandler
Summary
Chapter12.ProgrammableFileDownload
KeystoProgrammableFileDownload
UsingtheBrainysoftware.comFileDownloadBean
Summary
Chapter13.FileUpload
TheHTTPRequest
Client-SideHTML
HTTPRequestofanUploadedFile
UploadingaFile
FileUploadBean
MultipleFileUpload
Summary
Chapter14.SecurityConfiguration
ImposingSecurityConstraints
AllowingMultipleRoles
Form-BasedAuthentication
DigestAuthentication
MethodsRelatedtoSecurity
RestrictingCertainMethods
Summary
Chapter15.Caching
CachingDataintoaTextFile
CachinginMemory
Summary
Chapter16.ApplicationDeployment
ApplicationDirectoryStructure
DeploymentDescriptor
ServletAliasandMapping
JSPAliasandMapping
PackagingandDeployingaWebApplication
Summary
Chapter17.ArchitectingJavaWebApplications
Model1Architecture
Model2Architecture
Summary
Chapter18.DevelopingE-CommerceApplications
ProjectSpecification
TheDatabaseStructure
PageDesign
Preparation
ApplicationDesign
BuildingtheProject
Summary
Chapter19.XML-BasedE-Books
TheTableofContents
TranslatingXMLintotheObjectTree
TheProject
Pre-RendertheTableofContents
Summary
Chapter20.Web-BasedDocumentManagement
TheDocmanProject
Summary
PartII:Client-SideProgrammingwithJavaScript
Chapter21.JavaScriptBasics
IntroductiontoJavaScript
AddingJavaScriptCodetoHTML
JavaScriptObjectModel
EventHandler
WindowandStringObjects
Summary
Chapter22.Client-SideProgrammingBasics
CheckingWhetherJavaScriptIsEnabled
HandlingJavaScript-UnawareBrowsers
HandlingDifferentVersionsofJavaScript
IncludingaJavaScriptFile
CheckingtheOperatingSystem
CheckingtheBrowserGeneration
CheckingtheBrowserType
CheckingtheBrowserLanguage
HandlingDynamicVariable-Names
Summary
Chapter23.Redirection
AnticipatingFailedRedirection
UsingtheRefreshMetaTag
UsingthelocationObject
GoingBacktothePreviousPage
MovingForward
NavigationwithaSELECTElement
Summary
Chapter24.Client-SideInputValidation
TheisEmptyFunction
ThetrimFunction
ThetrimAllFunction
TheisPositiveIntegerFunction
TheisValidPhoneNumberFunction
TheisMoneyFunction
TheisUSDateandisOZDateFunctions
ConvertingDateFormats
DataTypeConversion:StringtoNumeric
DataTypeConversion:NumerictoString
UsingtheValidationFunctions
Summary
Chapter25.WorkingwithClient-SideCookies
CreatingCookieswitha<META>Tag
CreatingCookieswithdocument.cookie
CreatingCookieswiththesetCookieFunction
ReadingCookiesontheBrowser
DeletingaCookieontheBrowser
CheckingIftheBrowserCanAcceptCookiesUsingJavaScript
CheckingIftheBrowserAcceptsCookiesWithoutJavaScript
Summary
Chapter26.WorkingwithObjectTrees
TheArrayObject
TrulyDeletinganArrayElement
CreatinganObject
AHierarchyofObjects
Summary
Chapter27.ControllingApplets
IsJavaEnabled?
IstheAppletReady?
ResizinganApplet
CallinganApplet'sMethod
GettinganApplet'sProperty
SettinganAppletProperty
UsingJavaClassesDirectly
Applet-to-JavaScriptCommunication
AccessingtheDocumentObjectModelfromanApplet
InvokingJavaScriptFunctionsfromanApplet
EvaluatingaJavaScriptStatementfromanApplet
SettingtheAppletParameter
Applet-to-AppletCommunicationThroughJavaScript
DirectApplet-to-AppletCommunication
Summary
PartIII:DevelopingScalableApplicationswithEJB
Chapter28.EnterpriseJavaBeans
WhatIsanEnterpriseJavaBean?
BenefitsofEJB
EJBApplicationArchitecture
TheSixEJBRoles
TypesofEnterpriseBeans
WritingYourFirstEnterpriseBean
EJBExplained
WritingClientApplications
CreatingaBean'sInstance
Summary
Chapter29.TheSessionBean
WhatIsaSessionBean?
StatefulandStatelessSessionBeans
WritingaSessionBean
TheTassieOnlineBookstoreExample
Summary
Chapter30.EntityBeans
WhatIsanEntityBean?
TheRemoteInterface
TheHomeInterface
ThePrimaryKeyClass
TheEntityBean
TwoTypesofEntityBeans
WritingaBMPEntityBean
WritingaCMPEntityBean
Summary
Chapter31.EJBQueryLanguage
EJBQLSyntax
EJBQLBNF
Summary
Chapter32.JavaMessageService
IntroductiontoMessaging
TheJMSAPI
TheJMSAPIMessagingDomains
TheJMSObjectModel
WritingJMSClients
Summary
Chapter33.Message-DrivenBeans
WhatIsaMessage-DrivenBean?
TheApplicationProgrammingInterface
WritingaMessage-DrivenBean
Summary
PartIV:Appendixes
AppendixA.TomcatInstallationandConfiguration
TomcatInstallation
TomcatDirectories
ChangingthePort
ConstructingaJSPApplication
AppendixB.Thejavax.servletPackageReference
Interfaces
Classes
Exceptions
Interfaces
Classes
Exceptions
AppendixC.Thejavax.servlet.httpPackageReference
Interfaces
Classes
AppendixD.Thejavax.servlet.jspPackageReference
Interfaces
Classes
AppendixE.Thejavax.servlet.jsp.tagextPackageReference
Interfaces
Classes
AppendixF.JBossInstallationandConfiguration
SystemRequirements
InstallingJBoss
DirectoryStructure
Configuration
RunningJBoss
Deployment
JBossandTomcat
Summary
AppendixG.RelatedResources
J2EE
Servlet
JSP
TagLibrary
Servlet/JSPContainers
JDBC
JNDI
JMS
EJB
J2EEServer
AppendixH.What'sOntheCD-ROM?
ReadThisBeforeOpeningtheSoftware
GNULESSERGENERALPUBLICLICENSE
GNULESSERGENERALPUBLICLICENSE
NOWARRANTY
Copyright
Copyright©2002byNewRidersPublishing
FIRSTEDITION:April,2002
Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinany
formorbyanymeans,electronicormechanical,includingphotocopying,
recording,orbyanyinformationstorageandretrievalsystem,withoutwritten
permissionfromthepublisher,exceptfortheinclusionofbriefquotationsina
review.
LibraryofCongressCatalogCardNumber:2001093802
06050403027654321
Interpretationoftheprintingcode:Therightmostdouble-digitnumberisthe
yearofthebook'sprinting;therightmostsingle-digitnumberisthenumberof
thebook'sprinting.Forexample,theprintingcode02-1showsthatthefirst
printingofthebookoccurredin2002.
Trademarks
Alltermsmentionedinthisbookthatareknowntobetrademarksorservice
markshavebeenappropriatelycapitalized.NewRidersPublishingcannotattest
totheaccuracyofthisinformation.Useofaterminthisbookshouldnotbe
regardedasaffectingthevalidityofanytrademarkorservicemark.
WarningandDisclaimer
ThisbookisdesignedtoprovideinformationaboutJavaforthewebworking
withservlets,jsp,andejb.Everyefforthasbeenmadetomakethisbookas
completeandasaccurateaspossible,butnowarrantyoffitnessisimplied.
Theinformationisprovidedonanas-isbasis.TheauthorsandNewRiders
Publishingshallhaveneitherliabilitynorresponsibilitytoanypersonorentity
withrespecttoanylossordamagesarisingfromtheinformationcontainedin
thisbookorfromtheuseofthediscsorprogramsthatmayaccompanyit.
Publisher
DavidDwyer
AssociatePublisher
StephanieWall
ProductionManager
GinaKanouse
ManagingEditor
KristyKnoop
AcquisitionsEditor
DeborahHittel-Shoaf
DevelopmentEditor
GrantMunroe
ProductMarketingManager
KathyMalmloff
PublicityManager
SusanNixon
CopyEditor
KathyMurray
Indexer
ChrisMorris
ManufacturingCoordinator
JimConway
BookDesigner
LouisaKlucznik
CoverDesigner
BrainstormDesign,Inc.
CoverProduction
ArenHowell
Proofreader
SossitySmith
Composition
JeffBredensteiner
MediaDeveloper
JayPayne
AbouttheAuthor
BudiKurniawanisanITconsultantspecializinginInternetandobject-oriented
programmingandhastaughtbothJavaandMicrosofttechnologies.Heisthe
authorofthemostpopularJavaUploadbeanfromBrainySoftware.com,which
islicensedbyCommerceOne(NASDAQ:CMRC)andpurchasedbymajor
corporations,suchasSaudiBusinessMachineLtd(www.sbm.com.sa),Baxter
HealthcareCorporation(www.baxter.com),andothers.
BudihasaMastersofResearchdegreeinElectricalEngineeringfromSydney
University,Australia.Hisresearchtopicwasondigitalimageprocessing.Budi
haswrittenanumberofcomputerbooks,aswellaspublishedarticlesformore
than10publications—includingprestigiousJavamagazines,suchasJava-Pro,
JavaWorld,JavaReport,andO'Reilly'swww.onjava.com.Budiisnowthe
weeklycontributorfortheServlets/JSPsectionofJavaInsightandcanbe
contactedat
AbouttheTechnicalReviewers
Thesereviewerscontributedtheirconsiderablehands-onexpertisetotheentire
developmentprocessforJavafortheWebwithServlets,JSP,andEJB.Asthe
bookwasbeingwritten,thesededicatedprofessionalsreviewedallthematerial
fortechnicalcontent,organization,andflow.Theirfeedbackwascriticalto
ensuringthatJavafortheWebwithServlets,JSP,andEJBfitsourreader'sneed
forthehighest-qualitytechnicalinformation.
ChrisCraneiscurrentlyteachingatMemorialUniversityofNewfoundland,
whereheoffersprogrammingcoursescoveringawiderangeofprogramming
conceptsandlanguages,suchasdesktopapplicationdevelopmentusingVisual
Basic,C++,andJavatoDistributedEnterpriseApplicationsusingEJB,and
Microsoft.NetWebServices.Outsideofhisteachingduties,Chrisrunshisown
consultingcompany,developingEnterprise-levelapplicationsforcompanies
throughoutCanadaandtheU.S.HeisalsocertifiedasanMCP,MCSD,MCT,
CCNA,CCAIandSCP/Java2.
LanWujoinedPersistenceSoftwareinSiliconValleyafterreceivingher
Master'sDegreeinComputerScience.Lan'seffortsatPersistencewerefocused
onJavawithEJBs.Later,shemovedontomyCFOCorporation,wheresheis
involvedwiththedesigninganddevelopingoftheautomationsystem.Sheis
nowwithBlueMartiniSoftwareandresponsibleforautomationwithJavaand
webprogramming.
Acknowledgments
Somanypeopleareinvolvedintheprocessofdeliveringthisbook,without
whomthisbookwouldneverbeareality.
FirstandforemostI'dliketothankDeborahHittel-Shoaf,myAcquisitions
Editor,forherprofessionalismandflexibility.Really,shetakescareofher
authors.
ThanksalsogotoGrantMunroe,myDevelopmentEditor,forhispatienceand
forgettingallthechapterstogether.
Twoexcellenteditorshelpedmewithtechnicalreviewandprovidedinvaluable
feedbackandmadethecontentmuch,muchbetter:LanWuandChrisCrane.I
wouldalsoliketothankthem.
Finally,allthefolksatNewRiderswhohelpedmewiththediagrams,
proofreading,index,layout,andsoon.Thankyou.
SpecialthanksgotomybestfriendKenforprovidingmewithexcellent
accommodation(andInternetaccess)duringmyChristmasvisittoVancouver,
BC—afterbeingknockedoutexhaustedinthemiddleofthewritingofthis
book.Hispartyandthetoursrefreshedme.
TellUsWhatYouThink
Asthereaderofthisbook,youarethemostimportantcriticandcommentator.
Wevalueyouropinionandwanttoknowwhatwe'redoingright,whatwecould
dobetter,whatareasyou'dliketoseeuspublishin,andanyotherwordsof
wisdomyou'rewillingtopassourway.
AstheAssociatePublisherforNewRidersPublishing,Iwelcomeyour
comments.Youcanfax,email,orwritemedirectlytoletmeknowwhatyoudid
ordidn'tlikeaboutthisbook—aswellaswhatwecandotomakeourbooks
stronger.
PleasenotethatIcannothelpyouwithtechnicalproblemsrelatedtothetopicof
thisbook,andthatduetothehighvolumeofmailIreceive,Imightnotbeable
toreplytoeverymessage.
Whenyouwrite,pleasebesuretoincludethisbook'stitleandauthoraswellas
yournameandphoneorfaxnumber.Iwillcarefullyreviewyourcommentsand
sharethemwiththeauthorandeditorswhoworkedonthebook.
Fax:
317-581-4663
Email:
Mail:
StephanieWall
AssociatePublisher
NewRidersPublishing
201West103rdStreet
Indianapolis,IN46290USA
Introduction
TheInternetisstillyoungandvulnerable.Therefore,itshistoryisnotalengthy
one.Thewebstartedwheneverythingwasjuststaticpages.Unlessyouarea
six-year-oldwhizkidreadingthisbookbecauseyouaremoreinterestedinJava
webprogrammingthanPlayStation2,itismostlikelythatyouexperiencedthe
timewhenawebsitewasnomorethanHTMLpages.Intheearlierdays,aweb
sitehadatmostonepageanditmoreoftenthannotwascalledahomepage.
Theterms"Internetapplication"or"webapplication"werecoinedwhen
dynamiccontentwasintroduced.Looselyinterpreted,awebapplicationisaweb
sitewhosecontentsaregenerateddynamicallybeforebeingsenttothebrowser.
YoushouldfirstunderstandhowtheInternetworksbeforelearninghowaweb
applicationworks.
WhenyousurftheInternet,youbasicallyrequestforacertainfilelocatedina
particularcomputerinthelocationyouspecifyintheUniformResourceLocator
(URL).Thecomputerwherethefileisstorediscalledthewebserver.This
computer'smainfunctionistoserveanybodyontheInternetwhorequestsfiles
ithosts.Becauseyouneverknowwhenauserwillvisitanduseyourweb
application,yourwebservermustbeupandrunningallthetime.
WhenyouclickortypeinaURLintheLocationorAddressboxofyour
browser,thefollowingthingshappen:
TheclientbrowserestablishesaTCP/IPconnectionwiththeserver.
Thebrowsersendsarequesttotheserver.
Theserversendsaresponsetotheclient.
Theserverclosestheconnection.
Notethataftersendingtherequestedpagetothebrowser,theserveralways
closestheconnection,whetherornottheuserrequestsotherpagesfromthe
server.
WhatIsHappeningintheIndustry
SincetheemergenceoftheInternet,webtechnologieshavebecomemoreand
moreimportant,andwebapplicationsaremoreandmorecommon.Theuseofa
webbrowserisnolongerrestrictedtosurfingstaticpagesontheInternet.Itis
nowverycommonplacetoseeawebbrowserusedasanapplication'sclient.
Whatthismeansis,somepeoplebelieve,whoevercontrolstheInternetcontrols
thefutureofcomputing—oreventhefutureitself.Attheveryleast,the
evidencehasbeendemonstratedbythestrugglesofafewcompaniestograbthe
webbrowsers'dominationinthelate1990s.Asthebestexample,Microsoft
Corporation—stillthenumberoneplayerinthesoftwarebusinessupuntilnow
—feltitwasimportanttohaveeveryoneontheplanetusingitsInternet
Explorerbrowser.That'swhyitexerteditsoverwhelmingpowerinsoftware
technologytocreatethefastestandsmartestbrowsereveranddistributeitfor
free.WiththesurrenderofNetscape,Microsofthaswonthebattleofbrowsers.
Inthenextfiveyears,itisstillhardtoimaginehowanybrowsercouldsurpass
thepopularityofMicrosoftInternetExplorer.
Ontheserverside,it'sadifferentstory,though.Thewarisfarfromover.
Microsoftcan'tpushitsservertechnologyaseasilyasitforcedNetscapetogive
up.Infact,themostpopularservertechnologyisJava.Tobeprecise,it'sSun
Microsystems'Java2,EnterpriseEdition(J2EE).Microsoftisstilltryingto
catchupwithitsnew.NETinitiativethatisareplacementofitsprevious
DistributedinterNetApplications(DNA)platformfordevelopingenterprise
applications.Releasedinearly2002,.NETwillcollidehead-onwithJ2EE.The
nextfewyearswillstillseeJ2EEand.NETasthetwocompetingserver
technologies.Rightnow,it'sstilltooprematuretopredictwhowillcomeoutthe
winner.
Strategy-wise,MicrosofttakesafardifferentapproachfromSunintryingto
win.Microsoftprovidesasingle-vendorsolution,sellingfromtheoperating
systemtothedatabaseserver.J2EE,ontheotherhand,issupportedbythe
entireindustry.(ForalistofvendorswhoprovideJ2EEcompliantservers,see
AppendixG,"RelatedResources.")AnalystshavetriedtocompareJ2EEand
.NETinmanywhitepaperspublishedontheInternet.Unfortunately,the
conclusionsvaryagreatdeal.TofindoutmoreabouthowJ2EEand.NET
compare,youcanconsultthefollowingarticles,whichareavailableonline:
Microsoft.NETvs.J2EE:HowDoTheyStackUp?,
/>Java2EnterpriseEdition(J2EE)versusThe.NETPlatform:TwoVisions
foreBusiness,
DotNet.doc
J2EEvs.Microsoft.NET:AComparisonofBuildingXML-BasedWeb
Services,
/>CompareMicrosoft.NETtoJ2EETechnology,
/>Atthispoint,youshouldhavegottenthebigpictureofwhatishappeninginthe
industry.Youcanfindoutmoreabout.NETat.J2EE
ispresentedinthesection,"Java2."
Alsonotethatthetermwebservercanalsobeusedtorefertothesoftware
packageusedinthewebservercomputertohandlerequestsandrespondto
them.Infact,throughoutthisbook,thetermwebserverisusedtorefertothis
software.
Thefirstpopularwebserver—NCSAHTTPd—wascreatedbyRobMcCoolat
theNationalCenterforSupercomputingApplications.And,McCool'sinvention
wasreallycoolbecauseithelpedtheInternetrevolutionizeourlivesandwent
ontobecomethefoundationfortheApachewebserver—themostusedweb
serverontheInternettoday.
TheHypertextTransferProtocol(HTTP)
HTTPistheprotocolthatallowswebserversandbrowserstoexchangedata
overtheweb.Itisarequestandresponseprotocol.Theclientrequestsafileand
theserverrespondstotherequest.HTTPusesreliableTCPconnections—by
defaultonTCPport80.HTTP(currentlyatversion1.1atthetimeofthis
writing)wasfirstdefinedinRFC2068.ItwasthenrefinedinRFC2616,which
canbefoundat />
InHTTP,it'salwaystheclientwhoinitiatesatransactionbyestablishinga
connectionandsendinganHTTPrequest.Theserverisinnopositiontocontact
aclientormakeacallbackconnectiontotheclient.Eithertheclientortheserver
canprematurelyterminateaconnection.Forexample,whenusingaweb
browseryoucanclicktheStopbuttononyourbrowsertostopthedownload
processofafile,effectivelyclosingtheHTTPconnectionwiththewebserver.
HTTPRequests
AnHTTPtransactionbeginswitharequestfromtheclientbrowserandends
witharesponsefromtheserver.AnHTTPrequestconsistsofthreecomponents:
Method——URI—Protocol/Version
Requestheaders
Entitybody
AnexampleofanHTTPrequestisthefollowing:
GET/servlet/default.jspHTTP/1.1
Accept:text/plain;text/html
Accept-Language:en-gb
Connection:Keep-Alive
Host:localhost
Referer:http://localhost/ch8/SendDetails.htm
User-Agent:Mozilla/4.0(compatible;MSIE4.01;Windows
Content-Length:33
Content-Type:application/x-www-form-urlencoded
Accept-Encoding:gzip,deflate
LastName=Franks&FirstName=Michael
Themethod—URI—protocolversionappearsasthefirstlineoftherequest.
GET/servlet/default.jspHTTP/1.1
whereGETistherequestmethod,/servlet/default.jsprepresents
theURIandHTTP/1.1theProtocol/Versionsection.
Therequestmethodwillbeexplainedinmoredetailsinthenextsection,"HTTP
requestMethods."
TheURIspecifiesanInternetresourcecompletely.AURIisusuallyinterpreted
asbeingrelativetotheserver'srootdirectory.Thus,itshouldalwaysbeginwith
aforwardslash/.AURLisactuallyatypeofURI(see
TheProtocolversionrepresentstheversion
oftheHTTPprotocolbeingused.
Therequestheadercontainsusefulinformationabouttheclientenvironmentand
theentitybodyoftherequest.Forexample,itcouldcontainthelanguagethe
browserissetfor,thelengthoftheentitybody,andsoon.Eachheaderis
separatedbyacarriagereturn/linefeed(CRLF)sequence.
Betweentheheadersandtheentitybody,thereisablankline(CRLF)thatis
importanttotheHTTPrequestformat.TheCRLFtellstheHTTPserverwhere
theentitybodybegins.InsomeInternetprogrammingbooks,thisCRLFis
consideredthefourthcomponentofanHTTPrequest.
InthepreviousHTTPrequest,theentitybodyissimplythefollowingline:
LastName=Franks&FirstName=Michael
TheentitybodycouldeasilybecomemuchlongerinatypicalHTTPrequest.
HTTPrequestMethods
EachHTTPrequestcanuseoneofthemanyrequestmethodsasspecifiedinthe
HTTPstandards.TheHTTP1.1requestmethodsandthedescriptionsofeach
methodaregiveninTableI.1.
TableI.1.HTTP1.1requestMethods
Method
Description
GET
GETisthesimplest,andprobably,mostusedHTTPmethod.GETsimply
retrievesthedataidentifiedbytheURL.IftheURLreferstoascript(CGI,
servlet,andsoon),itreturnsthedataproducedbythescript.
HEAD
TheHEADmethodprovidesthesamefunctionalityasGET,butHEADonly
returnsHTTPheaderswithoutthedocumentbody.
POST
LikeGET,POSTisalsowidelyused.Typically,POSTisusedinHTML
forms.POSTisusedtotransferablockofdatatotheserverintheentity
bodyoftherequest.
OPTIONS TheOPTIONSmethodisusedtoqueryaserveraboutthecapabilitiesit
provides.Queriescanbegeneralorspecifictoaparticularresource.
PUT
ThePUTmethodisacomplementofaGETrequest,andPUTstoresthe
entitybodyatthelocationspecifiedbytheURI.ItissimilartothePUT
functioninFTP.
DELETE TheDELETEmethodisusedtodeleteadocumentfromtheserver.The
documenttobedeletedisindicatedintheURIsectionoftherequest.
TRACE
TheTRACEmethodisusedtotractthepathofarequestthroughfirewall
andmultipleproxyservers.TRACEisusefulfordebuggingcomplex
networkproblemsandissimilartothetraceroutetool.
Warning
HTTP1.0onlyhasthreerequestmethods:GET,HEAD,andPOST.
Ofthesevenmethods,onlyGETandPOSTarecommonlyusedinanInternet
application.
HTTPResponses
Similartorequests,anHTTPresponsealsoconsistsofthreeparts:
Protocol—Statuscode——Description
Responseheaders
Entitybody
ThefollowingisanexampleofanHTTPresponse:
HTTP/1.1200OK
Server:Microsoft-IIS/4.0
Date:Mon,3Jan199813:13:33GMT
Content-Type:text/html
Last-Modified:Mon,11Jan199813:23:42GMT
Content-Length:112
<HTML>
<HEAD>
<TITLE>HTTPResponseExample</TITLE></HEAD><BODY>
WelcometoBrainySoftware
</BODY>
</HTML>
Thefirstlineoftheresponseheaderissimilartothefirstlineoftherequest
header.ThefirstlinetellsyouthattheprotocolusedisHTTPversion1.1,the
requestsucceeded(200=success),andthateverythingwentokay.
Theresponseheaderscontainusefulinformationsimilartotheheadersinthe
request.TheentitybodyoftheresponseistheHTMLcontentoftheresponse
itself.TheheadersandtheentitybodyareseparatedbyasequenceofCRLFs.
SystemArchitecture
Thissectionismeanttogiveyouthebigpictureofasoftwareapplicationsystem
utilizingJavaorothertechnologies.Thissectiontakesthecommonapproachof
introducingsoftwaresystemarchitecturebyobservinghowithasevolved.
Awell-designedsoftwareapplicationispartitionedintoseparatelogicalparts
calledlayers.Eachlayerhasadifferentresponsibilityintheoverallarchitecture.
Theselayersarepurelyabstractions,anddonotcorrespondtophysical
distribution.
Typicallayersinasoftwaresystemareasfollows:
Presentationlayer.Inthislayerarepartsthathandletheuserinterfaceand
userinteraction.
Businesslogiclayer.Thislayercontainscomponentsthathandlethe
programminglogicoftheapplication.
Datalayer.Thislayerisusedbythebusinesslogiclayertopersiststate
permanently.Thislayernormallyconsistsofoneormoredatabaseswhere
dataisstored.However,othertypesofdatastorecouldalsobeused.For
example,itisnowverycommontouseXMLdocumentsasstoragetokeep
data.
TheTwo-TierArchitecture
Atwo-tieredapplicationisasimpleclient-serverapplicationinwhichthe
processingworkloadfallsontotheclientcomputer'sshouldersandtheserver
simplyactsasatrafficcontrollerbetweentheclientandthedata.Theterm"fat
client"forthistypeofarchitectureisduetothebulkofprocessingrequirements
attheclientside.Inthisarchitecture,thepresentationlayerandthebusiness
logiclayerarehostedinonetierandthedatalayerisonanothertier.FigureI.1
showsatwo-tierarchitecture.
FigureI.1.Atwo-tieredapplication.