已阅读5页,还剩50页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
WebWork2.0,StruttingtheOpenSymphonyWay,WhatisOpenSymphony?,AnopensourceprojectencompassingqualityenterpriseJavacomponentsManywellknownqualitycomponentsWebWork/XWorkSiteMeshOSCacheOSUserOSWorkflowQuartz,WhatisWebWork2.0?,ThesecondgenerationofWebWorkAwebMVCframeworkAwrapperontopofagenericCommandPatternimplementation(XWork)Asmallbutpowerfultaglibrary,HowdoesWebWorkuseXWork?,XWorkisagenericcommandpatternimplementationWebWorktranslatesbetweenthewebworldandXWork,WhatdoesXWorkprovide?,CommandpatternimplementationActionsarecommandobjectsinXWorkAddsadvancedfeaturesInterceptorsIncludessettingparameters,workflow,etcResultsIncludesoneforchainingtoanotherActionSimpleIoC(or“DependencyInjection)containerPowerfulexpressionlanguageOGNLFlexibletypeconversionMetadatadrivenvalidationframework,WhatdoesWebWorkadd?,AdapterforHTTPrequest/responseIntegrationofSession/ApplicationscopesServletDispatchertranslatesHTTPrequestsintoActionexecutionRequestparameterspassedtoActionResultsforservletredirect,ActionSupport,ActionsareonlyrequiredtoimplementtheActioninterfaceActionSupportisausefulbaseclassImplementsActionProvideserrormessagesupportFieldandActionlevelmessagesMessagesautomaticallyusedbyUItagsProvidesmessageinternationalizationMessagebundleforeachActionLooksupclasshierarchyUItagsuseinternationalizationsupporttofindtextAllfeaturesbasedonInterfaces,soyoucanimplementyourownfromscratch!,A“HelloWorld”example,SimplerequirementsTaketheusersnameandgenerateahellomessagepersonalizedforthemIftheuserentersabirthday,calculatehowlonguntiltheirbirthdayShowsImplementinganActionConfiguringWebWorkUsingthetaglibTypeconversionErrormessages,HelloWorldAction.java,publicclassHelloWorldActionextendsActionSupportprivateUseruser=newUser();publicUsergetUser()returnuser;publicintgetDaysTillNextBirthday()publicStringexecute()throwsExceptionStringname=getUser().getName();if(name=null)|(name.trim().equals()addFieldError(,Youmustenteraname.);if(hasErrors()returnINPUT;returnSUCCESS;,User.java,publicclassUserprivateStringname;privateDatebirthday;publicStringgetName()returnname;publicvoidsetName(Stringname)=name;publicDategetBirthday()returnbirthday;publicvoidsetBirthday(Datebirthday)this.birthday=birthday;,form.jsp,HelloWorldExample,success.jsp,HelloHello!daystillyournextbirthday.,Xwork.xmlforHelloWorld,/field/form.jsp/field/success.jsp/field/form.jsp,UnittestingActions,XWork/WebWorkshinesintestabilityActionshavenowebdependencies,soyoudonthavetosetupmocks,etc.2waysoftestingActionsJustcreateanewinstance,setsomeproperties,andexecuteUsetheframeworkdirectlyinyourteststoexecuteitwiththeInterceptors,etc.,HelloWorldActionTest,publicvoidtestFieldErrorAddedWhenNoUserName()throwsExceptionHelloWorldActionaction=newHelloWorldAction();assertEquals(Action.INPUT,action.execute();assertTrue(action.hasFieldErrors();MapfieldErrors=action.getFieldErrors();assertTrue(fieldErrors.containsKey();ListuserNameErrors=(List)fieldErrors.get();assertEquals(1,userNameErrors.size();assertEquals(Youmustenteraname.,userNameErrors.get(0);,Notesontheexample,ComposepagemodelfrommanyobjectsusingexpressionlanguageUItagsautomaticallyshowfielderrormessagesnexttotheformfieldReturncodefromActiondetermineswhichpagetodisplayMuchofthe“magic”isintheinterceptors,Interceptors:DomainAOP,InterceptorsallowcustomcodeintothecallstackMuchofthecorefunctionalityofXWorkandWebWorkisimplementedasInterceptorsAddcustomInterceptors,TimerInterceptor,TimerInterceptoristhesimplestInterceptorJusttimestheexecutionoftheActionpublicStringintercept(ActionInvocationinvocation)throwsExceptionif(log.isInfoEnabled()longstartTime=System.currentTimeMillis();Stringresult=invocation.invoke();longexecutionTime=System.currentTimeMillis()-startTime;Stringnamespace=invocation.getProxy().getNamespace();,LoggingInterceptor,LoggingInterceptorextendstheAroundInterceptorAroundInterceptorprovidescallbacksforbefore()andafter()theActionisexecutedpublicclassLoggingInterceptorextendsAroundInterceptorprotectedvoidafter(ActionInvocationinvocation,Stringresult)throwsExceptionlogMessage(invocation,FINISH_MESSAGE);protectedvoidbefore(ActionInvocationinvocation)throwsExceptionlogMessage(invocation,START_MESSAGE);,OtherInterceptors,SettingParametersParameterInterceptorStaticParameterInterceptorChainingInterceptorConversionErrorInterceptorDefiningWorkflowDefaultWorkflowInterceptorPrepareInterceptorServletConfigInterceptorPreventingduplicateposts2typesoftokeninterceptors,InterceptorStacks,InterceptorscanbegroupedintonamedInterceptorStacks2definedinwebwork-default.xmldefaultStackvalidationWorkflowStackStackscanbebuiltofotherstacksandinterceptors,Model-Drivenvs.Field-Driven,2typesofActionspossible:Model-drivenActionhasmethodsreturningyourmodelclasses(myAction.getUser()FieldsintheviewarefieldsofyourmodelViewsreferdirectlytoyourmodel(property=)ExcellentbecauseitallowsmodelreuseField-drivenActionhasfieldsofitsown,whicharefieldsintheviewexecute()collatesfieldsandinteractswiththemodelViewsrefertoactionfields(property=daysTillNextBirthday)UsefulwhereformisnotparalleltomodelAswecanseeinourAction,thetwocanbemixed,ModelDrivenInterface,XWork/WebWorkalsosupportsmodel-drivenActionsmoredirectlyTheModelDrivenInterfacehasonemethod:publicObjectgetModel()Propertiesofthemodelwillbedirectlyavailable,i.e.“name”insteadof“”AppliestoUItags,formfieldnames,etc.,MakingHelloWorldModelDriven,MaketheclassimplementModelDrivenChangegetUser()togetModel()publicclassHelloWorldActionextendsActionSupportimplementsModelDrivenpublicObjectgetModel()returnuser;,ModelDriven:ChangestotheJSP,Change“”,etc.tojust“name”Inform.jspInsuccess.jspHello!daystillyournextbirthday.,ApplyingtheModelDrivenInterceptor,Inxwork.xml/model/form.jsp/model/success.jsp/model/form.jsp,LookingattheModelInterceptor,TheModelInterceptorpushestheModelontotheValueStack,WhatistheValueStack?,TheValueStackbuildsastackofobjectsObjectsareusedtofindpropertyvaluesTheValueStackallowstheexpressionlanguagetofindpropertyvaluesacrossmultipleobjects,HowistheValueStackused?,TheActioninstanceisalwayspushedontotheValueStackTheModelispushedonbytheModelInterceptorTheUItagsuseittopushvaluesonduringtheirscopeandevaluateexpressionsThetagpushesthecurrentitemontothestackThetagpushesabeaninstanceonThetagevaluatesanexpressionagainsttheValueStackAlltagattributevaluesareevaluatedagainstthestackwhenbeingsetontothetaginstances,TheOGNLexpressionlanguage,ForexpressionsWWusesOGNL(ObjectGraphNavigationLanguage)anexpressionandbindinglanguageforgettingandsettingpropertiesofJavaobjectsNormallythesameexpressionisusedforbothgettingandsettingthevalueofapropertyEasytolearn,yetpowerfulIncrementallycompiledexpressions-fast!Embeddedeverywhereviews,ValueStack,*.xmlIndependentlyrunOpenSourceproject-,OGNLsamples,TheXWorkValidationFramework,SeparatesvalidationfromActionclassesAllowsfordifferentvalidationsindifferentcontextsforthesameobjectProvideshooksforlocalizedvalidationmessages2typesofvalidators,Objectlevelandfieldlevel,HelloWorldAction-validation.xml,Youmustenteraname.ValidationfileinthesamepackageastheclassDefinesonefieldvalidatorandtheerrormessagetoaddifitfails,BundledValidators,Changestoxwork.xml,/field/success.jsp/field/form.jspvalidationWorkflowStackisfromwebwork-default.xml,ChangestotheAction,Theexecute()methodcanjustreturnSUCCESSpublicStringexecute()throwsExceptionreturnSUCCESS;Thevalidationofthe“”propertyishandledbythevalidationinterceptorTheworkflowinterceptorreturnsINPUTifthereareanyerrorsaddedtotheAction,WhatisInversionofControl?,IoCremovestheonusofmanagingcomponentsfromyourbusinesslogicintoacontainer.Containermanageslifecyclesanddependenciesbetweencomponents.EJBisIoC,butwithastaticlistofservicesSecurity,persistenceandtransactionsJakartaAvalon,SpringsBeanFactory,andPicoContainerareallIoCcontainers,AdvantagesofIoC,PromotessimplicityanddecouplingComponentsdescribethemselvesDependenciesarediscoveredautomaticallyAdherestoLawofDemeterClassescoupledtoonlywhattheyuseEncouragessmallerresponsibilityclassesLeadstobetterinterface/implseparationUnittestsbecomefarsimplertheybecomemini-containers,IoCinXWork/WebWork,XWorkprovidesasimpleIoCcontainerWebWorkprovidesahierarchyofcontainersmappedtowebscopesApplicationSessionRequestXWorkActionComponentsspecifyonlywhichservicestheyrequireviainterfaces(egShoppingCartAware)Configurationfiledefinescomponentimplementationsandscopes.,AShoppingCartService,AShoppingCartservice-providesauserscart(sessionscoped)ShoppingCartAware.java:publicinterfaceShoppingCartAwarepublicvoidsetShoppingCart(ShoppingCartcart);ShoppingCart.java:publicinterfaceShoppingCartpublicvoidaddPet(Petpet);publicvoidremovePet(Petpet);publicbooleanisEmpty();publicintsize();publicListgetPets();,APetStoreService,APetStoreservice-providesmanagementofourpetinventory(applicationscoped)PetStoreAware.java:publicinterfacePetStoreAwarepublicvoidsetPetStore(PetStorestore);PetStore.java:publicinterfacePetStorevoidsavePet(Petpet);voidremovePet(Petpet);ListgetPets();PetgetPet(longid);,AserviceclientAction,publicclassAddToCartimplementsAction,PetStoreAware,ShoppingCartAware.publicvoidsetPetStore(PetStoreps)this.petStore=ps;publicvoidsetShoppingCart(ShoppingCartc)this.cart=c;publicStringexecute()throwsExceptionif(cart=null|petId=0)returnERROR;Petpet=petStore.getPet(petId);cart.addPet(pet);returnSUCCESS;,ConfiguringServices,Theseservicesareconfiguredincomponents.xmllikeso:applicationorg.petsoar.pets.DefaultPetStoreorg.petsoar.pets.PetStoreAwaresessionorg.petsoar.cart.SimpleShoppingCartorg.petsoar.cart.ShoppingCartAware,AchievingreusewithWebWork,WebWorkprovidesmanyopportunitiesformodularizingandreusingcomponentsMakeInterceptorstodoworkbeforeandaftertheActionisexecutedCreateserviceswhichareappliedviaIoCCreateActionbaseclassesCreatereusableUIcomponentsCreatereusableapplicationmodules,ReusableUIcomponents,TheWebWorkUItagsareimplementedusingVelocitytemplatesYoucanprovideyourowntemplatesforthetagsThetagletsyouuseanytemplateExamplesAdatepickertemplateErrormessagetemplate,UItagrendering,UItagsuseVelocitytoactuallyre
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025版物品租赁合同范本
- 2025协商离职合同的格式
- 医院科室人员介绍
- 2025版白内障常见症状及护理要领
- 2025版弥漫性血管内凝血常见症状及护理注意事项培训
- 2025版痔疮症状诊断与护理方法
- 20以内退位减法口算方法
- 2025版胃溃疡常见症状及消化系统疾病护理指导
- 一级注册计量师测量数据处理与计量专业实务试题及答案
- 带图的数据分析
- 某部队副食品供货项目配送方案
- 北师大版 四级上册数学 数学好玩(省级作业设计大赛作品)
- MSA-GRR数据自动生成工具演示教学
- 【语文】北京市小学六年级上册期中试题(含答案)
- 电梯的门系统
- 跨国公司外汇资金集中运营管理业务方案
- 曾国藩识人用人之道
- 土默特右旗高源矿业有限责任公司高源煤矿2022年度矿山地质环境年度治理计划
- 基于BIM的莆田第25中教学楼项目招标造价管理
- 中国农业银行笔试题库(含答案)
- 基于单元视角解读教学设计 选择性必修一 植物生命活动的调节 环境因素参与调节植物的生命活动
评论
0/150
提交评论