|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
还有就是总有人问我到底该学习什么语言,什么语言有前途,那么我的回答是不论是C,C++,java,.net,ruby,asp或是其他语言都可以学,编程的关键不是语言,而是思想。js
--2种ModelI体例:和ModelIILanceLavandowska
blueski
编译:
Servlet
假如你常常往或JSP的ModelI旧事组大概邮件列表,那末必定会看到很多关于和ModelII方OOP法的会商。事实接纳哪种,这取决于你的团体喜欢、团队事情战略和是不是接纳正统的。ModelI
复杂地说,将businesslogic事件逻辑()presentationcode和暗示代码()HTML交融在一同(如在中ModelII);则倡始最年夜限制地将一切的代码放到内容暗示以外。ModelI
:简单的单条理使用Java
假如是在一团体人都精晓和HTML的HTML情况中,大概你单独做着一切的事情,假设每一个人都有明晰的编程布局和思绪,那末这类办法会很无效,不外如许的假定不在本文会商局限以内。这类办法的第一个长处是假如你的使用改动了,你只需保护一个文件。而最年夜的缺点是可读性!除非非常当心,不然你的和Java代码会互相混同,从而难以保护。TimeZone
鄙人面这个例子中,我们将增添一个元JSP素,从而使它酿成文TimeZone件,它会前往基于工夫的所等候的。TimeZone假如没有提交,那末缺省的是服务器的缺省工夫。
======================================================================xmlversion
<=1.0""?>H1
TimeJSP<H1>jsp
<:scriptlet>theparameter
//"zone"shallbeequaltoanumberbetween0and24(inclusive)TimeZonetimeZone
=TimeZone.getDefault();/returnsthedefaultTimeZonefortheserver/if
(request.getParameterValues(zone"")!null=)
{StringtimeZoneArg
=request.getParameterValues(zone""0)[];timeZone
=TimeZone.getTimeZone(GMT"+"+timeZoneArg+"00:");getsaTimeZone.Forthisexamplewe
//rejustgoingtoassumeitsapositiveargument
//,notanegativeone.
}sincewe
//rebasingourtimefromGMT,wellsetourLocaletoBrittania,andgetaCalendar.CalendarmyCalendar
=Calendar.getInstance(timeZone,Locale.UK);jsp
</:scriptlet>myCalendar.get
<%=(Calendar.HOUR_OF_DAY)%>:myCalendar.get
<%=(Calendar.MINUTE)%>:myCalendar.get
<%=(Calendar.SECOND)%>
======================================================================JavaBean
响应地,数据也能够从取得并加以显现。鄙人一个例子中我们就能够看到。ModelII
:重RedirectingRequests定向哀求()HTML
在一个团队开辟情况中,有些是设Java计者,另外一些则是程Java序员,这时候这一办法显得十分主要。程HTML序员能够会合精神创立可重用代码,而设计师能够会合精神于内容暗示,相互绝对对峙,能够分离静态地修正本人的内容,只需整体的输出输入稳定。ModelII
如今我们可使用来ModelI暗示的Model-View-Controller谁人例子。这一办法遵守了(MVC)范例(citeDesignPatternsbook)。在servlet这个例子中,我们只要一个类(页大概)处Controller理哀求()TimeZone,获得,View设置一切用于暗示的变量,并将把持传送到暗示页()。作为云云复杂的使用,能够没有"Model"。Controller
:timeByZone.jspcontroller
可servlet所以一个或JSP一个页JSP。我保举利用,granularity由于如许我不用忧虑每当我做修正时要对类从头编译,可是,你将因而得到(颗粒性),今后要扩大该类也对照坚苦。
======================================================================xmlversion
<=1.0""?>--WorkerClass
<!,nobodyshouldseeme-->jsp
<:scriptlet>theparameter
//"zone"shallbeequaltoanumberbetween0and24(inclusive)TimeZonetimeZone
=TimeZone.getDefault();/returnsthedefaultTimeZonefortheserver/if
(request.getParameterValues(zone"")!null=)
{StringtimeZoneArg
=request.getParameterValues(zone""0)[];timeZone
=TimeZone.getTimeZone(GMT"+"+timeZoneArg+"00:");getsaTimeZone.Forthisexamplewe
//rejustgoingtoassumeitsapositiveargument
//,notanegativeone.
}TimeBeantimeBean
=newTimeBean();timeBean.setHours
=myCalendar.get(Calendar.HOUR_OF_DAY);timeBean.setMinutes
=myCalendar.get(Calendar.MINUTE);timeBean.setSeconds
=myCalendar.get(Calendar.SECOND);HttpSessionmySession
=request.getSession();mySession.putValue
(tempTimeBean""timeBean,);jsp
</:scriptlet>jsp
<:forwardpage=displayTime.jsp""/>
======================================================================View
:displayTime.jspview
一样地,这个既servlet能够是一个也jsp能够是一个文Session件。这里我们从中Bean获得并显现它的值。实践上我们会将这做两次,来树模是怎样被利用的。
======================================================================xmlversion
<=1.0""?>H1
TimeJSP<H1>jsp
<:useBeanclass=TimeBean""id=tempTimeBean""scope=session""/>jsp
<:getPropertyname=tempTimeBean""property=hours"">:jsp
<:getPropertyname=tempTimeBean""property=minutes"">:jsp
<:getPropertyname=tempTimeBean""property=seconds"">--thesewouldhaveprinted
<!"null"iftempTimeBeanwasnotinstantiatedbytimeByZone.jsp-->jsp
<:scriptlet>HttpSessionmySession
=request.getSession();TimeBeantimeBean
=mySession.getValue(tempTimeBean"");if
(timeBean!null=)
{/checktomakesureitsnotnull/,toavoidNullPointerExceptionsout.print
(timeBean.getHours());out.print
(":");out.print
(timeBean.getMinutes());out.print
(":");out.print
(timeBean.getSeconds());
}else
{out.println
(PressyourBackbuttonandselectaTimeZone"");
}jsp
</:scriptlet>
======================================================================null
第二种办法(在外部利用了代码)大概有些粗笨,但同意开辟者确保输入不至于很糟(比方":null:nullnull"Sessionbean),假定还没有被实例化和没有举行值的设置。这View种情形产生在客户端间接挪用了页scriptlets。成绩是利用剧本可url以同意更强的把持。假如你确信你能够把持存bean取,那末方View法固然更合适于开辟,并使页HTML更便利于设计者的协同事情。ModelII
下面的是"传统的"设Session计。一切的变量都包装了并放在对2象中。这有个不敷:1
)如Session果客户端回绝介入的话,是不成失掉的。2
)除Session非变Session量被显式地移走,不然它回一向存在,直到被损坏或过时。cookies
第一种案例极可能产生在如许的场所,即便用了作mechanism为声明的布局()form而开辟者没有可以供应声明的布局的替换表单()URL,即改写。Sessions
第二个案例乃至更加严峻,由于它大概引发很年夜的内存损耗,假如被30界说为保留比尺度存留工夫更长的话((尺度存留工夫是分30钟)。即便是分Session钟的,Model这类也Session大概在年夜的使用中引发劫难性的内存保守。为何呢?在对Session象外部设置的对象被实例化了,而且在终references止之前一向没有被移往。由于它们仍旧有联系关系(Session对象)指garbage-collected向它们,以是没法被渣滓搜集()ModelII。在模Session型中,良多对象被放到中JavaBean(要末间接地,要末经由过程)Session。跟着的Session举行,更多的页被存取,内存利用会增添并延续下往直到客户端停止了或Session者过Session期。要一向比及变.得不法,放在那的对象才干被渣滓搜集,而那些丧失的内存本能够用于任何别的的用处。Beans
改善的办法之一是将或Request者别的变量放到对RequestDispatcher.include象中往,并利用(RequestDispatcher.forward)而不是(View)。如许做今后,页Controller具有和一ModelII样的存取哀求的对象。传统的设计的不敷能够被扫除。ModelII
一个最初的评注:只管有如上所述,我团体仍有些不喜好的典范,假如它用一般办法开辟的话。客户端被引送到某一个地点,然后又被转向到另外一个分歧的类,我不喜好创立如许的体系。基于如许的缘故原由,我修正了计划,使它酿成了以下的模样:Controller
:timeByZone2.jspcontroller
和后面一样,使Request用值View来获得需要的数据,而且将数据放到哀求的对象中往。这回的区分是页RequestDispatcher.include将利用(Controller)来挪用。chained在这类办法中,客户端不再做重定向,哀求不是"链接”class的。相称于/jsp请求了另外一方来为它做一些事情,然后持续。
======================================================================xmlversion
<=1.0""?>--WorkerClass
<!,nobodyshouldseeme-->jsp
<:scriptlet>theparameter
//"zone"shallbeequaltoanumberbetween0and24(inclusive)TimeZonetimeZone
=TimeZone.getDefault();/returnsthedefaultTimeZonefortheserver/if
(request.getParameterValues(zone"")!null=)
{StringtimeZoneArg
=request.getParameterValues(zone""0)[];timeZone
=TimeZone.getTimeZone(GMT"+"+timeZoneArg+"00:");getsaTimeZone.Forthisexamplewe
//rejustgoingtoassumeitsapositiveargument
//,notanegativeone.
}TimeBeantimeBean
=newTimeBean();timeBean.setHours
=myCalendar.get(Calendar.HOUR_OF_DAY);timeBean.setMinutes
=myCalendar.get(Calendar.MINUTE);timeBean.setSeconds
=myCalendar.get(Calendar.SECOND);request.setAttribute
(tempTimeBean""timeBean,);jsp
</:scriptlet>
======================================================================View
:displayTime2.jspdisplayTime.jsp
和非timeByZone2.jsp常类似,但在也的顶部被挪用。请注重<jsp:useBean/>中scope的""request已被换成了""。
======================================================================xmlversion
<=1.0""?>H1
TimeJSP<H1>jsp
<:includepage=timeByZone2.jsp""/>jsp
<:useBeanclass=TimeBean""id=tempTimeBean""scope=request""/>jsp
<:getPropertyname=tempTimeBean""property=hours"">:jsp
<:getPropertyname=tempTimeBean""property=minutes"">:jsp
<:getPropertyname=tempTimeBean""property=seconds"">--thesewouldhaveprinted
<!"null"iftempTimeBeanwasnotinstantiatedbytimeByZone2.jsp-->
======================================================================View
在一个在建体系中,我们已利用这类办法来创立类的链,每个都只对它所处置的事情卖力。经由过程分辨公用的暗示格局,我们创立了一个对JSP象,即便在很高条理的中它也能够反复利用。我们的方针就是创建一些可重用的页,同时削减用于暗示的类的数目。ServletModel
单个的(AModelIIDesign)
甚么时分我有充足工夫来研讨这个课题,我会在这里宣布更多的工具。
附原文:JSPArchitectures
Anexplanationandcomparisonofthemethodologies
commonlyknownas
"ModelI"and"ModelII".LanceLavandowskaToOutline
IfyouspendanytimereadingthroughServletorJSPrelatednewsgroupsormailinglists
,yourelikelytoencounteradiscussionofModelIversusModelIImethodologies.Whichoneyouusedependsonpersonaltaste,teamworkstrategiesandOOPorthodoxy.Looselydescribed
,ModelIisanapproachwherebusinesslogicandpresentationcodecanbeintermixedwiththepresentationitself(HTMLinourarena).ModelIIproscribesthatallcode,totheextentthisispossible,beexcludedfromthepresentation.ModelI
:Simple21/2TierApplicationInateamenvironmentwhereeveryoneknowsJavaandHTML
,orifyouredoingitallyourself,thisapproachcanworkwell,providedeveryonemaintainsaclearcodingstructure(thatdiscussionisoutsidetheboundsofthisarticle).Theprimaryadvantageofthisapproachisthatthereisonlyonefiletomaintainforchangestoyourapplication.Themajordisadvantageisreadability!Unlessgreatcareistaken,yourHTMLandJavacodecanbecomesointermingledthatitbecomesdifficulttodebugandmaintainyourapplication.Forthisexample
,wearegoingtorevisitthe"SamplePage"fromtheJSPQuickStartchapter.ImgoingtoaddaTimeZoneelement,sowellhaveaJSPthatreturnsthetimebasedonthedesiredtimezone.IfnoTimeZoneissubmitted,welldefaulttothatoftheserver.
======================================================================xmlversion
<=1.0""?>H1
TimeJSP<H1>jsp
<:scriptlet>theparameter
//"zone"shallbeequaltoanumberbetween0and24(inclusive)TimeZonetimeZone
=TimeZone.getDefault();/returnsthedefaultTimeZonefortheserver/if
(request.getParameterValues(zone"")!null=)
{StringtimeZoneArg
=request.getParameterValues(zone""0)[];timeZone
=TimeZone.getTimeZone(GMT"+"+timeZoneArg+"00:");getsaTimeZone.Forthisexamplewe
//rejustgoingtoassumeitsapositiveargument
//,notanegativeone.
}sincewe
//rebasingourtimefromGMT,wellsetourLocaletoBrittania,andgetaCalendar.CalendarmyCalendar
=Calendar.getInstance(timeZone,Locale.UK);jsp
</:scriptlet>myCalendar.get
<%=(Calendar.HOUR_OF_DAY)%>:myCalendar.get
<%=(Calendar.MINUTE)%>:myCalendar.get
<%=(Calendar.SECOND)%>
======================================================================Similarly
,thedatatobedisplayedcouldhavebeengottenfromaJavaBean.Wellseealittleofthatinthenextexample.ModelII
:RedirectingRequestsInateamenvironmentwheresomemembersareHTMLdesignersandothersareJavaprogrammers
,thisapproachcanbeparticularlystrong.TheJavaprogrammerscanfocusoncreating(re)usablecode,whiletheHTMLdesignerscanfocusonpresentation.Whilethetworemaindependantoneachother,oneortheothercanchangedramaticallysolongastheprincipleinputsandoutputs(respectively)remainthesame.Nowwe
lltakethesamedesiredbehaviourfromtheModelIexample,andpresentitusingtheModelIImethodology.ThismethodologyfollowstheModel-View-Controller(MVC)paradigm(citeDesignPatternsbook).Forthisexample,wellhaveoneclass(orpageorservlet)processtherequest(Controller)gettheTimeZone,,setalltherequiredvariablesforpresentation,andpasscontrolofftoapresentationpage(View).Forsimpleappslikethis,thereisno"Model".Controller
:timeByZone.jspThecontrollercanbeaservletorajspfile.IprefertouseJSP
,asIdonthavetoworryaboutcompilingtheclasseachtimeImakechanges.However,youlosegranularitythisway,andmakeitmoredifficulttoextendthisclasslater(wellreviewthisinAdvancedJSPProgramming).
======================================================================xmlversion
<=1.0""?>--WorkerClass
<!,nobodyshouldseeme-->jsp
<:scriptlet>theparameter
//"zone"shallbeequaltoanumberbetween0and24(inclusive)TimeZonetimeZone
=TimeZone.getDefault();/returnsthedefaultTimeZonefortheserver/if
(request.getParameterValues(zone"")!null=)
{StringtimeZoneArg
=request.getParameterValues(zone""0)[];timeZone
=TimeZone.getTimeZone(GMT"+"+timeZoneArg+"00:");getsaTimeZone.Forthisexamplewe
//rejustgoingtoassumeitsapositiveargument
//,notanegativeone.
}TimeBeantimeBean
=newTimeBean();timeBean.setHours
=myCalendar.get(Calendar.HOUR_OF_DAY);timeBean.setMinutes
=myCalendar.get(Calendar.MINUTE);timeBean.setSeconds
=myCalendar.get(Calendar.SECOND);HttpSessionmySession
=request.getSession();mySession.putValue
(tempTimeBean""timeBean,);jsp
</:scriptlet>jsp
<:forwardpage=displayTime.jsp""/>
======================================================================View
:displayTime.jspAgain
,theviewcanbeeitheraservletorajspfile.HerewellgettheBeanfromtheSession,anddisplayitsvalues.Wellactuallydothistwice,toillustrateagainhowBeansareused.
======================================================================xmlversion
<=1.0""?>H1
TimeJSP<H1>jsp
<:useBeanclass=TimeBean""id=tempTimeBean""scope=session""/>jsp
<:getPropertyname=tempTimeBean""property=hours"">:jsp
<:getPropertyname=tempTimeBean""property=minutes"">:jsp
<:getPropertyname=tempTimeBean""property=seconds"">--thesewouldhaveprinted
<!"null"iftempTimeBeanwasnotinstantiatedbytimeByZone.jsp-->jsp
<:scriptlet>HttpSessionmySession
=request.getSession();TimeBeantimeBean
=mySession.getValue(tempTimeBean"");if
(timeBean!null=)
{/checktomakesureitsnotnull/,toavoidNullPointerExceptionsout.print
(timeBean.getHours());out.print
(":");out.print
(timeBean.getMinutes());out.print
(":");out.print
(timeBean.getSeconds());
}else
{out.println
(PressyourBackbuttonandselectaTimeZone"");
}jsp
</:scriptlet>
======================================================================Thesecondmethod
(usingcodeinside)maybemorecumbersome,butallowsthedevelopertoensureagainstuglyoutput(suchas"null:null:nullnull"iftheSessionbeanhasnotbeeninstantiated)&haditsvaluesset.ThiswouldlikelyonlyhappeniftheclientsomehowcalledtheViewpagedirectly.Thepointisthatusingscriptletsallowsforgreatercontrol.Ifyouarecertainyoucancontrolurlaccess,thebeanapproachcertainlyeasesdevelopment,andmakestheViewpageeasierforHTMLdesignerstoworkwith.Theaboveisthe
"traditional"ModelIIdesign.YoullnotethatallthevariablesarewrappedupandplacedintotheSessionobject.Thishastwoweaknesses:1)noSessionisavailabebecausetheclienthasrefusedtoparticipate,2)unlesstheSessionvariableisexplicitlyremoveditwillcontinuetoexistuntiltheSessionisdestroyedorexpires.ThefirstcaseismostlikelytohappenwhencookiesareusedastheStatemechanismandthedevelopershavefailedtoprovideforthealternativeformofStatemaintenance
,URLrewriting.Thesecondcaseisevenmoreserious
,asitcanleadtogreatmemoryuseifSessionsaredefinedtoexistformorethanthestandardamountoftime(30minutesappearstobethestandard).Eveninthecaseof30minuteSessions,thisModelcanleadtodisastrousmemoryleaksinsystemsundergreatuse.Why?Objectsgetinstantiated,setinsidetheSessionobject,andarenotremoveduntiltheSessionends.Becausetheystillhavereferences(theSessionobject)pointingtothem,theyarenotgarbage-collected.IntheModelIIpattern,manyobjectsareplacedintotheSession(eitherdirectlyorviaaJavaBean).AstheSessionprogresses(morepagesareaccessed)memory-useincreasesandpersistsuntiltheclientendstheSessionortheSessiontimesout.UntiltheSessionisinvalidated,theobjectsplacedtherecannotbegarbage-collected,andthusconsumememorythatcouldbeofuseelsewhere.OnemeansofaddressingthisissueistoplacetheBeansorothervariablesintotheRequestobject
,anduseRequestDispatcher.include(ratherthanRequestDispatcher.forward)(.Bydoingso),theViewpagehasaccesstothesameRequestobjectastheController,andtheweaknessesofthetraditionalModelIIdesignareobviated.Onefinalcomment
:despitealltheabove,IhaveapersonaldistastefortheModelIIparadigmasitiscommonlyimplemented.Thecreationofasystemwheretheclientissenttoanaddress,butisredirectedtoadifferentclass,isforsomereasonabhorrenttome.Forthisreason,Ivemodifiedthedesigninthefollowingmanner:Controller
:timeByZone2.jspAsbefore
,thecontrollerusestheRequestvaluestoobtainthenecessarydataandputthatdataintotheRequestobject.ThedifferencethistimeisthattheViewpagewillcalltheControllerusingRequestDispatcher.include(.Inthisway),theclientisneverredirected,andRequestsarenot"chained".Rather,theclass/jspcalledaskssomeoneelsetodosomeworkforit,thencontinues.
======================================================================xmlversion
<=1.0""?>--WorkerClass
<!,nobodyshouldseeme-->jsp
<:scriptlet>theparameter
//"zone"shallbeequaltoanumberbetween0and24(inclusive)TimeZonetimeZone
=TimeZone.getDefault();/returnsthedefaultTimeZonefortheserver/if
(request.getParameterValues(zone"")!null=)
{StringtimeZoneArg
=request.getParameterValues(zone""0)[];timeZone
=TimeZone.getTimeZone(GMT"+"+timeZoneArg+"00:");getsaTimeZone.Forthisexamplewe
//rejustgoingtoassumeitsapositiveargument
//,notanegativeone.
}TimeBeantimeBean
=newTimeBean();timeBean.setHours
=myCalendar.get(Calendar.HOUR_OF_DAY);timeBean.setMinutes
=myCalendar.get(Calendar.MINUTE);timeBean.setSeconds
=myCalendar.get(Calendar.SECOND);request.setAttribute
(tempTimeBean""timeBean,);jsp
</:scriptlet>
======================================================================View
:displayTime2.jspMuchlikedisplayTime.jsp
,howeveryoullseethattimeByZone2.jspiscalledatthetopofthepage.Noticethatthescopeof<jsp:useBean/haschangedto>"request".
======================================================================xmlversion
<=1.0""?>H1
TimeJSP<H1>jsp
<:includepage=timeByZone2.jsp""/>jsp
<:useBeanclass=TimeBean""id=tempTimeBean""scope=request""/>jsp
<:getPropertyname=tempTimeBean""property=hours"">:jsp
<:getPropertyname=tempTimeBean""property=minutes"">:jsp
<:getPropertyname=tempTimeBean""property=seconds"">--thesewouldhaveprinted
<!"null"iftempTimeBeanwasnotinstantiatedbytimeByZone2.jsp-->
======================================================================Inasystemcurrentlyunderconstruction
,wevemadeuseofthismethodtocreatechainsofclasses,eachresponsibleforitsownprocessing.Byidentifyingcommonpresentationformats,wevecreatedViewobjectsthatcanbereusedinyethigherlevelJavaServerPages.Ourgoalistocreatepagesthataredesignedforreuse,andtoreducethenumberofpresentationclasses.SingleServletModel
(AModelIIDesign)WhenI
vehadtimetoadequatelyresearchandimplementthisidea,Illpostsomethinghere.
java比较简单,没有C++的烦琐,但学习时最好有C++为基础.与JSP和SQL起应用,功能强大. |
|