SSH的web技术介绍
SSH的web技术介绍
I..引言
随着Java技术的逐渐成熟与完善,作为建立企业级应用的标准平台,JIIEE平台得到了长足的发展.借助于JIIEE规范中包含的多项技术:EnterpriseJavaBean(EJB).JavaServlets(Servlet).JavaServerPages(JSP).JavaMessageService(JMS)等,开发出了许多应用系统.但是,在传统JIIEE应用的开发过程中也出现了I.些问题:
I.)数据模型和逻辑模型之间的矛盾.目前使用的数据库基本上都是关系型数据库,而Java本质上是I.种面向对象的语言,对象在存储和读取时使用SQL和JDBC进行数据库操作,降低了编程的效率以及系统的可维护性.
II)传统的JIIEE应用多采用EJB的重量级框架,这种框架适合于开发大型企业应用,但是使用EJB容器进行开发和调试需要耗费大量时间.为了降低代码的耦合性,提高系统的开发效率,本文提出了I.种Struts框架.Spring框架和Hibernate框架的JIIEE应用开发策略.
II.用Struts实现MVC架构
MVC(Model-View-Controller)由TrygveReenskaug提出,首先被应用在SmallTalk-VIII0环境中,是许多交互和界面系统的构成基础.根据界面设计可变性的需求,MVC把交互系统的组成分解成模型.视图.控制器III部分.模型(Model)是软件所处理问题逻辑在独立于外在显示内容和形式情况下的内在抽象,封装了问题的核心数据.逻辑和功能的计算关系,独立于具体的界面表达和I/O操作.视图(View)把表示模型数据及逻辑关系和状态的信息及特定形式展示给用户.它从模型获得显示信息,对于相同的信息可以有多个不同的显示形式或视图.控制器(Controller)是处理 *好棒文|www.hbsrm.com +Q: ^3^5`1^9`1^6^0`7^2#
用户与软件的交互操作的,其职责是控制提供模型中任何变化的传播,确保用户界面于模型间的对应联系;它接受用户的输入,将输入反馈给模型,进而实现对模型的计算控制,是使模型和视图协调工作的部件.通常I.个视图对应I.个控制器.模型.视图与控制器的分离,使得I.个模型可以具有多个显示视图.如果用户通过某个视图的控制器改变了模型的数据,所有其它依赖于这些数据的视图都应反映到这些变化.因此,无论何时发生了何种数据变化,控制器都会将变化通知所有的视图,导致显示的更新.这实际上是I.种模型的变化-传播机制.
Struts框架最早是作为ApacheJakarta项目的组成部分问世运做,它继承了MVC的各项特性,并根据JIIEE的特点,做了相应的变化与扩展.Struts框架很好的结合了Jsp,JavaServlet,JavaBean,Taglib等技术.在Struts中,承担MVC中控制器角色的是ActionServlet.ActionServlet是I.个通用的控制组件.这个控制组件提供了处理所有发送到Struts的HTTP请求的入口点.它截取和分发这些请求到相应的动作类(这些动作类都是Action类的子类).另外控制组件也负责用相应的请求参数填充ActionForm(FromBean),并传给动作类(ActionBean).动作类访问核心商业逻辑,即访问JavaBean或调用EJB.最后动作类把控制权传给后续的JSP文件,由JSP文件生成视图.所有这些控制逻辑利用Struts-config.xml文件来配置.在Struts框架中,视图主要由JSP生成页面完成,Struts提供丰富的JSP标签库,这有利于分开表现逻辑和程序逻辑.模型以I.个或多个JavaBean的形式存在.在Struts中,主要存在III种Bean,分别是:Action,ActionForm,EJB或者JavaBean.Struts框架没有具体定义模型层的实现,在实际开发中,模型层通常是和业务逻辑紧密相连的,并且要对底层数据进行操作.下面介绍I.种开发策略,将Hibernate引入到Struts框架的模型层中,使用它来进行数据封装和映射,提供持久化的支持.
III.Spring应用构架
Spring明显区别于其他轻量级applicationframework,它将专注于web的支持,与struts和webwork有着明显的区别.在和struts和webwork的对比上,Spring是I.个服务于所有层面的applicationframework:提供了bean的配置基础,AOP的支持,JDBC的提取框架,抽象事务支持,等等.它有I.个非常显著的特点:在某个层面上如果你不需要Spring的支持,你就可以不使用String的class,只使用它的某I.部分的功能.从它的设计理念,你可以看到String帮助你实现了真正的逻辑层和web层的分离:例如.I.个校验应用将不用依靠controllers,就可以实现.这样的目标是更好的重用和易测:过分依靠不必要的容器和框架将不能实现这I.点.
当然,Spring的自己的web支持和通常框架模式的细致完整.然而,Spring替换struts,webwork或者其他的web方案非常的容易.对于Spring的web支持或者不同的地方,Spring允许你在web容器里面建立I.个中间层,在测试环境或者标准独立的应用里面来设置重用你的商务 *好棒文|www.hbsrm.com +Q: ^3^5`1^9`1^6^0`7^2#
逻辑.还有在JIIEE环境里面,你的商务逻辑不必依靠容器提供的服务,像JTA,EJB的支持.良好的构架的web应用可以运行在任何容器上,如,Tomcat或者Resin.值得注意的是,Spring不是和已经存在的解决方案进行竞争.我们鼓励结合标准的技术,如,Servlet,JSP,JTA,JNDI,JDBC,andJDO,和非常匹配的工具,如,Hibernate,Velocity,LogIVJ,andCauchosHessian/Burlap.这个框架的设计思想是在你的应用需要改良的时候,你将会做I.些技术的选择:例如,如果你需要分布式事务处理,你可能需要用Spring的JtaTransactionManager来实现JTA服务.或者,用DataSourceTransactionManager或者HibernateTransactionManager来实现美妙完美的单个数据库交换.
IV.Springweb框架的设计思想
Spring框架通过配置操作mappings,展示resolution,本地化和模版集成围绕着分派请求操作的servlet-DispatcherServlet设计的.缺省的操作是I.个非常简单的控制接口,他只提供了ModelAndViewhandleRequest(request,response)方法.这将用于I.个应用的控制,但是,如果你想包含多个层次的控制,AbstractController,AbstractCommandController,MultiActionController,SimpleFormController,AbstractWizardFormController将帮助你完成.应用控制将代表那些子系统.注意,你可以选择I.个适当的基类:如果你没有webform,你就不必用FormController.这就是和Struts最大的不同.你可以通过命令或者form对象来操作任何对象:这不需要接口工具或者I.个基础类的驱动.Spring的数据邦定是非常的灵活的.举例来说,它描述了具有在应用范围内的校验错误的输入机制,但不是系统错误.所以在你的form对象里面你不必复制你的业务对象的string属性,只操作出错的子任务,或者适当地转换string.换句话说,它通常可以很好的直接绑定你的业务对象.这也是和struts围绕请求基础类Action和ActionForm(每个action操作类型)建立主要的不同之I..对比WebWork,Sping更多的区别在于对象角色:Sping支持控制器的感念,I.个操作命令或者form对象,和得到数据传递给视图的模式.这个模式通常包含命令和form对象,但有时也包含任意的参考数据.换句话说,I.个WebWorkAction联合所有这些角色到I.个单独的对象.WebWork允许你用已经存在的业务对象作为你form的I.部分,但是只生成各自Action的bean属性.最后,操作请求的Action实例在I.个视图里面获得付值和formpopulation.然而,参考数据也需要作为Action的属性被模拟.I.个类里面有太多的角色是值得讨论的.关于视图:Spring的视图方案非常的灵活.I.个控制器执行可以通过response返回ModelAndView对象null,就可以直接写到I.个视图.在通常的状况下,I.个ModelAndView实例结合了I.个view和I.个modelMap,包含了beanname和通讯对象(像命令或者form,参考数据等等).View名称是非常高端的的配置,不是通过beanname,I.个properties文件就是通过你自己的ViewResolver.这个抽象的modelMap允许你在视图层面完成提取,没有任何的争辩JSP/Velocity或者其他,每I.种都可以直接完整使用.这个modelMap还可以简单得得到适当的格式化数据的转换,像JSP请求属性或者Velocity模版模式.
V.Hibernate应用框架
数据持久层及HibernateHibernate是I.个数据持久层框架,是I.种实现对象和关系之间映射(O/RMapping)的工具,它对JDBC进行了轻量级的对象封装,使程序员可以使用对象编程思想来操作数据库.它不仅提供了从Java类到数据表的映射,也提供了数据查询和恢复机制.相对于使用JDBC和SQL来操作数据库,使用Hibernate能大大的提高实现的效率.Hibernate框架用配置文件的形式来定义Java对象和数据表之间的映射关系,同时在更深的层面将数据表之间的关系解释为Java对象之间的继承及包含等关系.通过使用HQL语句将复杂的关系算法用对象的方式描述,在很大程度上简化了对数据的查询,加快了开发的效率.在Hibernate中有I.个简单而直观的API,用于对数据库所表示的对象执行查询.要创建或修改这些对象,只需在程序中与它们进行交互,然后告诉Hibernate保存即可.这样,大量封装持久化操作的业务逻辑不再需要编写烦琐的JDBC语句,从而使数据持久层得到了极大的简化.
VI.运用Hibernate和Struts开发JIIEE应用
以在JIIEE应用中非常普遍的用户登录过程为例,来说明上述体系结构是如何具体运用的.登录的流程非常清晰:用户从登录页面login.jsp输入登录信息,系统对登录信息进行验证,如果正确则成功登录,否则提示相应错误信息.在开发过程中,使用Eclipse作为开发环境,同时加载了对Struts及Hibernate提供更好的控制和支持的第III方插件MyEclipse,Web服务器使用Tomcat,数据库选用了Mysql.首先对Hibernate进行配置,只需要对系统自动生成的hibernate.cfg.xml进行修改,配置好数据库连接的各种参数以及定义数据映射文件.由于Hibernate所带的连接池主要用于测试,性能不是很好,可以通过JNDI将其修改为使用Tomcat的连接池.
VII.小结
在本文中,我们介绍了Struts应用框架,并介绍了I.些基本知识,关于Spring,以及Hibernate.我们也说明了如何运用Hibernate和Struts开发JIIEE,以及它如何用来将servlets和JSP在结合在同I.个应用之中.现在你已经有关于StrtusWeb应用程序模样的初步印象,以后我们将更深入的讨论Strtuts框架的理论和具体实践.
SSHbasedonWebTechnology
I..Introduction
OneprefacealongwiththeJavatechniqueofgradualmatureandperfect,Beestablishmentbusinessenterpriseclassapplicationofstandardterrace,theJIIEEterracegotsubstantialofdevelopment.SeveraltechniqueaskedforhelpfromtoincludeintheJIIEEnorm:EnterpriseJavaBean(EJB),JavaServlets(Servlet),JavaServerPages(JSP),JavaMessageService(JMS)...etc.,developmentmanyapplicationsystem.But,alsoappearedsomeprobleminthetraditionJIItheEEtheapplicationofthedevelopmenttheprocess:
I.)theantinomyofdatamodelandlogicmodel.Currentlythedatabaseofusagebasicallyandallisrelationtypedatabase,buttheJavabeessentiallyakindofthelanguagewhichfacetoobject,objectatsavingwithreadusageSQLandJDBCcarryonadatabaseoperationandloweredplaitdistanceofefficiencyandsystemofcanmaintenance;
II)traditionofJIIEEapplicationmuchtheadoptionisaccordingtotheEJBheavyweightframe,thiskindofframesuitablefordevelopalargebusinessenterpriseapplication,butusagetheEJBcontainercarryondevelopmentandadjusttotrytoneedtobewasteagreatdealoftime.ForloweringtheOutofcodetomatchsex,exaltationsystemofdevelopmentefficiency,thistextputforwardI.kindEEaccordingtotheJIIoftheStrutsframeandSpringframeandtheHibernateframeapplicationdevelopmentstrategy.
II.UsetheStrutsrealizationMVCstructure
usetheStrutsrealizationMVCstructureMVC(Model-View-Controller)isputforwardbytheTrygveReenskaug,firstdriveapplicationintheenvironmentSmallTalk-VIII0,ismanytohandoverwitheachotherwithinterfacesystemofconstitutefoundation.Accordingtotheneedofvariableoftheinterfacedesign,MVChandoverwitheachotherconstituteofsystemtoresolveintomodelandseediagram,controllerthreepart.Model(Model)issoftwareprocessingproblemlogicatindependenceinoutsidemanifestationundercontentsandformcircumstanceofinsideabstract,packedthecoredata,logicofproblemandfunctionofcalculationrelation,independenceinconcreteofinterfaceexpressionandI/Ooperation.Seediagram(View)meaninformationandparticularformdemonstrationofmodeldataandlogicrelationandappearancetothecustomer.Itacquireamanifestationinformationfromthemodel,therecanbemanyforhomologyofinformationdissimilarityofmanifestationformorseediagram.Thecontroller(Controller)isaprocessingthecustomerhandoverwithsoftwarewitheachotheroperationof,itsjobiscontrolprovidemodelinanyvarietyofdissemination,insureacustomerinterfaceamongthemodelofrightnessshouldcontact;Itacceptacustomerofimportation,give°theimportationfeedbackmodel,thenrealizationcomputemodelcontrol,ismakemodelandseediagramtomoderateworkofparts.UsuallyI.seeadiagramrightnessshouldacontroller.Model,seeseparateofdiagramandcontroller,makeamodelbeabletohavemanymanifestationtoseediagram.Ifthecustomerpassacertainseethecontrollerofdiagramchangethedataofmodel,allotherdependenceintheseseeofdatadiagramallshouldreflectionarrivethesevariety.Whenthereforeandregardlessoccurrencewhatdatavariety,controllerallwouldvarietynoticeallyseediagram,causemanifestationofrenewal.Thisisactuallyakindofvarietyofmodel-disseminationmechanism.
TheStrutsframeistobetheitemofApacheJakartatoconstituteparttopublishlucktodoattheearlieststage,itinheritedMVCofeachitemcharacteristic,anddidaccordingtothecharacteristicsofJIIEEcorrespondofvarietywithexpand.TheStrutsframewasgoodtocombineJsp,JavaServlet,JavaBean,Taliaetc.technique.IntheStruts,whattoundertakethecontrollerroleintheMVCbeanActionServlet.TheActionServletisaningeneralusecontrolmodule.ThiscontrolmoduleprovidedaprocessingallHTTPclaimwhichsendoutStrutsofentrancepoint.Itsinterceptionwithdistributetheseclaimtoarrivecorrespondofactiontype.(theseactionalloftypeisActionsontype)MoreoverthecontrolmoduleisalsoresponsibleforusingtocorrespondofclaimtheparameterfillActionForm(FromBean),andpassactiontype(ActionBean).Actiontypethebusinesslogicoftheinterviewcore,theninterviewJavaBeanoradjusttouseEJB.Endactiontypecontrolthepowerpassfollow-upofJSPdocument,fromJSPdocumentbornseediagram.AllthesecontrollogicmakeuseofStruts-config.xmlthedocumentcometoallocation.SeediagramintheStrutsframemainfromJSPbornpagecompletion,theStrutsprovideabundantofJSPlabeldatabase,thisisadvantageoustoseparatingperformancelogicandprocedurelogic.ThemodeliswithI.ortheformexistenceofseveralJavaBean.IntheStruts,mainexistencethreekindsofBean,respectivelyBE:Action,ActionForm,EJBperhapsJavaBean.TheStrutsframehavenoconcretedefinitionmodellayerofrealization,inactuallythedevelopment,modellayerusuallyisclosewithbusinesslogicconnectwitheachother,andwanttocarryonoperationtothefirstfloordata.Theunderneathsintroductionisakindofdevelopmentstrategy,leadtheHibernateintothemodellayerofStrutsframe,usageittocarryonadatatopackwithreflecttoshoot,provideholdoutforlongtimeturnofsupport.IVusageHibernateandtheStrutsdevelopmentJIIEEapplicationIV.I.systemstructurediagramIIImanifestationaccordingtoHibernateandStrutsdevelopmentstrategyofsystemstructurediagram.
III.SpringtheApplicationFramework
Springisn’tparticularlyawebframeworkbutagenericlightweightapplicationframeworkwithdedicatedwebsupport,andshowsthearchitecturaldifferencestoStrutsandWebWork.IncontrasttoStrutsorWebWork,Springisanapplicationframeworkforalllayers:Itoffersabeanconfigurationfoundation,AOPsupport,aJDBCabstractionframework,abstracttransactionsupport,etc.Itisaverynon-intrusiveeffort:YourapplicationclassesdonotneedtodependonanySpringclassesifnotnecessary,andyoucanreuseeverypartonitsownifyouliketo.Fromitsverydesign,theframeworkencouragescleanseparationoftiers,mostimportantlywebtierandbusinesslogic:e.g.thevalidationframeworkdoesnotdependonwebcontrollers.Majorgoalsarereusabilityandtestability:Unnecessarycontainerorframeworkdependenciescanbeconsideredavoidableevils.
Ofcourse,Springsownwebsupportisnicelyintegratedwiththeframeworksgeneralpatterns.Nevertheless,replacingthewebsolutionwithStruts,WebWork,orthelikeiseasy.BothwithSpringswebsupportoradifferentone,Springallowsforbuildingatruededicatedmiddletierinthewebcontainer,withtheoptiontoreuseexactlythesamebusinesslogicintestenvironmentsorstandaloneapplications.AndwithinJIIEE,yourbusinesslogicwillnotunnecessarilydependoncontainerserviceslikeJTAorEJB-allowingcomplex,well-architectedwebapplicationstorunina"simple"containerlikeTomcatorResin.NotethatSpringdoesntgenerallyaimtocompetewithexistingsolutions.ItratherfostersseamlessintegrationwithstandardslikeServlet,JSP,JTA,JNDI,JDBC,andJDO,andwell-suitedtoolslikeHibernate,Velocity,LogIVJ,andCauchosHessian/Burlap.Theframeworkisdesignedtogrowwiththeneedsofyourapplications,intermsoftechnologychoice:Forexample,youwillprobablyuseJTAviaSpringsJtaTransactionManagerifyouneeddistributedtransactions-butonlythen,asthereareperfectreplacementsforsingledatabases,likeDataSourceTransactionManagerorHibernateTransactionManager.
IV.TheDesignofSpringsWebFramework
SpringswebframeworkisdesignedaroundaDispatcherServletthatdispatchesrequeststohandlers,withconfigurablehandlermappings,viewresolution,andlocaleandthemeresolution.ThedefaulthandlerisaverysimpleControllerinterface,justofferinga"ModelAndViewhandleRequest(request,response)"method.Thiscanalreadybeusedforapplicationcontrollers,butyouwillprefertheincludedimplementationhierarchy,consistingofAbstractController,AbstractCommandController,MultiActionController,SimpleFormController,AbstractWizardFormController.Applicationcontrollerswilltypicallybesubclassesofthose.Notethatyoucanchooseanappropriatebaseclass:Ifyoudonthaveaform,youdontneedaFormController.ThisisamajordifferencetoStruts.
Youcantakeanyobjectascommandorformobject:Theresnoneedtoimplementaninterfaceorderivefromabaseclass.Springsdatabindingishighlyflexible,e.g.ittreatstypemismatchesasvalidationerrorsthatcanbeevaluatedbytheapplication,notassystemerrors.SoyoudontneedtoduplicateyourbusinessobjectspropertiesasStringsinyourformobjects,justtobeabletohandleinvalidsubmissions,ortoconverttheStringsproperly.Instead,itsoftenpreferabletobinddirectlytoyourbusinessobjects.ThisisanothermajordifferencetoStrutswhichisbuiltaroundrequiredbaseclasseslikeActionandActionForm-foreverytypeofaction.?ComparedtoWebWork,Springhasmoredifferentiatedobjectroles:ItsupportsthenotionofaController,anoptionalcommandorformobject,andamodelthatgetspassedtotheview.Themodelwillnormallyincludethecommandorformobjectbutalsoarbitraryreferencedata.Instead,aWebWorkActioncombinesallthoserolesintoonesingleobject.WebWorkdoesallowyoutouseexistingbusinessobjectsaspartofyourform,butjustbymakingthembeanpropertiesoftherespectiveActionclass.Finally,thesameActioninstancethathandlestherequestgetsusedforevaluationandformpopulationintheview.Thus,referencedataneedstobemodelledasbeanpropertiesoftheActiontoo.Thesearearguablytoomanyrolesinoneobject.Regardingviews:Springsviewresolutionisextremelyflexible.AControllerimplementationcanevenwriteaviewdirectlytotheresponse,returningnullasModelAndView.Inthenormalcase,aModelAndViewinstanceconsistsofaviewnameandamodelMap,containingbeannamesandcorrespondingobjects(likeacommandorform,referencedata,etc).Viewnameresolutionishighlyconfigurable,eitherviabeannames,viaapropertiesfile,orviayourownViewResolverimplementation.TheabstractmodelMapallowsforcompleteabstractionoftheviewtechnology,withoutanyhassle:BeitJSP,Velocity,oranythingelse-everyrenderercanbeintegrateddirectly.ThemodelMapsimplygetstransformedintoanappropriateformat,likeJSPrequestattributesoraVelocitytemplatemodel.
V.HibernatetheApplicationFramework
DatasholdingoutforlongtimelayerandHibernateisonepieceaccordingtoholdoutforlongtimelayerframe,isakindofrealizationobjectandrelationofthetoolwhichreflecttoshoot(O/RMapping),itcarriedontheobjectofthelightweighttopacktotheJDBCandmakeproceduremembercanusageobjectplaitdistancethoughttooperationdatabase.ItnotonlyprovidedtoshootfromJavatoreflectofdataform,butalsoprovidedadataasearchandinstaurationmechanism.OppositeinusageJDBCandSQLtooperationdatabase,useHibernateabilityconsumedlyofexaltationrealizationofefficiency.TheHibernateframeuseallocationdocumentoftheformcometothereflectofthedefinitionJavaobjectanddataformtoshootrelation,inthemeantimeatmoredeepoflevelofdataformofrelationexplanationfortherelationssuchasinheritofandcontainmentetc.ofJavaobject.PasstheusageHQLlanguagesentencecomplicationsofrelationthecalculatewayusethewayofobjectdescription,toalargeextentsimplificationlogarithmsaccordingtoofsearch,speeddevelopmentofefficiency.HaveintheHibernateasimplebutkeeptheAPIofview,usedfortothedatabasemeanofobjectperformancesearch.Wanttoestablishorthemodificationbetheseobjects,needintheprocedurecarryonwiththemtohandoverwitheachother,thentellHibernatetokeep.So,agreatdealofpackholdoutforlongtimeturnoperationofbusinesslogicnolongerdemandwriteatrivialJDBClanguagesentence,makedatalastlongthusthelayergotbiggestofsimplification.
VI.UseHibernateandStrutstodevelopJIIEEapplication
Developmentpracticeunderneathcombineadevelopmentpractice,withintheJIItheEEtheapplicationverywidespreadcustomerregisterprocessforexample,elucidationabove-mentionedsystemstructureishowconcreteusage.Theprocessofregisterisveryclear:Customerfromregisterpagelogin.jspimportationregisterinformation,systemtoregistertheinformationcarryonverification,ifexactitudesuccessregister,otherwisehintcorrespondmistakeinformation.Inthedevelopmentprocess,theusageEclipsebeusedasdevelopmentenvironmentandaddedtocarrytoprovidetotheStrutsandtheHibernateinthemeantimebettercontrolandsupportofthreesquareplug-inMyEclipse,WebserverusageTomcat,thedatabasechosetouseMysql.CarryonanallocationtotheHibernatefirst,needtothesystemautothebornhibernate.cfg.xmlcarryonmodification,allocationgooddatabaseconjunctionofvariousparameteranddefinitionthedatareflecttoshootadocument.BecausetheHibernatetakeofconjunctionpondmainusedfortest,thefunctionisntverygood,canpassJNDIwillitmodificationisusageTomcatofconjunctionpond.
VII.Summary
Inthispaper,weintroducedtheStrutsapplicationframework.AndintroducessomebasicknowledgeaboutSpringandHibernate,.WealsoshowhowtouseHibernateandStrutsdevelopmentJIIEE,andhowitusedtobeservletsandJSPincombinationinthesameapplication.NowthatyouhaveatasteoftheStrtusWebapplication,afterthatwewilldigdeeperintothetheoryandpracticebehindtheStrutsarchitecture.
I..引言
随着Java技术的逐渐成熟与完善,作为建立企业级应用的标准平台,JIIEE平台得到了长足的发展.借助于JIIEE规范中包含的多项技术:EnterpriseJavaBean(EJB).JavaServlets(Servlet).JavaServerPages(JSP).JavaMessageService(JMS)等,开发出了许多应用系统.但是,在传统JIIEE应用的开发过程中也出现了I.些问题:
I.)数据模型和逻辑模型之间的矛盾.目前使用的数据库基本上都是关系型数据库,而Java本质上是I.种面向对象的语言,对象在存储和读取时使用SQL和JDBC进行数据库操作,降低了编程的效率以及系统的可维护性.
II)传统的JIIEE应用多采用EJB的重量级框架,这种框架适合于开发大型企业应用,但是使用EJB容器进行开发和调试需要耗费大量时间.为了降低代码的耦合性,提高系统的开发效率,本文提出了I.种Struts框架.Spring框架和Hibernate框架的JIIEE应用开发策略.
II.用Struts实现MVC架构
MVC(Model-View-Controller)由TrygveReenskaug提出,首先被应用在SmallTalk-VIII0环境中,是许多交互和界面系统的构成基础.根据界面设计可变性的需求,MVC把交互系统的组成分解成模型.视图.控制器III部分.模型(Model)是软件所处理问题逻辑在独立于外在显示内容和形式情况下的内在抽象,封装了问题的核心数据.逻辑和功能的计算关系,独立于具体的界面表达和I/O操作.视图(View)把表示模型数据及逻辑关系和状态的信息及特定形式展示给用户.它从模型获得显示信息,对于相同的信息可以有多个不同的显示形式或视图.控制器(Controller)是处理 *好棒文|www.hbsrm.com +Q: ^3^5`1^9`1^6^0`7^2#
用户与软件的交互操作的,其职责是控制提供模型中任何变化的传播,确保用户界面于模型间的对应联系;它接受用户的输入,将输入反馈给模型,进而实现对模型的计算控制,是使模型和视图协调工作的部件.通常I.个视图对应I.个控制器.模型.视图与控制器的分离,使得I.个模型可以具有多个显示视图.如果用户通过某个视图的控制器改变了模型的数据,所有其它依赖于这些数据的视图都应反映到这些变化.因此,无论何时发生了何种数据变化,控制器都会将变化通知所有的视图,导致显示的更新.这实际上是I.种模型的变化-传播机制.
Struts框架最早是作为ApacheJakarta项目的组成部分问世运做,它继承了MVC的各项特性,并根据JIIEE的特点,做了相应的变化与扩展.Struts框架很好的结合了Jsp,JavaServlet,JavaBean,Taglib等技术.在Struts中,承担MVC中控制器角色的是ActionServlet.ActionServlet是I.个通用的控制组件.这个控制组件提供了处理所有发送到Struts的HTTP请求的入口点.它截取和分发这些请求到相应的动作类(这些动作类都是Action类的子类).另外控制组件也负责用相应的请求参数填充ActionForm(FromBean),并传给动作类(ActionBean).动作类访问核心商业逻辑,即访问JavaBean或调用EJB.最后动作类把控制权传给后续的JSP文件,由JSP文件生成视图.所有这些控制逻辑利用Struts-config.xml文件来配置.在Struts框架中,视图主要由JSP生成页面完成,Struts提供丰富的JSP标签库,这有利于分开表现逻辑和程序逻辑.模型以I.个或多个JavaBean的形式存在.在Struts中,主要存在III种Bean,分别是:Action,ActionForm,EJB或者JavaBean.Struts框架没有具体定义模型层的实现,在实际开发中,模型层通常是和业务逻辑紧密相连的,并且要对底层数据进行操作.下面介绍I.种开发策略,将Hibernate引入到Struts框架的模型层中,使用它来进行数据封装和映射,提供持久化的支持.
III.Spring应用构架
Spring明显区别于其他轻量级applicationframework,它将专注于web的支持,与struts和webwork有着明显的区别.在和struts和webwork的对比上,Spring是I.个服务于所有层面的applicationframework:提供了bean的配置基础,AOP的支持,JDBC的提取框架,抽象事务支持,等等.它有I.个非常显著的特点:在某个层面上如果你不需要Spring的支持,你就可以不使用String的class,只使用它的某I.部分的功能.从它的设计理念,你可以看到String帮助你实现了真正的逻辑层和web层的分离:例如.I.个校验应用将不用依靠controllers,就可以实现.这样的目标是更好的重用和易测:过分依靠不必要的容器和框架将不能实现这I.点.
当然,Spring的自己的web支持和通常框架模式的细致完整.然而,Spring替换struts,webwork或者其他的web方案非常的容易.对于Spring的web支持或者不同的地方,Spring允许你在web容器里面建立I.个中间层,在测试环境或者标准独立的应用里面来设置重用你的商务 *好棒文|www.hbsrm.com +Q: ^3^5`1^9`1^6^0`7^2#
逻辑.还有在JIIEE环境里面,你的商务逻辑不必依靠容器提供的服务,像JTA,EJB的支持.良好的构架的web应用可以运行在任何容器上,如,Tomcat或者Resin.值得注意的是,Spring不是和已经存在的解决方案进行竞争.我们鼓励结合标准的技术,如,Servlet,JSP,JTA,JNDI,JDBC,andJDO,和非常匹配的工具,如,Hibernate,Velocity,LogIVJ,andCauchosHessian/Burlap.这个框架的设计思想是在你的应用需要改良的时候,你将会做I.些技术的选择:例如,如果你需要分布式事务处理,你可能需要用Spring的JtaTransactionManager来实现JTA服务.或者,用DataSourceTransactionManager或者HibernateTransactionManager来实现美妙完美的单个数据库交换.
IV.Springweb框架的设计思想
Spring框架通过配置操作mappings,展示resolution,本地化和模版集成围绕着分派请求操作的servlet-DispatcherServlet设计的.缺省的操作是I.个非常简单的控制接口,他只提供了ModelAndViewhandleRequest(request,response)方法.这将用于I.个应用的控制,但是,如果你想包含多个层次的控制,AbstractController,AbstractCommandController,MultiActionController,SimpleFormController,AbstractWizardFormController将帮助你完成.应用控制将代表那些子系统.注意,你可以选择I.个适当的基类:如果你没有webform,你就不必用FormController.这就是和Struts最大的不同.你可以通过命令或者form对象来操作任何对象:这不需要接口工具或者I.个基础类的驱动.Spring的数据邦定是非常的灵活的.举例来说,它描述了具有在应用范围内的校验错误的输入机制,但不是系统错误.所以在你的form对象里面你不必复制你的业务对象的string属性,只操作出错的子任务,或者适当地转换string.换句话说,它通常可以很好的直接绑定你的业务对象.这也是和struts围绕请求基础类Action和ActionForm(每个action操作类型)建立主要的不同之I..对比WebWork,Sping更多的区别在于对象角色:Sping支持控制器的感念,I.个操作命令或者form对象,和得到数据传递给视图的模式.这个模式通常包含命令和form对象,但有时也包含任意的参考数据.换句话说,I.个WebWorkAction联合所有这些角色到I.个单独的对象.WebWork允许你用已经存在的业务对象作为你form的I.部分,但是只生成各自Action的bean属性.最后,操作请求的Action实例在I.个视图里面获得付值和formpopulation.然而,参考数据也需要作为Action的属性被模拟.I.个类里面有太多的角色是值得讨论的.关于视图:Spring的视图方案非常的灵活.I.个控制器执行可以通过response返回ModelAndView对象null,就可以直接写到I.个视图.在通常的状况下,I.个ModelAndView实例结合了I.个view和I.个modelMap,包含了beanname和通讯对象(像命令或者form,参考数据等等).View名称是非常高端的的配置,不是通过beanname,I.个properties文件就是通过你自己的ViewResolver.这个抽象的modelMap允许你在视图层面完成提取,没有任何的争辩JSP/Velocity或者其他,每I.种都可以直接完整使用.这个modelMap还可以简单得得到适当的格式化数据的转换,像JSP请求属性或者Velocity模版模式.
V.Hibernate应用框架
数据持久层及HibernateHibernate是I.个数据持久层框架,是I.种实现对象和关系之间映射(O/RMapping)的工具,它对JDBC进行了轻量级的对象封装,使程序员可以使用对象编程思想来操作数据库.它不仅提供了从Java类到数据表的映射,也提供了数据查询和恢复机制.相对于使用JDBC和SQL来操作数据库,使用Hibernate能大大的提高实现的效率.Hibernate框架用配置文件的形式来定义Java对象和数据表之间的映射关系,同时在更深的层面将数据表之间的关系解释为Java对象之间的继承及包含等关系.通过使用HQL语句将复杂的关系算法用对象的方式描述,在很大程度上简化了对数据的查询,加快了开发的效率.在Hibernate中有I.个简单而直观的API,用于对数据库所表示的对象执行查询.要创建或修改这些对象,只需在程序中与它们进行交互,然后告诉Hibernate保存即可.这样,大量封装持久化操作的业务逻辑不再需要编写烦琐的JDBC语句,从而使数据持久层得到了极大的简化.
VI.运用Hibernate和Struts开发JIIEE应用
以在JIIEE应用中非常普遍的用户登录过程为例,来说明上述体系结构是如何具体运用的.登录的流程非常清晰:用户从登录页面login.jsp输入登录信息,系统对登录信息进行验证,如果正确则成功登录,否则提示相应错误信息.在开发过程中,使用Eclipse作为开发环境,同时加载了对Struts及Hibernate提供更好的控制和支持的第III方插件MyEclipse,Web服务器使用Tomcat,数据库选用了Mysql.首先对Hibernate进行配置,只需要对系统自动生成的hibernate.cfg.xml进行修改,配置好数据库连接的各种参数以及定义数据映射文件.由于Hibernate所带的连接池主要用于测试,性能不是很好,可以通过JNDI将其修改为使用Tomcat的连接池.
VII.小结
在本文中,我们介绍了Struts应用框架,并介绍了I.些基本知识,关于Spring,以及Hibernate.我们也说明了如何运用Hibernate和Struts开发JIIEE,以及它如何用来将servlets和JSP在结合在同I.个应用之中.现在你已经有关于StrtusWeb应用程序模样的初步印象,以后我们将更深入的讨论Strtuts框架的理论和具体实践.
SSHbasedonWebTechnology
I..Introduction
OneprefacealongwiththeJavatechniqueofgradualmatureandperfect,Beestablishmentbusinessenterpriseclassapplicationofstandardterrace,theJIIEEterracegotsubstantialofdevelopment.SeveraltechniqueaskedforhelpfromtoincludeintheJIIEEnorm:EnterpriseJavaBean(EJB),JavaServlets(Servlet),JavaServerPages(JSP),JavaMessageService(JMS)...etc.,developmentmanyapplicationsystem.But,alsoappearedsomeprobleminthetraditionJIItheEEtheapplicationofthedevelopmenttheprocess:
I.)theantinomyofdatamodelandlogicmodel.Currentlythedatabaseofusagebasicallyandallisrelationtypedatabase,buttheJavabeessentiallyakindofthelanguagewhichfacetoobject,objectatsavingwithreadusageSQLandJDBCcarryonadatabaseoperationandloweredplaitdistanceofefficiencyandsystemofcanmaintenance;
II)traditionofJIIEEapplicationmuchtheadoptionisaccordingtotheEJBheavyweightframe,thiskindofframesuitablefordevelopalargebusinessenterpriseapplication,butusagetheEJBcontainercarryondevelopmentandadjusttotrytoneedtobewasteagreatdealoftime.ForloweringtheOutofcodetomatchsex,exaltationsystemofdevelopmentefficiency,thistextputforwardI.kindEEaccordingtotheJIIoftheStrutsframeandSpringframeandtheHibernateframeapplicationdevelopmentstrategy.
II.UsetheStrutsrealizationMVCstructure
usetheStrutsrealizationMVCstructureMVC(Model-View-Controller)isputforwardbytheTrygveReenskaug,firstdriveapplicationintheenvironmentSmallTalk-VIII0,ismanytohandoverwitheachotherwithinterfacesystemofconstitutefoundation.Accordingtotheneedofvariableoftheinterfacedesign,MVChandoverwitheachotherconstituteofsystemtoresolveintomodelandseediagram,controllerthreepart.Model(Model)issoftwareprocessingproblemlogicatindependenceinoutsidemanifestationundercontentsandformcircumstanceofinsideabstract,packedthecoredata,logicofproblemandfunctionofcalculationrelation,independenceinconcreteofinterfaceexpressionandI/Ooperation.Seediagram(View)meaninformationandparticularformdemonstrationofmodeldataandlogicrelationandappearancetothecustomer.Itacquireamanifestationinformationfromthemodel,therecanbemanyforhomologyofinformationdissimilarityofmanifestationformorseediagram.Thecontroller(Controller)isaprocessingthecustomerhandoverwithsoftwarewitheachotheroperationof,itsjobiscontrolprovidemodelinanyvarietyofdissemination,insureacustomerinterfaceamongthemodelofrightnessshouldcontact;Itacceptacustomerofimportation,give°theimportationfeedbackmodel,thenrealizationcomputemodelcontrol,ismakemodelandseediagramtomoderateworkofparts.UsuallyI.seeadiagramrightnessshouldacontroller.Model,seeseparateofdiagramandcontroller,makeamodelbeabletohavemanymanifestationtoseediagram.Ifthecustomerpassacertainseethecontrollerofdiagramchangethedataofmodel,allotherdependenceintheseseeofdatadiagramallshouldreflectionarrivethesevariety.Whenthereforeandregardlessoccurrencewhatdatavariety,controllerallwouldvarietynoticeallyseediagram,causemanifestationofrenewal.Thisisactuallyakindofvarietyofmodel-disseminationmechanism.
TheStrutsframeistobetheitemofApacheJakartatoconstituteparttopublishlucktodoattheearlieststage,itinheritedMVCofeachitemcharacteristic,anddidaccordingtothecharacteristicsofJIIEEcorrespondofvarietywithexpand.TheStrutsframewasgoodtocombineJsp,JavaServlet,JavaBean,Taliaetc.technique.IntheStruts,whattoundertakethecontrollerroleintheMVCbeanActionServlet.TheActionServletisaningeneralusecontrolmodule.ThiscontrolmoduleprovidedaprocessingallHTTPclaimwhichsendoutStrutsofentrancepoint.Itsinterceptionwithdistributetheseclaimtoarrivecorrespondofactiontype.(theseactionalloftypeisActionsontype)MoreoverthecontrolmoduleisalsoresponsibleforusingtocorrespondofclaimtheparameterfillActionForm(FromBean),andpassactiontype(ActionBean).Actiontypethebusinesslogicoftheinterviewcore,theninterviewJavaBeanoradjusttouseEJB.Endactiontypecontrolthepowerpassfollow-upofJSPdocument,fromJSPdocumentbornseediagram.AllthesecontrollogicmakeuseofStruts-config.xmlthedocumentcometoallocation.SeediagramintheStrutsframemainfromJSPbornpagecompletion,theStrutsprovideabundantofJSPlabeldatabase,thisisadvantageoustoseparatingperformancelogicandprocedurelogic.ThemodeliswithI.ortheformexistenceofseveralJavaBean.IntheStruts,mainexistencethreekindsofBean,respectivelyBE:Action,ActionForm,EJBperhapsJavaBean.TheStrutsframehavenoconcretedefinitionmodellayerofrealization,inactuallythedevelopment,modellayerusuallyisclosewithbusinesslogicconnectwitheachother,andwanttocarryonoperationtothefirstfloordata.Theunderneathsintroductionisakindofdevelopmentstrategy,leadtheHibernateintothemodellayerofStrutsframe,usageittocarryonadatatopackwithreflecttoshoot,provideholdoutforlongtimeturnofsupport.IVusageHibernateandtheStrutsdevelopmentJIIEEapplicationIV.I.systemstructurediagramIIImanifestationaccordingtoHibernateandStrutsdevelopmentstrategyofsystemstructurediagram.
III.SpringtheApplicationFramework
Springisn’tparticularlyawebframeworkbutagenericlightweightapplicationframeworkwithdedicatedwebsupport,andshowsthearchitecturaldifferencestoStrutsandWebWork.IncontrasttoStrutsorWebWork,Springisanapplicationframeworkforalllayers:Itoffersabeanconfigurationfoundation,AOPsupport,aJDBCabstractionframework,abstracttransactionsupport,etc.Itisaverynon-intrusiveeffort:YourapplicationclassesdonotneedtodependonanySpringclassesifnotnecessary,andyoucanreuseeverypartonitsownifyouliketo.Fromitsverydesign,theframeworkencouragescleanseparationoftiers,mostimportantlywebtierandbusinesslogic:e.g.thevalidationframeworkdoesnotdependonwebcontrollers.Majorgoalsarereusabilityandtestability:Unnecessarycontainerorframeworkdependenciescanbeconsideredavoidableevils.
Ofcourse,Springsownwebsupportisnicelyintegratedwiththeframeworksgeneralpatterns.Nevertheless,replacingthewebsolutionwithStruts,WebWork,orthelikeiseasy.BothwithSpringswebsupportoradifferentone,Springallowsforbuildingatruededicatedmiddletierinthewebcontainer,withtheoptiontoreuseexactlythesamebusinesslogicintestenvironmentsorstandaloneapplications.AndwithinJIIEE,yourbusinesslogicwillnotunnecessarilydependoncontainerserviceslikeJTAorEJB-allowingcomplex,well-architectedwebapplicationstorunina"simple"containerlikeTomcatorResin.NotethatSpringdoesntgenerallyaimtocompetewithexistingsolutions.ItratherfostersseamlessintegrationwithstandardslikeServlet,JSP,JTA,JNDI,JDBC,andJDO,andwell-suitedtoolslikeHibernate,Velocity,LogIVJ,andCauchosHessian/Burlap.Theframeworkisdesignedtogrowwiththeneedsofyourapplications,intermsoftechnologychoice:Forexample,youwillprobablyuseJTAviaSpringsJtaTransactionManagerifyouneeddistributedtransactions-butonlythen,asthereareperfectreplacementsforsingledatabases,likeDataSourceTransactionManagerorHibernateTransactionManager.
IV.TheDesignofSpringsWebFramework
SpringswebframeworkisdesignedaroundaDispatcherServletthatdispatchesrequeststohandlers,withconfigurablehandlermappings,viewresolution,andlocaleandthemeresolution.ThedefaulthandlerisaverysimpleControllerinterface,justofferinga"ModelAndViewhandleRequest(request,response)"method.Thiscanalreadybeusedforapplicationcontrollers,butyouwillprefertheincludedimplementationhierarchy,consistingofAbstractController,AbstractCommandController,MultiActionController,SimpleFormController,AbstractWizardFormController.Applicationcontrollerswilltypicallybesubclassesofthose.Notethatyoucanchooseanappropriatebaseclass:Ifyoudonthaveaform,youdontneedaFormController.ThisisamajordifferencetoStruts.
Youcantakeanyobjectascommandorformobject:Theresnoneedtoimplementaninterfaceorderivefromabaseclass.Springsdatabindingishighlyflexible,e.g.ittreatstypemismatchesasvalidationerrorsthatcanbeevaluatedbytheapplication,notassystemerrors.SoyoudontneedtoduplicateyourbusinessobjectspropertiesasStringsinyourformobjects,justtobeabletohandleinvalidsubmissions,ortoconverttheStringsproperly.Instead,itsoftenpreferabletobinddirectlytoyourbusinessobjects.ThisisanothermajordifferencetoStrutswhichisbuiltaroundrequiredbaseclasseslikeActionandActionForm-foreverytypeofaction.?ComparedtoWebWork,Springhasmoredifferentiatedobjectroles:ItsupportsthenotionofaController,anoptionalcommandorformobject,andamodelthatgetspassedtotheview.Themodelwillnormallyincludethecommandorformobjectbutalsoarbitraryreferencedata.Instead,aWebWorkActioncombinesallthoserolesintoonesingleobject.WebWorkdoesallowyoutouseexistingbusinessobjectsaspartofyourform,butjustbymakingthembeanpropertiesoftherespectiveActionclass.Finally,thesameActioninstancethathandlestherequestgetsusedforevaluationandformpopulationintheview.Thus,referencedataneedstobemodelledasbeanpropertiesoftheActiontoo.Thesearearguablytoomanyrolesinoneobject.Regardingviews:Springsviewresolutionisextremelyflexible.AControllerimplementationcanevenwriteaviewdirectlytotheresponse,returningnullasModelAndView.Inthenormalcase,aModelAndViewinstanceconsistsofaviewnameandamodelMap,containingbeannamesandcorrespondingobjects(likeacommandorform,referencedata,etc).Viewnameresolutionishighlyconfigurable,eitherviabeannames,viaapropertiesfile,orviayourownViewResolverimplementation.TheabstractmodelMapallowsforcompleteabstractionoftheviewtechnology,withoutanyhassle:BeitJSP,Velocity,oranythingelse-everyrenderercanbeintegrateddirectly.ThemodelMapsimplygetstransformedintoanappropriateformat,likeJSPrequestattributesoraVelocitytemplatemodel.
V.HibernatetheApplicationFramework
DatasholdingoutforlongtimelayerandHibernateisonepieceaccordingtoholdoutforlongtimelayerframe,isakindofrealizationobjectandrelationofthetoolwhichreflecttoshoot(O/RMapping),itcarriedontheobjectofthelightweighttopacktotheJDBCandmakeproceduremembercanusageobjectplaitdistancethoughttooperationdatabase.ItnotonlyprovidedtoshootfromJavatoreflectofdataform,butalsoprovidedadataasearchandinstaurationmechanism.OppositeinusageJDBCandSQLtooperationdatabase,useHibernateabilityconsumedlyofexaltationrealizationofefficiency.TheHibernateframeuseallocationdocumentoftheformcometothereflectofthedefinitionJavaobjectanddataformtoshootrelation,inthemeantimeatmoredeepoflevelofdataformofrelationexplanationfortherelationssuchasinheritofandcontainmentetc.ofJavaobject.PasstheusageHQLlanguagesentencecomplicationsofrelationthecalculatewayusethewayofobjectdescription,toalargeextentsimplificationlogarithmsaccordingtoofsearch,speeddevelopmentofefficiency.HaveintheHibernateasimplebutkeeptheAPIofview,usedfortothedatabasemeanofobjectperformancesearch.Wanttoestablishorthemodificationbetheseobjects,needintheprocedurecarryonwiththemtohandoverwitheachother,thentellHibernatetokeep.So,agreatdealofpackholdoutforlongtimeturnoperationofbusinesslogicnolongerdemandwriteatrivialJDBClanguagesentence,makedatalastlongthusthelayergotbiggestofsimplification.
VI.UseHibernateandStrutstodevelopJIIEEapplication
Developmentpracticeunderneathcombineadevelopmentpractice,withintheJIItheEEtheapplicationverywidespreadcustomerregisterprocessforexample,elucidationabove-mentionedsystemstructureishowconcreteusage.Theprocessofregisterisveryclear:Customerfromregisterpagelogin.jspimportationregisterinformation,systemtoregistertheinformationcarryonverification,ifexactitudesuccessregister,otherwisehintcorrespondmistakeinformation.Inthedevelopmentprocess,theusageEclipsebeusedasdevelopmentenvironmentandaddedtocarrytoprovidetotheStrutsandtheHibernateinthemeantimebettercontrolandsupportofthreesquareplug-inMyEclipse,WebserverusageTomcat,thedatabasechosetouseMysql.CarryonanallocationtotheHibernatefirst,needtothesystemautothebornhibernate.cfg.xmlcarryonmodification,allocationgooddatabaseconjunctionofvariousparameteranddefinitionthedatareflecttoshootadocument.BecausetheHibernatetakeofconjunctionpondmainusedfortest,thefunctionisntverygood,canpassJNDIwillitmodificationisusageTomcatofconjunctionpond.
VII.Summary
Inthispaper,weintroducedtheStrutsapplicationframework.AndintroducessomebasicknowledgeaboutSpringandHibernate,.WealsoshowhowtouseHibernateandStrutsdevelopmentJIIEE,andhowitusedtobeservletsandJSPincombinationinthesameapplication.NowthatyouhaveatasteoftheStrtusWebapplication,afterthatwewilldigdeeperintothetheoryandpracticebehindtheStrutsarchitecture.
版权保护: 本文由 hbsrm.com编辑,转载请保留链接: www.hbsrm.com/lwqt/wxzs/215.html