JSPModel2.docx
- 文档编号:14353669
- 上传时间:2023-06-22
- 格式:DOCX
- 页数:20
- 大小:65.29KB
JSPModel2.docx
《JSPModel2.docx》由会员分享,可在线阅读,更多相关《JSPModel2.docx(20页珍藏版)》请在冰点文库上搜索。
JSPModel2
Server-SideJava
UnderstandingJavaServerPagesModel2architecture
ExploringtheMVCdesignpattern
Summary
BydevelopingafamiliarWeb-basedshoppingcart,you'lllearnhowtoutilizetheModel-View-Controller(MVC)designpatternandtrulyseparatepresentationfromcontentwhenusingJavaServerPages.GovindSeshadrishowsyououthoweasyitcanbe.(2,000words)
ByGovindSeshadri
Despiteitsrelativelyrecentintroduction,JavaServerPages(JSP)technologyiswellonitswaytobecomingthepreeminentJavatechnologyforbuildingapplicationsthatservedynamicWebcontent.JavadevelopersloveJSPformyriadreasons.Somelikethefactthatitbringsthe"writeonce,runanywhere"paradigmtointeractiveWebpages;othersappreciatethefactthatitisfairlysimpletolearnandletsthemwieldJavaasaserver-sidescriptinglanguage.Butmostconcurononething--thebiggestadvantageofusingJSPisthatithelpseffectivelyseparatepresentationfromcontent.Inthisarticle,Iprovideanin-depthlookathowyoucangainoptimalseparationofpresentationfromcontentbyusingtheJSPModel2architecture.Thismodelcanalsobeseenasaserver-sideimplementationofthepopularModel-View-Controller(MVC)designpattern.PleasenotethatyoushouldbefamiliarwiththebasicsofJSPandservletprogrammingbeforecontinuingon,asIdonotaddressanysyntaxissuesinthisarticle.
So,what'swrongwithservlets?
WhileJSPmaybegreatforservingupdynamicWebcontentandseparatingcontentfrompresentation,somemaystillwonderwhyservletsshouldbecastasideforJSP.Theutilityofservletsisnotinquestion.Theyareexcellentforserver-sideprocessing,and,withtheirsignificantinstalledbase,areheretostay.Infact,architecturallyspeaking,youcanviewJSPasahigh-levelabstractionofservletsthatisimplementedasanextensionoftheServlet2.1API.Still,youshouldn'tuseservletsindiscriminately;theymaynotbeappropriateforeveryone.Forinstance,whilepagedesignerscaneasilywriteaJSPpageusingconventionalHTMLorXMLtools,servletsaremoresuitedforback-enddevelopersbecausetheyareoftenwrittenusinganIDE--aprocessthatgenerallyrequiresahigherlevelofprogrammingexpertise.Whendeployingservlets,evendevelopershavetobecarefulandensurethatthereisnotightcouplingbetweenpresentationandcontent.Youcanusuallydothisbyaddingathird-partyHTMLwrapperpackagelikehtmlKonatothemix.Buteventhisapproach,thoughprovidingsomeflexibilitywithsimplescreenchanges,stilldoesnotshieldyoufromachangeinthepresentationformatitself.Forexample,ifyourpresentationchangedfromHTMLtoDHTML,youwouldstillneedtoensurethatwrapperpackageswerecompliantwiththenewformat.Inaworst-casescenario,ifawrapperpackageisnotavailable,youmayenduphardcodingthepresentationwithinthedynamiccontent.So,whatisthesolution?
Asyoushallsoonsee,oneapproachwouldbetousebothJSPandservlettechnologiesforbuildingapplicationsystems.
Differingphilosophies
TheearlyJSPspecificationsadvocatedtwophilosophicalapproachesforbuildingapplicationsusingJSPtechnology.Theseapproaches,termedtheJSPModel1andModel2architectures,differessentiallyinthelocationatwhichthebulkoftherequestprocessingwasperformed.IntheModel1architecture,showninFigure1,theJSPpagealoneisresponsibleforprocessingtheincomingrequestandreplyingbacktotheclient.Thereisstillseparationofpresentationfromcontent,becausealldataaccessisperformedusingbeans.AlthoughtheModel1architectureshouldbeperfectlysuitableforsimpleapplications,itmaynotbedesirableforcompleximplementations.IndiscriminateusageofthisarchitectureusuallyleadstoasignificantamountofscriptletsorJavacodeembeddedwithintheJSPpage,especiallyifthereisasignificantamountofrequestprocessingtobeperformed.WhilethismaynotseemtobemuchofaproblemforJavadevelopers,itiscertainlyanissueifyourJSPpagesarecreatedandmaintainedbydesigners--whichisusuallythenormonlargeprojects.Ultimately,itmayevenleadtoanuncleardefinitionofrolesandallocationofresponsibilities,causingeasilyavoidableproject-managementheadaches.
Figure1:
JSPModel1architecture
TheModel2architecture,showninFigure2,isahybridapproachforservingdynamiccontent,sinceitcombinestheuseofbothservletsandJSP.Ittakesadvantageofthepredominantstrengthsofbothtechnologies,usingJSPtogeneratethepresentationlayerandservletstoperformprocess-intensivetasks.Here,theservletactsasthecontrollerandisinchargeoftherequestprocessingandthecreationofanybeansorobjectsusedbytheJSP,aswellasdeciding,dependingontheuser'sactions,whichJSPpagetoforwardtherequestto.NoteparticularlythatthereisnoprocessinglogicwithintheJSPpageitself;itissimplyresponsibleforretrievinganyobjectsorbeansthatmayhavebeenpreviouslycreatedbytheservlet,andextractingthedynamiccontentfromthatservletforinsertionwithinstatictemplates.Inmyopinion,thisapproachtypicallyresultsinthecleanestseparationofpresentationfromcontent,leadingtocleardelineationoftherolesandresponsibilitiesofthedevelopersandpagedesignersonyourprogrammingteam.Infact,themorecomplexyourapplication,thegreaterthebenefitsofusingtheModel2architectureshouldbe.
Figure2:
JSPModel2architecture
InordertoclarifytheconceptsbehindtheModel2architecture,let'swalkthroughadetailedimplementationofit:
asampleonlinemusicstorecalledMusicWithoutBorders.
UnderstandingMusicWithoutBorders
Themainview,orpresentation,forourMusicWithoutBordersonlinestoreisfacilitatedbytheJSPpageEShop.jsp(showninListing1).Youwillnoticethatthepagedealsalmostexclusivelywithpresentingthemainuserinterfaceoftheapplicationtotheclient,andperformsnoprocessingwhatsoever--anoptimalJSPscenario.Also,noticethatanotherJSPpage,Cart.jsp(showninListing2),isincludedwithinEShop.jspviathedirective includepage="Cart.jsp"flush="true"/>. Listing1: EShop.jsp <%@pagesession="true"%>
MusicWithoutBorders
action="/examples/servlet/ShoppingServlet" method="POST"> CD: Quantity:
includepage="Cart.jsp"flush="true"/>