`
- 浏览:
45839 次
- 性别:
- 来自:
上海
-
- Chapter14.Integratingwithotherwebframeworks
- 14.1.Introduction
-
SpringcanbeeasilyintegratedintoanyJava-basedwebframework.AllyouneedtodoistodeclaretheContextLoaderListenerinyourweb.xmlanduseacontextConfigLocation<context-param>tosetwhichcontextfilestoload.
- The<context-param>:
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/applicationContext*.xml</param-value>
- </context-param>
- The<listener>:
- <listener>
-
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
-
NOTE:ListenerswereaddedtotheServletAPIinversion2.3.IfyouhaveaServlet2.2container,youcanusetheContextLoaderServlettoachievethissamefunctionality.
-
Ifyoudon'tspecifythecontextConfigLocationcontextparameter,theContextLoaderListenerwilllookfora/WEB-INF/applicationContext.xmlfiletoload.Oncethecontextfilesareloaded,SpringcreatesaWebApplicationContextobjectbasedonthebeandefinitionsandputsitintotheServletContext.
-
AllJavawebframeworksarebuiltontopoftheServletAPI,soyoucanusethefollowingcodetogettheApplicationContextthatSpringcreated.
- WebApplicationContextctx=WebApplicationContextUtils.getWebApplicationContext(servletContext);
-
TheWebApplicationContextUtilsclassisforconvenience,soyoudon'thavetorememberthenameoftheServletContextattribute.ItsgetWebApplicationContext()methodwillreturnnullifanobjectdoesn'texistundertheWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTEkey.RatherthanriskgettingNullPointerExceptionsinyourapplication,it'sbettertousethegetRequiredWebApplicationContext()method.ThismethodthrowsanExceptionwhentheApplicationContextismissing.
- OnceyouhaveareferencetotheWebApplicationContext,youcanretrievebeansbytheirnameortype.Mostdevelopersretrievebeansbyname,thencastthemtooneoftheirimplementedinterfaces.
-
Fortunately,mostoftheframeworksinthissectionhavesimplerwaysoflookingupbeans.NotonlydotheymakeiteasytogetbeansfromtheBeanFactory,buttheyalsoallowyoutousedependencyinjectionontheircontrollers.Eachframeworksectionhasmoredetailonitsspecificintegrationstrategies.
- 14.2.JavaServerFaces
-
JavaServerFaces(JSF)isacomponent-based,event-drivenwebframework.AccordingtoSunMicrosystem'sJSFOverview,JSFtechnologyincludes:
-
AsetofAPIsforrepresentingUIcomponentsandmanagingtheirstate,handlingeventsandinputvalidation,definingpagenavigation,andsupportinginternationalizationandaccessibility.
-
AJavaServerPages(JSP)customtaglibraryforexpressingaJavaServerFacesinterfacewithinaJSPpage.
- 14.2.1.DelegatingVariableResolver
-
TheeasiestwaytointegrateyourSpringmiddle-tierwithyourJSFweblayeristousetheDelegatingVariableResolverclass.Toconfigurethisvariableresolverinyourapplication,you'llneedtoedityourfaces-context.xml.Aftertheopening<faces-config>element,addan<application>elementanda<variable-resolver>elementwithinit.ThevalueofthevariableresolvershouldreferenceSpring'sDelegatingVariableResolver:
- <faces-config>
- <application>
- <variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>
- <locale-config>
-
<default-locale>en</default-locale>
- <supported-locale>en</supported-locale>
- <supported-locale>es</supported-locale>
- </locale-config>
- <message-bundle>messages</message-bundle>
- </application>
-
ByspecifyingSpring'svariableresolver,youcanconfigureSpringbeansasmanagedpropertiesofyourmanagedbeans.TheDelegatingVariableResolverwillfirstdelegatevaluelookupstothedefaultresolveroftheunderlyingJSFimplementation,andthentoSpring'srootWebApplicationContext.ThisallowsyoutoeasilyinjectdependenciesintoyourJSF-managedbeans.
-
Managedbeansaredefinedinyourfaces-config.xmlfile.Belowisanexamplewhere#{userManager}isabeanthat'sretrievedfromSpring'sBeanFactory.
- <managed-bean>
- <managed-bean-name>userList</managed-bean-name>
-
<managed-bean-class>com.whatever.jsf.UserList</managed-bean-class>
- <managed-bean-scope>request</managed-bean-scope>
- <managed-property>
- <property-name>userManager</property-name>
- <value>#{userManager}</value>
- </managed-property>
- </managed-bean>
-
TheDelegatingVariableResolveristherecommendedstrategyforintegratingJSFandSpring.Ifyou'relookingformorerobustintegrationfeatures,youmighttakealookattheJSF-Springproject.
- 14.2.2.FacesContextUtils
-
AcustomVariableResolverworkswellwhenmappingyourpropertiestobeansinfaces-config.xml,butattimesyoumayneedtogrababeanexplicitly.TheFacesContextUtilsclassmakesthiseasy.It'ssimilartoWebApplicationContextUtils,exceptthatittakesaFacesContextparameterratherthanaServletContextparameter.
- ApplicationContextctx=FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
- 14.3.Struts
-
StrutsisthedefactowebframeworkforJavaapplications,mainlybecauseitwasoneofthefirsttobereleased(June2001).InventedbyCraigMcClanahan,StrutsisanopensourceprojecthostedbytheApacheSoftwareFoundation.Atthetime,itgreatlysimplifiedtheJSP/Servletprogrammingparadigmandwonovermanydeveloperswhowereusingproprietaryframeworks.Itsimplifiedtheprogrammingmodel,itwasopensource,andithadalargecommunity,whichallowedtheprojecttogrowandbecomepopularamongJavawebdevelopers.
- TointegrateyourStrutsapplicationwithSpring,youhavetwooptions:
-
ConfigureSpringtomanageyourActionsasbeans,usingtheContextLoaderPlugin,andsettheirdependenciesinaSpringcontextfile.
-
SubclassSpring'sActionSupportclassesandgrabyourSpring-managedbeansexplicitlyusingagetWebApplicationContext()method.
- 14.3.1.ContextLoaderPlugin
-
TheContextLoaderPluginisaStruts1.1+plug-inthatloadsaSpringcontextfilefortheStrutsActionServlet.ThiscontextreferstotherootWebApplicationContext(loadedbytheContextLoaderListener)asitsparent.Thedefaultnameofthecontextfileisthenameofthemappedservlet,plus-servlet.xml.IfActionServletisdefinedinweb.xmlas<servlet-name>action</servlet-name>,thedefaultis/WEB-INF/action-servlet.xml.
-
Toconfigurethisplug-in,addthefollowingXMLtotheplug-inssectionnearthebottomofyourstruts-config.xmlfile:
-
<plug-inclassName="org.springframework.web.struts.ContextLoaderPlugIn"/>
-
Thelocationofthecontextconfigurationfilescanbecustomizedusingthe"contextConfigLocation"property.
-
<plug-inclassName="org.springframework.web.struts.ContextLoaderPlugIn">
-
<set-propertyproperty="contextConfigLocation"
-
value="/WEB-INF/action-servlet.xml.xml,/WEB-INF/applicationContext.xml"/>
-
</plug-in>
-
Itispossibletousethisplugintoloadallyourcontextfiles,whichcanbeusefulwhenusingtestingtoolslikeStrutsTestCase.StrutsTestCase'sMockStrutsTestCasewon'tinitializeListenersonstartupsoputtingallyourcontextfilesinthepluginisaworkaround.Abughasbeenfiledforthisissue.
-
Afterconfiguringthisplug-ininstruts-config.xml,youcanconfigureyourActiontobemanagedbySpring.Spring1.1.3providestwowaystodothis:
-
OverrideStruts'defaultRequestProcessorwithSpring'sDelegatingRequestProcessor.
-
UsetheDelegatingActionProxyclassinthetypeattributeofyour<action-mapping>.
-
BothofthesemethodsallowyoutomanageyourActionsandtheirdependenciesintheaction-context.xmlfile.ThebridgebetweentheActioninstruts-config.xmlandaction-servlet.xmlisbuiltwiththeaction-mapping's"path"andthebean's"name".Ifyouhavethefollowinginyourstruts-config.xmlfile:
-
<actionpath="/users".../>
-
YoumustdefinethatAction'sbeanwiththe"/users"nameinaction-servlet.xml:
-
<beanname="/users".../>
- 14.3.1.1.DelegatingRequestProcessor
-
ToconfiguretheDelegatingRequestProcessorinyourstruts-config.xmlfile,overridethe"processorClass"propertyinthe<controller>element.Theselinesfollowthe<action-mapping>element.
- <controller>
-
<set-propertyproperty="processorClass"
-
value="org.springframework.web.struts.DelegatingRequestProcessor"/>
- </controller>
-
Afteraddingthissetting,yourActionwillautomaticallybelookedupinSpring'scontextfile,nomatterwhatthetype.Infact,youdon'tevenneedtospecifyatype.Bothofthefollowingsnippetswillwork:
-
<actionpath="/user"type="com.whatever.struts.UserAction"/>
-
<actionpath="/user"/>
-
Ifyou'reusingStruts'modulesfeature,yourbeannamesmustcontainthemoduleprefix.Forexample,anactiondefinedas<actionpath="/user"/>withmoduleprefix"admin"requiresabeannamewith<beanname="/admin/user"/>.
-
NOTE:Ifyou'reusingTilesinyourStrutsapplication,youmustconfigureyour<controller>withtheDelegatingTilesRequestProcessor.
- 14.3.1.2.DelegatingActionProxy
-
IfyouhaveacustomRequestProcessorandcan'tusetheDelegatingTilesRequestProcessor,youcanusetheDelegatingActionProxyasthetypeinyouraction-mapping.
-
<actionpath="/user"type="org.springframework.web.struts.DelegatingActionProxy"
-
name="userForm"scope="request"validate="false"parameter="method">
-
<forwardname="list"path="/userList.jsp"/>
-
<forwardname="edit"path="/userForm.jsp"/>
- </action>
-
Thebeandefinitioninaction-servlet.xmlremainsthesame,whetheryouuseacustomRequestProcessorortheDelegatingActionProxy.
-
IfyoudefineyourActioninacontextfile,thefullfeaturesetofSpring'sbeancontainerwillbeavailableforit:dependencyinjectionaswellastheoptiontoinstantiateanewActioninstanceforeachrequest.Toactivatethelatter,addsingleton="false"toyourAction'sbeandefinition.
-
<beanname="/user"singleton="false"autowire="byName"
-
class="org.example.web.UserAction"/>
- 14.3.2.ActionSupportClasses
-
Aspreviouslymentioned,youcanretrievetheWebApplicationContextfromtheServletContextusingtheWebApplicationContextUtilsclass.AneasierwayistoextendSpring'sActionclassesforStruts.Forexample,insteadofsubclassingStruts'Actionclass,youcansubclassSpring'sActionSupportclass.
-
TheActionSupportclassprovidesadditionalconveniencemethods,likegetWebApplicationContext().BelowisanexampleofhowyoumightusethisinanAction:
-
publicclassUserActionextendsDispatchActionSupport{
-
publicActionForwardexecute(ActionMappingmapping,
- ActionFormform,
- HttpServletRequestrequest,
- HttpServletResponseresponse)
- throwsException{
-
if(log.isDebugEnabled()){
-
log.debug("entering'delete'method...");
- }
- WebApplicationContextctx=getWebApplicationContext();
-
UserManagermgr=(UserManager)ctx.getBean("userManager");
-
-
returnmapping.findForward("success");
- }
- }
-
SpringincludessubclassesforallofthestandardStrutsActions-theSpringversionsmerelyhaveSupportappendedtothename:
- ActionSupport,
- DispatchActionSupport,
- LookupDispatchActionSupportand
- MappingDispatchActionSupport.
-
Therecommendedstrategyistousetheapproachthatbestsuitsyourproject.Subclassingmakesyourcodemorereadable,andyouknowexactlyhowyourdependenciesareresolved.However,usingtheContextLoaderPluginallowyoutoeasilyaddnewdependenciesinyourcontextXMLfile.Eitherway,Springprovidessomeniceoptionsforintegratingthetwoframeworks.
- 14.4.Tapestry
-
Tapestryisapowerful,component-orientedwebapplicationframeworkfromApache'sJakartaproject(http:
- 14.4.1.Architecture
-
AtypicallayeredJ2EEapplicationbuiltwithTapestryandSpringwillconsistofatopUIlayerbuiltwithTapestry,andanumberoflowerlayers,hostedoutofoneormoreSpringApplicationContexts.
- UserInterfaceLayer:
-
-concernedwiththeuserinterface
- -containssomeapplicationlogic
- -providedbyTapestry
-
-asidefromprovidingUIviaTapestry,codeinthislayerdoesitsworkviaobjectswhichimplementinterfacesfromtheServiceLayer.TheactualobjectswhichimplementtheseservicelayerinterfacesareobtainedfromaSpringApplicationContext.
- ServiceLayer:
-
-applicationspecific'service'code
-
-workswithdomainobjects,andusestheMapperAPItogetthosedomainobjectsintoandoutofsomesortofrepository(database)
-
-hostedinoneormoreSpringcontexts
-
-codeinthislayermanipulatesobjectsinthedomainmodel,inanapplicationspecificfashion.Itdoesitsworkviaothercodeinthislayer,andviatheMapperAPI.Anobjectinthislayerisgiventhespecificmapperimplementationsitneedstoworkwith,viatheSpringcontext.
-
-sincecodeinthislayerishostedintheSpringcontext,itmaybetransactionallywrappedbytheSpringcontext,asopposedtomanagingitsowntransactions
- DomainModel:
-
-domainspecificobjecthierarchy,whichdealswithdataandlogicspecifictothisdomain
-
-althoughthedomainobjecthierarchyisbuiltwiththeideathatitispersistedsomehowandmakessomegeneralconcessionstothis(forexample,bidirectionalrelationships),itgenerallyhasnoknowledgeofotherlayers.Assuch,itmaybetestedinisolation,andusedwithdifferentmappingimplementationsforproductionvs.testing.
-
-theseobjectsmaybestandalone,orusedinconjunctionwithaSpringapplicationcontexttotakeadvantageofsomeofthebenefitsofthecontext,e.g.,isolation,inversionofcontrol,differentstrategyimplementations,etc.
- DataSourceLayer:
- -MapperAPI(alsocalledDataAccessObjects):anAPIusedtopersistthedomainmodeltoarepositoryofsomesort(generallyaDB,butcouldbethefilesystem,memory,etc.)
-
-MapperAPIimplementations:oneormorespecificimplementationsoftheMapperAPI,forexample,aHibernate-specificmapper,aJDO-specificmapper,JDBC-specificmapper,oramemorymapper.
-
-mapperimplementationsliveinoneormoreSpringApplicationContexts.Aservicelayerobjectisgiventhemapperobjectsitneedstoworkwithviathecontext.
- Database,filesystem,orotherrepositories:
-
-objectsinthedomainmodelarestoredintooneormorerepositoriesviaoneormoremapperimplementations
-
-arepositorymaybeverysimple(e.g.filesystem),ormayhaveitsownrepresentationofthedatafromthedomainmodel(i.e.aschemainadb).Itdoesnotknowaboutotherlayershowerver.
- 14.4.2.Implementation
-
Theonlyrealquestion(whichneedstobeaddressedbythisdocument),ishowTapestrypagesgetaccesstoserviceimplementations,whicharesimplybeansdefinedinaninstanceoftheSpringApplicationContext.
- 14.4.2.1.Sampleapplicationcontext
-
AssumewehavethefollowingsimpleApplicationContextdefinition,inxmlform:
-
<?xmlversion="1.0"encoding="UTF-8"?>
-
<!DOCTYPEbeansPUBLIC"-//SPRING//DTDBEAN//EN"
-
"http://www.springframework.org/dtd/spring-beans.dtd">
- <beans>
- <!--=========================GENERALDEFINITIONS=========================-->
- <!--=========================PERSISTENCEDEFINITIONS=========================-->
- <!--theDataSource-->
-
<beanid="dataSource"class="org.springframework.jndi.JndiObjectFactoryBean">
-
<propertyname="jndiName"><value>java:DefaultDS</value></property>
-
<propertyname="resourceRef"><value>false</value></property>
- </bean>
- <!--defineaHibernateSessionfactoryviaaSpringLocalSessionFactoryBean-->
-
<beanid="hibSessionFactory"
-
class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
-
<propertyname="dataSource"><refbean="dataSource"/></property>
- </bean>
- <!--
-
-Definesatransactionmanagerforusageinbusinessordataaccessobjects.
-
-Nospecialtreatmentbythecontext,justabeaninstanceavailableasreference
-
-forbusinessobjectsthatwanttohandletransactions,e.g.viaTransactionTemplate.
- -->
-
<beanid="transactionManager"
-
class="org.springframework.transaction.jta.JtaTransactionManager">
- </bean>
-
<beanid="mapper"
-
class="com.whatever.dataaccess.mapper.hibernate.MapperImpl">
-
<propertyname="sessionFactory"><refbean="hibSessionFactory"/></property>
- </bean>
- <!--=========================BUSINESSDEFINITIONS=========================-->
- <!--AuthenticationService,includingtxinterceptor-->
-
<beanid="authenticationServiceTarget"
-
class="com.whatever.services.service.user.AuthenticationServiceImpl">
-
<propertyname="mapper"><refbean="mapper"/></property>
- </bean>
-
<beanid="authenticationService"
-
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
-
<propertyname="transactionManager"><refbean="transactionManager"/></property>
-
<propertyname="target"><refbean="authenticationServiceTarget"/></property>
-
<propertyname="proxyInterfacesOnly"><value>true</value></property>
-
<propertyname="transactionAttributes">
- <props>
-
<propkey="*">PROPAGATION_REQUIRED</prop>
- </props>
- </property>
- </bean>
- <!--UserService,includingtxinterceptor-->
-
<beanid="userServiceTarget"
-
class="com.whatever.services.service.user.UserServiceImpl">
-
<propertyname="mapper"><refbean="mapper"/></property>
- </bean>
-
<beanid="userService"
-
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
-
<propertyname="transactionManager"><refbean="transactionManager"/></property>
-
<propertyname="target"><refbean="userServiceTarget"/></property>
-
<propertyname="proxyInterfacesOnly"><value>true</value></property>
-
<propertyname="transactionAttributes">
- <props>
-
<propkey="*">PROPAGATION_REQUIRED</prop>
- </props>
- </property>
- </bean>
- </beans>
-
InsidetheTapestryapplication,weneedtoloadthisapplicationcontext,andallowTapestrypagestogettheauthenticationServiceanduserServicebeans,whichimplementtheAuthenticationServiceandUserServiceinterfaces,respectively.
-
14.4.2.2.ObtainingbeansinTapestrypages
-
Atthispoint,theapplicationcontextisavailabletoawebapplicationbycallingSpring'sstaticutilityfunctionWebApplicationContextUtils.getApplicationContext(servletContext),whereservletContextisthestandardServletContextfromtheJ2EEServletspecification.Assuch,onesimplemechanismforapagetogetaninstanceoftheUserService,forexample,wouldbewithcodesuchas:
- WebApplicationContextappContext=WebApplicationContextUtils.getApplicationContext(
- getRequestCycle().getRequestContext().getServlet().getServletContext());
-
UserServiceuserService=(UserService)appContext.getBean("userService");
- ...somecodewhichusesUserService
-
Thismechanismdoeswork.Itcanbemadealotlessverbosebyencapsulatingmostofthefunctionalityinamethodinthebaseclassforthepageorcomponent.However,insomerespectsitgoesagainsttheInversionofControlapproachwhichSpringencourages,whichisbeingusedinotherlayersofthisapp,inthatideallyyouwouldlikethepagetonothavetoaskthecontextforaspecificbeanbyname,andinfact,thepagewouldideallynotknowaboutthecontextatall.
-
Luckily,thereisamechanismtoallowthis.WerelyuponthefactthatTapestryalreadyhasamechanismtodeclarativelyaddpropertiestoapage,anditisinfactthepreferredapproachtomanageallpropertiesonapageinthisdeclarativefashion,sothatTapestrycanproperlymanagetheirlifecycleaspartofthepageandcomponentlifecycle.
- 14.4.2.3.ExposingtheapplicationcontexttoTapestry
-
FirstweneedtomaketheApplicationContextavailabletotheTapestrypageorComponentwithouthavingtohavetheServletContext;thisisbecauseatthestageinthepage's/component'slifecyclewhenweneedtoaccesstheApplicationContext,theServletContextwon'tbeeasilyavailabletothepage,sowecan'tuseWebApplicationContextUtils.getApplicationContext(servletContext)directly.OnewayisbydefiningacustomversionoftheTapestryIEnginewhichexposesthisforus:
- packagecom.whatever.web.xportal;
- ...
- import...
- ...
-
publicclassMyEngineextendsorg.apache.tapestry.engine.BaseEngine{
-
publicstaticfinalStringAPPLICATION_CONTEXT_KEY="appContext";
-
-
-
protectedvoidsetupForRequest(RequestContextcontext){
- super.setupForRequest(context);
-
- Mapglobal=(Map)getGlobal();
-
ApplicationContextac=(ApplicationContext)global.get(APPLICATION_CONTEXT_KEY);
-
if(ac==null){
- ac=WebApplicationContextUtils.getWebApplicationContext(
- context.getServlet().getServletContext()
- );
- global.put(APPLICATION_CONTEXT_KEY,ac);
- }
- }
- }
-
ThisengineclassplacestheSpringApplicationContextasanattributecalled"appContext"inthisTapestryapp's'Global'object.MakesuretoregisterthefactthatthisspecialIEngineinstanceshouldbeusedforthisTapestryapplication,withanentryintheTapestryapplicationdefinitionfile.Forexample:
- file:xportal.application:
-
<?xmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEapplicationPUBLIC
-
"-//ApacheSoftwareFoundation//TapestrySpecification3.0//EN"
-
"http://jakarta.apache.org/tapestry/dtd/Tapestry_3_0.dtd">
- <application
-
name="WhateverxPortal"
-
engine-class="com.whatever.web.xportal.MyEngine">
- </application>
- 14.4.2.4.Componentdefinitionfiles
-
Nowinourpageorcomponentdefinitionfile(*.pageor*.jwc),wesimplyaddproperty-specificationelementstograbthebeansweneedoutoftheApplicationContext,andcreatepageorcomponentpropertiesforthem.Forexample:
-
<property-specificationname="userService"
-
type="com.whatever.services.service.user.UserService">
-
global.appContext.getBean("userService")
- </property-specification>
-
<property-specificationname="authenticationService"
-
type="com.whatever.services.service.user.AuthenticationService">
-
global.appContext.getBean("authenticationService")
- </property-specification>
-
TheOGNLexpressioninsidetheproperty-specificationspecifiestheinitialvaluefortheproperty,asabeanobtainedfromthecontext.Theentirepagedefinitionmightlooklikethis:
-
<?xmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEpage-specificationPUBLIC
-
"-//ApacheSoftwareFoundation//TapestrySpecification3.0//EN"
-
"http://jakarta.apache.org/tapestry/dtd/Tapestry_3_0.dtd">
-
<page-specificationclass="com.whatever.web.xportal.pages.Login">
-
<property-specificationname="username"type="java.lang.String"/>
-
<property-specificationname="password"type="java.lang.String"/>
-
<property-specificationname="error"type="java.lang.String"/>
-
<property-specificationname="callback"type="org.apache.tapestry.callback.ICallback"persistent="yes"/>
-
<property-specificationname="userService"
-
type="com.whatever.services.service.user.UserService">
-
global.appContext.getBean("userService")
- </property-specification>
-
<property-specificationname="authenticationService"
-
type="com.whatever.services.service.user.AuthenticationService">
-
global.appContext.getBean("authenticationService")
- </property-specification>
-
<beanname="delegate"class="com.whatever.web.xportal.PortalValidationDelegate"/>
-
<beanname="validator"class="org.apache.tapestry.valid.StringValidator"lifecycle="page">
-
<set-propertyname="required"expression="true"/>
-
<set-propertyname="clientScriptingEnabled"expression="true"/>
- </bean>
-
<componentid="inputUsername"type="ValidField">
-
<static-bindingname="displayName"value="Username"/>
-
<bindingname="value"expression="username"/>
-
<bindingname="validator"expression="beans.validator"/>
- </component>
-
<componentid="inputPassword"type="ValidField">
-
<bindingname="value"expression="password"/>
-
<bindingname="validator"expression="beans.validator"/>
-
<static-bindingname="displayName"value="Password"/>
-
<bindingname="hidden"expression="true"/>
- </component>
- </page-specification>
-
14.4.2.5.Addingabstractaccessors
-
NowintheJavaclassdefinitionforthepageorcomponentitself,allweneedtodoisaddanabstractgettermethodforthepropertieswehavedefined,toaccessthem.WhenthepageorcomponentisactuallyloadedbyTapestry,itperformsruntimecodeinstrumentationontheclassfiletoaddthepropertieswhichhavebeendefined,andhookuptheabstractgettermethodstothenewlycreatedfields.Forexample:
-
-
publicabstractUserServicegetUserService();
-
-
publicabstractAuthenticationServicegetAuthenticationService();
-
Forcompleteness,theentireJavaclass,foraloginpageinthisexample,mightlooklikethis:
- packagecom.whatever.web.xportal.pages;
-
-
-
publicabstractclassLoginextendsBasePageimplementsErrorProperty,PageRenderListener{
-
-
publicstaticfinalStringUSER_KEY="user";
-
-
-
privatestaticfinalStringCOOKIE_NAME=Login.class.getName()+".username";
-
privatefinalstaticintONE_WEEK=7*24*60*60;
-
-
publicabstractStringgetUsername();
-
publicabstractvoidsetUsername(Stringusername);
-
publicabstractStringgetPassword();
-
publicabstractvoidsetPassword(Stringpassword);
-
publicabstractICallbackgetCallback();
-
publicabstractvoidsetCallback(ICallbackvalue);
-
publicabstractUserServicegetUserService();
-
publicabstractAuthenticationServicegetAuthenticationService();
-
-
protectedIValidationDelegategetValidationDelegate(){
-
return(IValidationDelegate)getBeans().getBean("delegate");
- }
-
protectedvoidsetErrorField(StringcomponentId,Stringmessage){
- IFormComponentfield=(IFormComponent)getComponent(componentId);
-
IValidationDelegatedelegate=getValidationDelegate();
-
delegate.setFormComponent(field);
-
delegate.record(newValidatorException(message));
- }
-
-
-
publicvoidattemptLogin(IRequestCyclecycle){
- Stringpassword=getPassword();
-
-
setPassword(null);
-
IValidationDelegatedelegate=getValidationDelegate();
-
delegate.setFormComponent((IFormComponent)getComponent("inputPassword"));
-
delegate.recordFieldInputValue(null);
-
-
if(delegate.getHasErrors())
-
return;
-
try{
- Useruser=getAuthenticationService().login(getUsername(),getPassword());
- loginUser(user,cycle);
- }
-
catch(FailedLoginExceptionex){
-
this.setError("Loginfailed:"+ex.getMessage());
-
return;
- }
- }
-
-
-
publicvoidloginUser(Useruser,IRequestCyclecycle){
- Stringusername=user.getUsername();
-
-
- Mapvisit=(Map)getVisit();
- visit.put(USER_KEY,user);
-
-
- ICallbackcallback=getCallback();
-
if(callback==null)
-
cycle.activate("Home");
-
else
- callback.performCallback(cycle);
-
-
- IEngineengine=getEngine();
-
Cookiecookie=newCookie(COOKIE_NAME,username);
- cookie.setPath(engine.getServletPath());
- cookie.setMaxAge(ONE_WEEK);
-
- cycle.getRequestContext().addCookie(cookie);
- engine.forgetPage(getPageName());
- }
-
publicvoidpageBeginRender(PageEventevent){
-
if(getUsername()==null)
- setUsername(getRequestCycle().getRequestContext().getCookieValue(COOKIE_NAME));
- }
- }
- 14.4.3.Summary
-
Inthisexample,we'vemanagedtoallowservicebeansdefinedintheSpringApplicationContexttobeprovidedtothepageinadeclarativefashion.Thepageclassdoesnotknowwheretheserviceimplementationsarecomingfrom,andinfactitiseasytoslipinanotherimplementation,forexample,duringtesting.ThisinversionofcontrolisoneoftheprimegoalsandbenefitsoftheSpringFramework,andwehavemanagedtoextenditallthewayuptheJ2EEstackinthisTapestryapplication.
- 14.5.WebWork
-
WebWorkisawebframeworkdesignedwithsimplicityinmind.It'sbuiltontopofXWork,whichisagenericcommandframework.XWorkalsohasanIoCcontainer,butitisn'tasfull-featuredasSpringandwon'tbecoveredinthissection.WebWorkcontrollersarecalledActions,mainlybecausetheymustimplementtheActioninterface.TheActionSupportclassimplementsthisinterface,anditismostcommonparentclassforWebWorkactions.
-
WebWorkmaintainsitsownSpringintegrationproject,locatedonjava.netinthexwork-optionalproject.Currently,threeoptionsareavailableforintegratingWebWorkwithSpring:
-
SpringObjectFactory:overrideXWork'sdefaultObjectFactorysoXWorkwilllookforSpringbeansintherootWebApplicationContext.
-
ActionAutowiringInterceptor:useaninterceptortoautomaticallywireanAction'sdependenciesasthey'recreated.
-
SpringExternalReferenceResolver:lookupSpringbeansbasedonthenamedefinedinan<external-ref>elementofan<action>element.
-
AllofthesestrategiesareexplainedinfurtherdetailinWebWork'sDocumentation.
- --------------------------------------------------------------------------------
- Prev
分享到:
Global site tag (gtag.js) - Google Analytics
相关推荐
Spring框架是Java开发中广泛应用的一个轻量级容器,它提供了丰富的功能,允许开发者构建模块化、松耦合的系统。本篇文章将详细讲解Spring如何与其他知名框架进行整合,以实现更高效的应用开发。 1. Spring与...
整理网上大牛的资料 spring集成mybatis logback redis quartz 常用框架
**Spring框架**: Spring是一个全面的后端应用程序框架,提供了依赖注入(DI)和面向切面编程(AOP)等功能。在SSH集成中,Spring作为核心容器,管理着应用的bean,包括Struts的Action类和Hibernate的SessionFactory...
Spring+SpringMVC+Hibernate 框架集成详解 本文档旨在详细介绍 Spring、SpringMVC 和 Hibernate 框架的集成,旨在帮助开发人员快速了解这三个框架的集成过程。 Spring 框架 Spring 框架是一个 Java 语言的开源...
本示例将聚焦于Spring Boot如何与其他框架进行集成,帮助开发者快速构建功能丰富的应用程序。 首先,Spring Boot对Web开发的支持是其核心特性之一。"H5DSWEB"可能指的是一个基于H5技术的Web项目,这通常涉及到前端...
整合 Spring 与其他 ORM 框架,需要理解 Spring 的核心概念,如 Bean 容器、依赖注入以及 AOP 等,同时也需熟悉 ORM 框架自身的特性和使用方式。正确配置相关 jar 包,如 `spring-orm-3.2.0.RELEASE.jar`,是确保...
在整合过程中,确保正确引入并配置这些jar包,遵循Spring的约定,如使用XML配置文件或Java配置类,可以有效地将Spring与其他框架集成,提高开发效率。同时,注意版本兼容性,避免因版本不匹配导致的问题。使用Maven...
它是Spring与其他框架集成的桥梁。 4. **spring-aop.jar**:该库实现了面向切面编程,提供了一种声明式处理横切关注点的方式,如日志、事务管理等。 5. **spring-expression.jar**:Spring表达式语言(Spring ...
总之,Spring框架集成Socket服务涉及创建Socket服务器Bean,实现监听器接口,并在应用启动时自动启动Socket服务。这使得Socket服务能无缝融入Spring应用的生命周期,提供高效、实时的通信能力。在实际开发中,还要...
该项目为基于SpringBoot框架集成的SpringSecurity安全框架设计,源码解析详尽。项目包含58个文件,其中Java源文件47个,XML配置文件5个,其他文件类型包括Git忽略文件、LICENSE、Maven构建文件、YAML配置文件、HTML...
本培训PPT详细讲解了Spring框架的原理、配置方法以及如何与其他框架集成,旨在帮助开发者更好地理解和应用Spring。 1. Spring框架基础: Spring是一个开源的轻量级框架,它简化了企业级Java应用程序的开发。其核心...
Spring框架则是一个全面的后端解决方案,提供了依赖注入、事务管理、AOP(面向切面编程)等功能,还能整合其他框架;Hibernate则是一个强大的对象关系映射(ORM)工具,简化了数据库操作。 Struts2的集成主要涉及到...
手把手教你集成spring cloud + shiro微服务...用最少的工作量,改造基于shiro安全框架的微服务项目,实现spring cloud + shiro 框架集成。博客地址:https://blog.csdn.net/weixin_42686388/article/details/103084289
它也是Spring与其他框架集成的入口,如Spring MVC、Quartz调度器等。 4. **Spring AOP**: `spring-aop.jar`实现了面向切面编程,允许开发者定义切面、通知和切入点,实现代码的解耦和模块化。它与AspectJ库结合,...
Spring框架是一个全面的Java企业级应用开发解决方案,涵盖了依赖注入(DI)、面向切面编程(AOP)、数据访问、事务管理、远程服务等多种功能。在本文中,我们关注的是Spring的核心模块,即Spring Framework,它提供...
Spring Boot是Spring框架的简化版本,它旨在简化初始设置并提供开箱即用的功能,而MyBatis则是一个轻量级的持久层框架,它将SQL操作与Java代码紧密集成,提供了灵活的数据访问。 首先,我们来看标题"spring-boot +...
ssm框架整合,实现spring mvc,spring,mybaits框架的集成,
而Spring框架则提供了全面的依赖注入(DI)和面向切面编程(AOP)功能,以及对其他框架的集成。 在"Struts2+Hibernate+Spring三大框架集成范例"中,我们可以看到一个综合性的示例项目,这个项目包含了基本的登录、...
接下来,Spring框架扮演了胶水的角色,将整个应用粘合在一起。Spring的依赖注入(DI)使得对象之间的依赖关系得以解耦,提高了代码的可测试性和可维护性。此外,Spring的AOP允许开发者在不修改源代码的情况下,插入...