Tải bản đầy đủ - 0 (trang)
Chapter 15.  Web Applications and Web Services

Chapter 15.  Web Applications and Web Services

Tải bản đầy đủ - 0trang

applicationserversnowalsoofferawaytodeploywebservices,

butthisisnotyetasstandardizedasservletsandweb

applicationdeployment.

ServersthatsupportthefullsetofJavaEnterpriseAPIs

(includingservlets,JSPs,EnterpriseJavaBeans,andusuallyweb

services)arecalledapplicationservers.JBossisafree,open

sourceJavaapplicationserveravailablefrom

http://www.jboss.org,andBEA'sWebLogicisapopular

commercialapplicationserver.Whenwetalkabouthighly

modularapplicationcomponents,weoftenrefertotheir

environmentasacontainer.Whenwewanttotalkspecifically

aboutthepartoftheseserversthatrunsservletsorweb

services,wecanrefertothemastheservletcontainerorweb

servicescontainer.Wemayalsogenericallyrefertothemas

servlettools,servletengines,orservletrunners.

Wewilltrytoavoidtalkingintoomuchdetailaboutparticular

serverenvironments,butwewillusetheApacheProject's

Tomcatserverfortheexamplesinthisbook.Tomcatisa

popular,freeservletandwebapplicationcontainerthatcanbe

usedbyitselforinconjunctionwithotherpopularwebservers.

ItiseasytoconfigureandisapureJavaapplication,soyoucan

useitonanyplatformthathasaJavaVM.Youcandownloadit

fromhttp://jakarta.apache.org/tomcat/.Tomcathasbeen

adoptedbySunaspartoftheJ2EEreferenceimplementation,

soitalwayshasanup-to-dateimplementationofthe

specificationsavailableinbothsourceandbinaryform.Tomcat

Version5.xisrequiredtosupportJavaServletAPIVersion2.4,

but,forourdiscussion,littleelsehaschangedfromearlier

versionsoftheserver.Forourwebservicesexample,we'llhave

togetthereferenceimplementationofTomcatfromSun,asthis

worksbestwiththeJWSDP.

Exceptwherenoted,allofourservletexampleswillwork

equallywellwiththeolderTomcat4.xandtheServlet2.3API.

TheServletAPIsandJavadocumentationcanbedownloaded

directlyfromhttp://java.sun.com/products/servlet/.Youmight



considertakingalookattheJavaservletspecificationwhite

paper,alsoavailableatthatlocation.Itisafairlyreadable

specificationdocument.



15.1.WebApplicationTechnologies

Manydifferentwaysofwritingserver-sidesoftwareforweb

applicationshaveevolvedovertheyears.Earlyon,thestandard

wasCGI,usuallyincombinationwithascriptinglanguagesuch

asPerl.Variouswebserversalsoofferednative-languageAPIs

forpluggablesoftwaremodules.Java,howeverandinparticular

theJavaServletAPIisrapidlybecomingthemostpopular

architectureforbuildingweb-basedapplications.Javaservlet

containersareavailableforvirtuallyeverywebserverand

servletsarebecomingfoundationalfornewlevelsofweb

infrastructure,suchaswebservices.

WhyhasJavabecomesopopularontheserverside?Javais

generallyfasterthanscriptinglanguages,especiallyinaserversideenvironmentwherelong-runningapplicationscanbehighly

optimizedbytheVM.Servletshaveanadditionalspeed

advantageovertraditionalCGIprograms,becauseservlets

executeinamultithreadedwaywithinoneinstanceofaVM.

OlderCGIapplicationsrequiredtheservertostartaseparate

process,pipedatatoit,andreceivetheresponseasastream.

TheuniqueruntimesafetyofJavaalsobeatsmostnativeAPIs

inaproductionweb-serverenvironment,whereitwouldbevery

badtohaveanerranttransactionbringdowntheserver.Java's

portabilityalsomeansthatserver-sideapplicationscanbe

scaleduprapidlyacrossdifferenttypesofhardwarewithout

significantportingissues.Inmanyways,Javahasreallyproven

itselfinthis"businessenvironment"toagreaterextentthanin

theWindows-dominateddesktopworld.

Speedandsafetyarefactors,butperhapsthemostimportant

reasonforusingJavaisthatitmakeswritinglargeandcomplex

applicationsmuchmoremanageable.Javaservletsmaynotbe

quiteaseasytowriteasscripts,buttheyareeasiertoupdate

withnewfeatures,andservletsarefarbetteratscalingfor

complex,high-volumeapplications.Fromservletcode,youcan



accessallthestandardJavaAPIswithintheVMwhileyour

servletsarehandlingrequests.ThismeansthatyourJava

servletcodecanworkwellinamultitieredarchitecture,

accessing"live"databaseconnectionswithJDBCor

communicatingwithothernetworkservicesthathavealready

beenestablished.Thiskindofbehaviorhasbeenhackedinto

CGIenvironments,butforJava,itisbothrobustandnatural.

Beforewemoveon,weshouldalsomentionservlets'

relationshipstoothertechnologies:JavaServerPages(JSPs),

XML/XSL,andapplicationframeworkssuchasStrutsandJava

ServerFaces(JSF).We'lltalkmoreaboutthetechnologies

involvedinwebserviceslaterinthechapter.



15.1.1.JSPs

JSPsareadocument-centricwaytowriteserver-side

applications.TheyconsistofHTMLcontentwithspecializedtag

librariesandactiveJava-likesyntaxembeddedwithinthe

pages.JSPsarecompileddynamicallybythewebserverinto

JavaservletsandcanworkwithJavaAPIsdirectlyandindirectly

togeneratedynamiccontentforthepages.Althoughallofthe

workstilloccursontheserverside,JSPsallowthedeveloperto

workasifhewerewritingcoderightinthepage,whichhas

bothbenefitsanddrawbacks.Thebenefitofthissortof

"immediatemode"programmingstyleisthatitiseasytograsp

andquicktocrankout.Thedrawbackisthatitcanleadtoan

unmanageablemixofbusinesslogicandpresentationlogic.The

morecodethatappearsmixedinwiththestaticcontent,the

greaterthemaintenanceheadache.

Mostlarge-scaleJSPprojectstodayutilizetaglibrariesto

minimizead-hoccodeinthepages.JSPsarealsonowroutinely

usedincombinationwithcontrollerservletsorotherback-end

frameworkcontrollercomponentsthatdotheheavyliftingof

businesslogicforthem.Inthiscase,thetermcontrollerrefers



totheModel-View-Controller(MVC)separationofconcernsthat

weintroducedearlierwhentalkingaboutSwingGUIs.

MaintainingthisseparationleveragestheadvantagesofJSP

whileavoidingitspitfalls.



15.1.2.XML

XMLisapowerfulsetofstandardsforworkingwithstructured

informationintextform.TheExtensibleStylesheetLanguage

(XSL)isalanguagefortransformingXMLdocumentsintoother

kindsofdocuments,includingHTML.Thecombinationof

servletsthatcangenerateXMLcontentandXSLstylesheets

thatcantransformcontentforpresentationisaveryexciting

direction,coveredindetailinChapter24.Aswe'llseelater,web

servicesuseXMLastheirnativedataformat,makingthem

completelyportableacrossplatformsandlanguages.



15.1.3.ApplicationFrameworks

Oneofthemostpopularframeworksforbuildingweb

applicationsistheApacheFoundation'sStrutsWebApplication

Framework.StrutsimplementstheModel-View-Controller

paradigmbyprovidingbothamodularcontrollercomponent

architectureandanextensivetaglibraryforJSPpage

development.Strutsabstractssomeofthemappingand

navigationaspectsrequiredtogluetogetherawebapplication

throughtheuseofanXML-basedconfigurationfileandalso

addstheabilitytododeclarativemappingofHTMLformsto

Javaobjectsaswellasautomatedvalidationofformfields.

Overtheyears,someofthevalueofStrutshasbeenwhittled

awaybybigimprovementsintheunderlyingServletAPI.As

we'llseeinthischapter,theweb.xmlwebapplication

configurationfilecanaccomplishalotbyitselfandfeatures



suchasservletfiltersanddeclarativefeaturessuchassecurity

andloginhaveaddedagreatdealtothemodularityofservletbasedapplications.Strutscanalsobeabitawkwardandisnot

quiteascleanoreasytounderstandasonemightwish.

However,fornowStrutsisthe800-poundgorillaintheroom

andcommandsalotofattention.Strutshasabigfollowingand

formanypeopleitisaninvaluablepieceoftheweb

infrastructure.YoucandownloadStrutsat

http://struts.apache.org/.

JSFisSun'sresponsetoStruts.Developedoverthepastfew

yearsbytheJavaCommunityProcess(includingsomeofthe

originalStrutspeople)itisintendedtobecomethe"official"

Java-sanctionedweb-applicationframework.JSFbuildsupon

lessonslearnedwithStrutsandrefinestheMVCmodelwith

server-sideapplicationcomponentsandmorefine-grained

navigationandeventmanagement.JSFismaturingafter

initiallybeingreceivedwithmixedreviews.Itisprobablyon

trackforwideradoptioninthefuture.YoucandownloadtheJSF

APIsandlearnmoreat

http://java.sun.com/j2ee/javaserverfaces/.



15.2.WebApplications

Sofarwe'veusedtheterm"webapplication"generically,

referringtoanykindofbrowser-basedapplicationthatis

locatedonawebserver.Nowwearegoingtohavetobemore

precisewiththatterm.InthecontextoftheJavaServletAPI,a

webapplicationisacollectionofservlets,supportingJava

classes,contentsuchasHTMLorJSPpagesandimages,and

configurationinformation.Fordeployment(installationonaweb

server),awebapplicationisbundledintoaWARfile.We'll

discussWARfilesindetaillater,butsufficeittosaythatthey

areessentiallyJARarchivescontainingalltheapplicationfiles

alongwithsomedeploymentinformation.Theimportantthing

isthatthestandardizationofWARfilesmeansnotonlythatthe

Javacodeisportable,butalsothattheprocessofdeployingall

theapplication'spartsitsJavaclasses,resources,and

configurationisstandardized.

AttheheartoftheWARarchiveistheweb.xmlfile.ThisXML

configurationfiledescribeswhichservletsandJSPsaretobe

deployed,theirnamesandURLpaths,theirinitialization

parameters,andahostofotherinformation,includingsecurity

andauthenticationrequirements.

Webapplications,orwebapps,alsohaveaverywell-defined

runtimeenvironment.Eachwebapphasitsown"root"pathon

thewebserver,meaningthatalltheURLsaddressingits

servletsandfilesstartwithacommonuniqueprefix(e.g.,

www.oreilly.com/someapplication/).Thewebapp'sservletsare

alsoisolatedfromthoseofotherwebapplications.Webapps

cannotdirectlyaccesseachother'sfiles(althoughtheymaybe

allowedtodosothroughthewebserver,ofcourse).Eachweb

appalsohasitsownservletcontext.We'lldiscusstheservlet

contextinmoredetail,butinbrief,itisacommonareafor

servletswithinanapplicationtoshareinformationandget

resourcesfromtheenvironment.Thehighdegreeofisolation



betweenwebapplicationsisintendedtosupportthedynamic

deploymentandupdatingofapplicationsrequiredbymodern

businesssystemsandaddresssecurityandreliabilityconcerns.

Webappsareintendedtobecoarse-grained,relatively

completeapplicationsnottobetightlycoupledwithotherweb

apps.Althoughthere'snoreasonyoucan'tmakewebapps

cooperateatahighlevel,forsharinglogicacrossapplications,

youmightwanttoconsiderwebservices,whichwe'lldiscuss

laterinthischapter.



15.2.1.TheServletLifeCycle

Let'sjumpaheadtotheServletAPIitselfsothatwecanget

startedbuildingservletsrightaway.We'llfillinthegapslater

whenwediscussvariouspartsoftheAPIsandWARfile

structureinmoredetail.TheServletAPIisverysimple,almost

exactlyparallelingtheAppletAPI.Therearethreelife-cycle

methodsinit(),service(),anddestroy()alongwithsome

methodsforgettingconfigurationparametersandservlet

resources.Beforeaservletisusedthefirsttime,it'sinitialized

bythecontainerthroughitsinit()method.Thereafter,the

servletspendsitstimehandlingservice()requestsanddoingits

jobuntil(presumably)theserverisshutdown,andthe

servlet'sdestroy()methodiscalled,givingitanopportunityto

cleanup.

Generally,onlyoneinstanceofeachdeployedservletclassis

instantiatedpercontainer.Moreprecisely,itisoneinstanceper

servletentryintheweb.xmlfile,butwe'lltalkmoreabout

servletdeploymentlater.Inthepast,therewasanexceptionto

thatrulewhenusingthespecial,SingleThreadModeltypeofservlet.

AsofServletAPI2.4,single-threadedservletshavebeen

deprecated.

Bydefault,servletsareexpectedtohandlerequestsina

multithreadedway;thatis,theservlet'sservicemethodsmay



beinvokedbymanythreadsatthesametime.Thismeansthat

youcannotstoreclient-relateddataininstancevariablesof

yourservletobject.(Ofcourse,youcanstoregeneraldata

relatedtotheservlet'soperation,aslongasitdoesnotchange

onaper-requestbasis.)Per-clientstateinformationcanbe

storedinaclientsessionobjectontheserverorinaclient-side

cookie,whichpersistsacrossclientrequests.We'lltalkabout

clientstatelateraswell.

Theservice()methodofaservletacceptstwoparameters:a

servlet"request"objectandaservlet"response"object.These

providetoolsforreadingtheclientrequestandgenerating

output;we'lltalkaboutthemindetailintheexamples.



15.2.2.Servlets

ThereareactuallytwopackagesofinterestintheServletAPI.

Thefirstisthejavax.servletpackage,whichcontainsthemost

generalServletAPIs.Thesecondimportantpackageis

javax.servlet.http,whichcontainsAPIsspecifictoservletsthat

handleHTTPrequestsforwebservers.Intherestofthis

section,wearegoingtodiscussservletsasifallservletswere

HTTP-related.Intheory,youcanwriteservletsforother

protocols,butthat'snotwhatwe'recurrentlyinterestedin.

Theprimarytoolprovidedbythejavax.servlet.httppackageis

theHttpServletbaseclass.Thisisanabstractservletthat

providessomebasicimplementationdetailsrelatedtohandling

anHTTPrequest.Inparticular,itoverridesthegenericservlet

service()requestandbreaksitoutintoseveralHTTP-related

methods,includingdoGet(),doPost(),doPut(),anddoDelete().

Thedefaultservice()methodexaminestherequestto

determinewhatkinditisanddispatchesittooneofthese

methods,soyoucanoverrideoneormoreofthemto

implementthespecificwebserverbehavioryouneed.



doGet()anddoPost()correspondtothestandardHTTPGETand

POSToperations.GETisthestandardrequestforretrievingafile



ordocumentataspecifiedURL.POSTisthemethodbywhicha

clientsendsanarbitraryamountofdatatotheserver.HTML

formsarethemostcommonuseforPOST.

Toroundtheseout,HttpServletprovidesthedoPut()anddoDelete(

)methods.Thesemethodscorrespondtoapoorlysupported

partoftheHTTPprotocol,meanttoprovideawaytoupload

andremovefiles.doPut()issupposedtobelikePOSTbutwith

differentsemantics;doDelete()wouldbeitsopposite.These

aren'twidelyused.

HttpServletalsoimplementsthreeotherHTTP-relatedmethods



foryou:doHead(),doTrace(),anddoOptions().Youdon'tnormally

needtooverridethesemethods.doHead()implementstheHTTP

HEADrequest,whichasksfortheheadersofaGETrequestwithout

thebody.HttpServletimplementsthisbydefaultinthetrivial

way,byperformingtheGETmethodandthensendingonlythe

headers.YoumaywishtooverridedoHead()withamore

efficientimplementationifyoucanprovideoneasan

optimization.doTrace()anddoOptions()implementother

featuresofHTTPthatallowfordebuggingandsimple

client/servercapabilitiesnegotiation.Youshouldn'tneedto

overridethese.

AlongwithHttpServlet,javax.servlet.httpalsoincludessubclasses

oftheServletRequestandServletResponseobjects,HttpServletRequest

andHttpServletRe-sponse.Thesesubclassesprovide,respectively,

theinputandoutputstreamsneededtoreadandwriteclient

data.TheyalsoprovidetheAPIsforgettingorsettingHTTP

headerinformationand,aswe'llsee,clientsessioninformation.

Ratherthandocumentthesedryly,we'llshowtheminthe

contextofsomeexamples.Asusual,we'llstartwiththe

simplestpossibleexample.



15.2.3.TheHelloClientServlet



Here'sourservletversionof"Hello,World,"HelloClient:

//file:HelloClient.java

importjava.io.*;

importjavax.servlet.ServletException;

importjavax.servlet.http.*;

publicclassHelloClientextendsHttpServlet{

publicvoiddoGet(HttpServletRequestrequest,

HttpServletResponseresponse)

throwsServletException,IOException{

//mustcomefirst

response.setContentType("text/html");

PrintWriterout=response.getWriter();



out.println(

"HelloClient

+"

Hello,Client

"

+"");

out.close();

}

}



Ifyouwanttotrythisservletrightaway,skipaheadto"WAR

FilesandDeployment,"wherewewalkthroughtheprocessof

runningthisservlet.Simplypackageuptheservletclassfile

alongwithasimpleweb.xmlfilethatdescribesitandplaceiton

yourserver.Butfornow,we'regoingtodiscussjusttheservlet

examplecodeitself,whichisprettysimple.

Let'shavealookattheexample.HelloClientextendsthebase

HttpServletclassandoverridesthedoGet()methodtohandle

simplerequests.Inthiscase,wewanttorespondtoanyGET



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 15.  Web Applications and Web Services

Tải bản đầy đủ ngay(0 tr)

×