©2012MartyHallCustomizedJavaEETraining::TheJSP2ExpressionLanguage2OriginalsofSlidesandSourceCodeforExamples:©2012MartyHallCustomizedJavaEETraining:://courses.coreservlets.com/.JSF2,PrimeFaces,Servlets,JSP,Ajax(withjQuery),GWT,Androiddevelopment,Java6and7programming,SOAP-basedandRESTfulWebServices,Spring,Hibernate/JPA,XML,Hadoop,andcustomizedcombinationsoftopics.TaughtbytheauthorofCoreServletsandJSP,MoreServletsandJSP,andthistutorial.Availableatpublicvenues,orcustomizedversionscanbeheldon-siteatyourorganization.Contacthall@coreservlets.comfordetails.Agenda•Motivatinguseoftheexpressionlanguage•Understandingthebasicsyntax•UnderstandingtherelationshipoftheexpressionlanguagetotheMVCarchitecture•Referencingscopedvariables•Accessingbeanproperties,arrayelements,Listelements,andMapentries•Usingexpressionlanguageoperators•Evaluatingexpressionsconditionally4©2012MartyHallCustomizedJavaEETraining::SimplifyingMVCOutputPages5ServletsandJSP:PossibilitiesforHandlingaSingleRequest•Servletonly.Workswellwhen:–Outputisabinarytype.E.g.:animage–Thereisnooutput.E.g.:youaredoingforwardingorredirectionasinSearchEngineexample.–Format/layoutofpageishighlyvariable.E.g.:portal.•JSPonly.Workswellwhen:–Outputismostlycharacterdata.E.g.:HTML–Format/layoutmostlyfixed.•Combination(MVCarchitecture).Neededwhen:–Asinglerequestwillresultinmultiplesubstantiallydifferent-lookingresults.–YouhavealargedevelopmentteamwithdifferentteammembersdoingtheWebdevelopmentandthebusinesslogic.–Youperformcomplicateddataprocessing,buthavearelativelyfixedlayout.6ImplementingMVCwithRequestDispatcher1.Definebeanstorepresentresultdata–OrdinaryJavaclasseswithatleastonegetBlahmethod2.Useaservlettohandlerequests–Servletreadsrequestparameters,checksformissingandmalformeddata,callsbusinesslogic,etc.3.Obtainbeaninstances–Theservletinvokesbusinesslogic(application-specificcode)ordata-accesscodetoobtaintheresults.4.Storethebeanintherequest,session,orservletcontext–TheservletcallssetAttributeontherequest,session,orservletcontextobjectstostoreareferencetothebeansthatrepresenttheresultsoftherequest.7ImplementingMVCwithRequestDispatcher(Continued)5.ForwardtherequesttoaJSPpage.–TheservletdetermineswhichJSPpageisappropriatetothesituationandusestheforwardmethodofRequestDispatchertotransfercontroltothatpage.6.Extractthedatafromthebeans.–TheJSPpageaccessesbeanswithjsp:useBeanandascopematchingthelocationofstep4.Thepagethenusesjsp:getPropertytooutputthebeanproperties.–TheJSPpagedoesnotcreateormodifythebean;itmerelyextractsanddisplaysdatathattheservletcreated.8DrawbackofMVC•Maindrawbackisthefinalstep:presentingtheresultsintheJSPpage.–jsp:useBeanandjsp:getProperty•Clumsyandverbose•Cannotaccessbeansubproperties–JSPscriptingelements•Resultinhard-to-maintaincode•DefeatthewholepurposebehindMVC.•Goal–Moreconcise,succinct,andreadablesyntax•AccessibletoWebdevelopers–Abilitytoaccesssubproperties–Abilitytoaccesscollections9MainPointofELforNewMVCApps•Bean–publicStringgetFirstName(…){…}•Servlet–CustomersomeCust=lookupService.findCustomer(…);–request.setAttribute(customer,someCust);–(UseRequestDispatcher.forwardtogotoJSPpage)•JSP–h1Firstnameis${customer.firstName}/h1•IfthisisallyoueverknowabouttheExpressionLanguage,youarestillinprettygoodshape10MainPointofELforMVCAppsthatareUpgradingfromJSP1.2•WheninJSP2.x-compliantserverwithcurrentweb.xmlversion,change:jsp:useBeanid=someNametype=somePackage.someClassscope=request,session,orapplication/jsp:getPropertyname=someNameproperty=someProperty/•To:${someName.someProperty}•Bean,servlet,businesslogic–Remainexactlythesameasbefore11AdvantagesoftheExpressionLanguage•Conciseaccesstostoredobjects.–Tooutputa“scopedvariable”(objectstoredwithsetAttributeinthePageContext,HttpServletRequest,HttpSession,orServletContext)namedsaleItem,youuse${saleItem}.•Shorthandnotationforbeanproperties.–TooutputthecompanyNameproperty(i.e.,resultofthegetCompanyNamemethod)ofascopedvariablenamedcompany,youuse${company.companyName}.ToaccessthefirstNamepropertyofthepresidentpropertyofascopedvariablenamedcompany,youuse${company.president.firstName}.•Simpleaccesstocollectionelements.–Toaccessanelementofanarray,List,orMap,youuse${variable[indexOrKey]}.ProvidedthattheindexorkeyisinaformthatislegalforJavava