Tải bản đầy đủ - 0 (trang)
Chapter 2. Inside the Web Tier

Chapter 2. Inside the Web Tier

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

2.1AnArchitectureOverview

Thissectionpresentsahigh-levelarchitecturalviewofaStruts

application.Althoughthissectionshowsanarchitectureforan

enterpriseapplication,notallapplicationswrittenusingStruts

willbeofthissizeandmakeup.However,thistypeof

applicationdoesallowustopresentmanyfacetsofhowStruts

applicationsmaybeconfigured.

ManyapplicationsespeciallyJ2EEapplicationscanbedescribed

intermsoftheirtiers.Theapplication'sfunctionalityis

separatedacrossthesetiers,orfunctionallayers,toprovide

separationofresponsibility,reusability,improvedscalability,and

manyotherbenefits.Theseparationoftiersmaybeaphysical

separationwhereeachislocatedonaseparatehardware

resource,oritmaybepurelylogical.Inthelattercase,oneor

moretiersarecollocated(i.e.,arrangedorgroupedtogether)

onthesamehardwareresource,andtheseparationexistsin

termsofsoftwarecomponents.Figure2-1illustratesthetiers

thatmaybeusedbyatypicalStrutsapplication.



Figure2-1.Functionalapplicationtiers



NoteveryStrutsapplicationwillcontainallofthetiers

illustratedinFigure2-1.Formanysmallerapplications,the

middletiermayconsistprimarilyofawebcontainerthat

interactsdirectlywithadatabaseintheenterpriseinformation

system(EIS)tier.



WhatIsaContainer?

TherearemanydifferenttypesofcontainersEJBcontainers,webcontainers,

servletcontainers,andsoon.Ingeneral,containersprovideahosting

environmentforsoftwarecomponentstorunin.Containersprovidegeneral

servicesthatthecomponentswithintheenvironmentcanuse,sothatthe

componentdevelopersdon'thavetoworryaboutprovidingtheseservices.Aweb

containerallowsservlets,JSPcomponents,andotherJavaclassestobe

deployedandexecutedwithinthecontainer.ServicessuchastheJavaNaming

andDirectoryInterface(JNDI),connectionpooling,andtransactionservicescan

beconfiguredatthecontainerlevelsimilartothewayinwhichEJBcontainers

managesecurity,transactions,andbeanpoolingandthecomponentdevelopers

don'thavetoworryaboutmanagingtheseresources.

Whenusingtheservicesprovidedbyacontainer,componentdevelopersmay

havetogiveupsomecontroloftheenvironmenttothecontainer.Third-party

vendors,whomustfollowcertainguidelinesthatareexplicitlylaidoutinpublic

specifications,buildthesecontainers.Althougheachvendorisallowedto

implementcertainportionsofthecontainerinaproprietarymanner,theymust

followthespecificationstoensurethatapplicationsareportable.



2.1.1TheClientTier

Theclienttierprovidesawayforuserstointeractwiththe

application.Thisinteractionmaybethroughawebbrowser,or

itmaybeprogrammatic,throughawebservicesinterface.

Regardlessofthetypeofclient,theinteractionincludes

submittingarequestandreceivingsometypeofresponsefrom

themiddletier.

InthecaseoftheStrutsframework,themostcommontypeof

clientisawebbrowser.However,itisalsopossibletohave

clientssuchaswirelessdevicesandJavaapplets.



2.1.2TheWebTier



Figure2-1showsthemiddletierasanaggregateoftheweb

tierplussometypeofapplicationservercomponent(inthis

case,anEJBcontainer).Thesetwotiersoftenarecombined,

andmanyapplicationserversincludewebtierfunctionality.

Thewebtierallowstheclienttiertocommunicateandinteract

withapplicationlogicthatresidesinothertiers.Inmore

traditionalwebapplications,it'snotuncommonforsomeorall

oftheapplicationlogictoresideinthistier.Inlarger,

enterprise-scaleapplications,thewebtieractsasatranslator

andmapsHTTPrequestsintoserviceinvocationsonthemiddle

tier.

Thewebtieralsoisresponsibleformanagingscreenflowbased

onapplicationanduserstate.Thewebtiercommunicateswith

eitheradatabaseor,inthecaseofanenterpriseapplication,an

applicationserver.Thewebtieristhegluethatbindsclient

applicationstothecorebackendbusinesssystems.

Thecomponentsthatresideinthewebtierallowdevelopersto

extendthebasicfunctionalityofawebservice.Inthecaseof

Struts,itdoesthisthroughframeworkcomponentsthatrunina

servletcontainer.



2.1.3TheMiddleTier

Themiddletierisoftenreferredtoasthe"applicationtier"or

"server."Thisisdueinparttothefactthatthereisoftenan

applicationserverwithinthistier.NotallStrutsapplications

haveanapplicationtier.Thisisespeciallytrueforsmallweb

applicationsmanysmallprojectsforgousingalargeapplication

serverandcommunicatedirectlywithadatabaseorsomeother

datastore.Whenanapplicationserverispresent,thewebtier

communicateswithitusingsomevariationofRemoteMethod

Invocation(RMI).IfanEJBserverispresentintheapplication

tier,thecommunicationprotocolisRMIoverIIOP(Internet



Inter-ORBProtocol).



RMIoverIIOP

RemoteMethodInvocation(RMI)allowsmethodstobeinvokedonremote

objects.Java'simplementationofRMI,knownastheJavaRemoteMethod

Protocol(JRMP),hasbeenaroundforquitesometimeandisspecifically

designedforJava-to-Javaremotecommunications.

OneoftheissueswithJRMPisthataJVMmustberunningonboththeclientand

theserver.Withthenumberofso-calledlegacyapplicationsthatarewrittenin

languagessuchasC++,Javaneededawaytocommunicatewiththesesystems.

ThisiswhereRMIoverIIOPhelpsout.

TheInternetInter-ORBProtocol(IIOP)wasdesignedtoallowdistributed

componentstocommunicatewithoneanotherusingTCP/IP.IIOPislanguageandplatform-independent.

ByusingRMIontopofIIOP,Javacancommunicatewithapplicationswrittenin

manyotherlanguagesandonvariousplatforms.RMI/IIOP,asitofteniswritten,

isrequiredtobesupportedbyallEJBserversandexistsintheEJBandJ2EE

specifications.



Whenincluded,theapplicationtiermightprovideamore

scalable,fault-tolerant,andhighlyavailablearchitecture.Oneof

themainpurposesofusinganapplicationtieristoseparatethe

responsibilitiesofpresentationfromthoseofthemodelandthe

businessrulesfortheapplication.Today,manywebapplications

useEJBserversfortheirapplicationtiers.Theymaynotuseall

availableaspectsoftheJ2EEarchitecture,suchasEJBs,but

thereareotherbenefitsthatcanbeleveragedfromaJ2EE

serversuchasJavaMail,JDBCandJMStonameafew.



2.1.4TheEnterpriseInformationSystemTier

TheEIStiercontainsdataandservicesthatareused

throughouttheenterprise.Itprovidesaccesstoenterprise

resourcessuchasdatabases,mainframes,customer



relationshipmanagement(CRM)applications,andresourceplanningsystems.

ThemiddletiercommunicateswithcomponentsintheEIStier

usingresource-specificprotocols.Forexample,tocommunicate

witharelationaldatabase,themiddletiernormallywillusea

JDBCdriver.Forenterpriseresourceplanning(ERP)systems,a

proprietaryadapterbisused,althoughsomeERPsystemsand

otherenterpriseresourcesarestartingtosupportamoreweb

service-likeaccessapproach.



2.1.5WhereDoesStrutsFitIn?

AsillustratedinFigure2-2,theStrutsframeworkresidesinthe

webtier.Strutsapplicationsarehostedbyawebcontainerand

canmakeuseofservicesprovidedbythecontainer,suchas

handlingrequestsviatheHTTPandHTTPSprotocols.Thisfrees

developerstofocusonbuildingapplicationsthatsolvebusiness

problems.



Figure2-2.TheStrutsframeworkisusedwithin

thewebtier



2.2TheHTTPRequest/ResponsePhase

Tobetterillustratehowthewebserverandservletcontainer

worktogethertoserviceclients,thissectiondiscussesthe

protocolforanHTTPrequestandresponse,fromthetimea

clientrequestisreceiveduntiltheserverreturnsaresponse.

Strutsmakesheavyuseoftherequestandresponseobjects,

andacompleteunderstandingoftheround-tripprocesswill

helpclarifysometopicsdiscussedlaterinthebook.



Althoughthebrowserisnottheonlytypeofclientthatcanbeused

withStruts,itcertainlyisthemostcommon.Moreandmoredevelopers

arestartingtouseStrutsforwirelessapplicationsandevensome

interactionwithwebservices,butthewebbrowserremainsthe

predominantclient.



HTTPisbasedonarequest/responsemodel,sotherearetwo

typesofHTTPmessages:therequestandtheresponse.The

browseropensaconnectiontoaserverandmakesarequest.

Theserverprocessestheclient'srequestandreturnsa

response.Figure2-3illustratesthisprocess.



Figure2-3.TheHTTPrequest/responsemodel



Bothtypesofmessagesconsistofastartline,zeroormore

headerfields,andanemptylinethatindicatestheendofthe

messageheaders.Bothmessagetypesalsomaycontainan

optionalmessagebody.

Theformatandmakeupoftherequestandresponsemessages

areverysimilar,butthereareafewdifferences.We'lldiscuss

eachtypeofmessageseparately.



2.2.1TheHTTPRequest

ThestartlineofanHTTPrequestisknownastherequestline.

It'salwaysthefirstlineoftherequestmessage,anditcontains

threeseparatefields:

AnHTTPmethod

Auniversalresourceidentifier(URI)

AnHTTPprotocolversion

AlthoughthereareseveralHTTPmethodsforretrievingdata

fromaserver,thetwousedmostoftenareGETandPOST.The

GETmethodrequestsfromtheservertheresource,indicatedby

therequestURI.IftheURIpointstoadata-producingresource

suchasaservlet,thedatawillbereturnedwithintheresponse

message.AlthoughtheGETmessagecanpassinformationin

thequerystring,thePOSTmethodisusedtoexplicitlypass

datatotheserverthatcanbeusedforprocessingbythe

requestURI.

TheURIidentifiestheresourcethatshouldprocesstherequest.



Forthepurposesofthisdiscussion,itcanbeeitheranabsolute

orarelativepath.ArequestwithaninvalidURIwillreturnan

errorcode(typically404).

TheHTTPrequestprotocolversionidentifiestotheserverwhich

versionoftheHTTPspecificationtherequestconformsto.The

followingexampleillustratestherequestlineforasampleGET

request:

GET/index.htmlHTTP/1.0



YoucanexecutethisexamplebyopeningupaTelnetsessionto

aserverrunningawebserver.Youmustspecifythehostname

andportnumberofthewebserver.Forexample:

telnetlocalhost80



ThentypetheGETcommand.YouwillneedtopressEntertwice

afterissuingthecommand:oncefortheendoftherequestline

andagaintolettheserverknowyouarefinishedwiththe

request.Assumingthere'safilecalledindex.htmlintheroot

directory,theHTMLresponsewillbereturned.(Actually,you

willalwaysseearesponseitjustmaynotbetheonethatyou

expected.)We'lltalkmoreaboutusingTelnettointeractwitha

webserverwhenwediscussredirectsandforwardslaterinthis

chapter.

Asmentionedearlier,theHTTPrequestmaycontainzeroor

moreheaderfields.Requestheaderfieldsallowtheclientto

passtotheserveradditionalinformationabouttherequestand

theclientitself.Theformatofaheaderfield,forboththe

requestandtheresponse,isthenameoftheheaderfield,

followedbyacolon(:)andthevalue.Ifmultiplevaluesare

specifiedforasingleheaderfield,theymustbeseparatedwith



commas.Table2-1listssomeofthemorecommonlyused

requestheaders.

Table2-1.CommonHTTPrequestheaderfields

Name



Accept



Accept-Charset



Purpose

Indicatesthemediatypesthatareacceptablefortheresponse.Ifno

Acceptheaderfieldispresent,theservercansafelyassumethatthe

clientacceptsallmediatypes.AnexampleofanAcceptheadervalue

is"image/gif,image/jpeg".

Indicateswhatcharactersetsareacceptablefortheresponse.Ifthe

Accept-Charsetheaderisnotpresentintherequest,theservercan

assumethatanycharactersetisacceptable.TheISO-8859-1

charactersetcanbeassumedtobeacceptablebyalluseragents.



Accept-Encoding SimilartotheAcceptheaderfield,butfurtherrestrictsthecontentencodingvaluesthatareacceptablebytheclient.Anexampleofan

Accept-Encodingheadervalueis"compress,gzip".



Accept-Language



Indicateswhichlanguagestheclientwouldprefertheresponsetobe

in.AnexampleofanAccept-Languageheadervalueis"en-us,de-li,

es-us".



Indicateswhatencodingmechanismhasbeenappliedtothebodyof

Content-Encoding themessageand,therefore,whatdecodingmechanismmustbeused

togettheinformation.AnexampleofaContent-Encodingheader

valueis"gzip".



Content-Type



Indicatesthemediatypeofthebodysenttotherecipient.An

exampleofaContent-Typeheadervalueis"text/html;charset=ISO8859-1".



Host



Indicatesthehostnameandportnumberoftheresourcebeing

requested,asobtainedfromtheoriginalURL.AnexampleofaHost

headervalueis"www.somehost.com".



Referer



Allowstheclienttospecifytheaddress(URI)oftheresourcefrom

whichtherequestURIwasobtained.Thisheaderisusedmainlyfor

maintenanceandtrackingpurposes.



User-Agent



Containsinformationabouttheclientthatoriginatedtherequest.This

headerisusedmainlyforstatisticalpurposesandtracingofprotocol

violations.AnexampleofaUser-Agentheadervalueis"Mozilla/4.0



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

Chapter 2. Inside the Web Tier

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

×