JAVA网页设计Velocity A template engine OR A Rule...
学习JAVA的目的更多的是培养自身的工作能力,我觉得工作能力的一个核心就是:独立思考能力,因为只有独立思考后,才会有自己的见解March2005
Discussion
Velocity:AtemplateengineORARuleengineORBoth?
MostofthedevelopersmustbefamiliarwithVelocityasagreatopensourcetemplateengineandIdon’tthinkIneedtosaymuchaboutitsusesandfeaturesasatemplateengine.Thispapercompilesitsfeaturesasaruleengine.
Ihavebeenworkingwithjavaforthepast6yearsandrecently,IgotanopportunitytodesignanddevelopanEntitlementApplication.
Anentitlementistheresultoftheexecutionofaformula,orrulethatspecifieswhatmustbeconsideredwhendecidingwhetheragivenuserhasrightstomanipulateoruseagivenresource(orobject).Thisrulemaybecomposedofoneormoreconditionsthatmightonlybeevaluatedwithapplicationcontextspecificdata.Inaddition,aruleevaluationmayresultinmorethansimpleyes/noanswersandcontainadditionalinformationthatwouldberequiredbyanapplicationtonowperformtherequestedaccesstotheresource.Thesearecalledobligations.ThereforeanEntitlementServicecanbeusedbothasaruleevaluatorandaprivilegedataservice.
InitssimplestformanEntitlementServiceperformsstandardauthorizationcalls.Forexample,canauserperformasimpleactionagainstanamedresource?Initsmorecomplicatedformanentitlementmaybearuleonhowanobjectsuchasafinancialtransactionmaybemanipulated.Inthisrulethespecificparametersofthetransactionmaybecomparedagainstsetlimitsorcurrentfinancialdata.Theruleinthiscasemaybearepresentationofbusinesslogic.
Therearefourtypesofentitlement:
Coarse-grainedentitlement-Thecontrolofaccesstobroadcategoriesofresources,forexample,anentireapplication,anentiresubsystem,oraccesstospecificwebpages.
Fine-grainedentitlement-Thegrantingorwithholdingofindividualresourceslikebuttons,links,menuchoicesonapageorscreen,orfunctionswithinaprogram.
Transactionalentitlement-Anentitlementthatchecksprivilegetomanipulatearesourcebyexaminingveryspecificparametersabouta‘transaction’uponthatresource.Thecharacteristicsoforrelationshipsbetweentheseparameterscouldbeexpressednumerically(<,>,=,…),usingdateandtimeinformation,orevenaspartofaformula(*,%,/,-,+).
Dynamicentitlement-Whereaparameterofa‘transaction’representsinformationthatmustbecalculatedorretrievedfromanexternalsource.Thisinformationmayberetrievedbyacalltoanapplicationspecificservice.
Soaccordingtotherequirements,thisapplicationhastohave:
Somelogictoreturnthestoreddata(Users,UserGroups,Resources,ResourceGroups,Permissionsetc)basedonsomefilters.Forexamplereturnmealltheuserswhohaveanaccessonthisresource.Logictocheckthepermission.PermissionsareBooleaninnatureanddon’trequireanycomplexlogictoprocess.Although,permissionareverysimpletheyarequietpowerfulforbuildinganentitlementapplicationandcatertomostofthecasesofCoarse-grainedandFine-grainedentitlements.ArulebasedenginetohandleTransactionalandDynamicentitlements.
Now,wewilldirectlyfocusontheusesofVelocityasaruleengineasthisarticleisnotaboutdevelopinganentitlementapplication.
So,insteadofdevelopingmyownruleengineIstartedlookingaroundtofindoutadecentruleenginethatcanfulfillmyrequirements.AndIbegantoexploreruleengineslike:
JEL(http://galaxy.fzu.cz/JEL),BeanShell(http://www.beanshell.org/home.html),EL(http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html)
andmanymore,especiallytheoneswithopensourcesbecausemymanagementdidnotwanttospendtoomuchmoneyonthisapplication.
WhatIwaslookingforwasanenginewiththefollowingfeatures:
Easeofuseindevelopment.Shouldreducemydevelopmenttime.Easyandflexibleintermsofconfiguration.Itshouldhaveveryeasyandfamiliarlanguagetowriterulesespeciallyforanon-technicaladmintomaintain.Easilyextendable.Clearseparationbetweenadmin(Ruleauthor)anddeveloper.Testedandreliable.Greatcommunitysupport.NobodyisperfectandeverybodyneedsHelp:)
ButIcouldn’tfindanythinggoodenoughoutthere.Suddenly,Velocitygotmyattention.IhavealreadyusedVelocitytogeneratemyGUI.However,thistime,Iwaslookingatitwithadifferentpointofview.Iwascompilingitsfeaturesintermsofaruleengineanditseemedtomeaconsiderablefitforthisnewframework.ThenitbecameaperfectfitwhenIrealizeditsusesoftoolboxconceptaswell.ThetoolboxconceptprovidesthepowertoruleanauthortoaccessanyEISorapplication(almostanything)atruntimeandwithacompletetransparencytotheauthor.
NowletsgooverareallifeexampleanduseVelocityasruleengine.Beforewegoahead,letsconfigureVelocity.
Velocitycanbeusedasaservletinawebapplicationorasautilityinastandaloneapplication.Inourcase,wewilluseitasastandaloneapplication.Now,asastandaloneapplication,youcanuseitintwoways.Oneissingletonanotherisseparateruntimeinstance.Iuseditassingleton.Followingisthecodesample:
publicclassRuleEngineVelocityImplimplementsRuleEngine{publicRuleEngineVelocityImpl{try{//InitializeVelocity.Velocity.init();}catch(Exceptione){//Dosomething.}}publicStringexecute(StringruleId,Mapparams){//getthevelocitytemplatefromsomestorage.Stringtemplate=getFromSomewhere(ruleId);//CreateaContextobject.VelocityContextcontext=newVelocityContext(params);//Getatemplateasstream.StringWriterwriter=newStringWriter();StringReaderreader=newStringReader(template);//askVelocitytoevaluateit.booleanresult=Velocity.evaluate(context,writer,ruleId,reader);StringstrResult=null;if(result){strResult=writer.getBuffer().toString();}returnstrResult;}publicstaticvoidmain(String[]args){//addthevariableandtheirvalueswhichisbeingreferredin//template/rule.Mapparams=newHashMap();params.put("Anykey",AnyObject);//InitializeRuleEngineandexecutetherule.RuleEngineengine=newRuleEngineVelocityImpl();Stringresult=engine.execute("MyRule",params);System.out.println("Result:"+result);}}
Now,wewillwritearuletocheckacreditlimitforsomeuser.AVTLtemplate/ruleforthismaylooklikethis:
#if($creditLimit>1000)Overlimit.Youcantcompletethistransaction.##ORjustaBooleanvaluelikefalse###else#set($creditLimit=1000-$creditLimit)Now,yourbalanceis${creditLimit}.##ORjustaBooleanvalueliketrue###end
Youcanstoretherulesinafileorinadatabaseorinanyanotherdatastorage.Inmycase,Istoredtheserules/templatesinaRDBMSandIprovidedanAdminGUItomaintainthem.Letsassumedatabasetable,‘Rule’withtwocolumns,RuleIdandTemplate.IinsertarulewithRuleId“Chk_Credit_Limit”.
Now,letsmodifythemainmethodof“RuleEngineVelocityImpl“class.
publicstaticvoidmain(String[]args){Mapparams=newHashMap();params.put("creditLimit",newInteger(200));//InitializeRuleEngineandexecutetherule.RuleEngineengine=newRuleEngineVelocityImpl();Stringresult=engine.execute("Chk_Credit_Limit",params);System.out.println("Result:"+result);}
Theoutputwillbe:
Now,yourbalanceis800.
Doesn’titsoundsveryfamiliarandeasy?Ithastobe.Itisvelocity,dude!!!
Now,letsseethepoweroftoolboxconcept.
Naturally,VelocityonlysupportsintegerbutVelocitytoolsprojectaddsthepowertoVelocitytodoanykindofMath,Dateprocessingandformattingwhichyouwillneedtousefortheruleengine.
Sinceatoolboxisextendableandit’sveryeasytowriteatool(almostanyclasswithpublicmethodcanbeusedastool)youhaveunlimitedopportunitiestowriteNnumbersoftoolscorrespondingtoyourapplication/requirementscontextandallwillbeavailabletoruleauthorforwritingthesmartrules.Forexample,letssayanairlinecompanyhascomeupwithabusinessruleforyear2005thatstates:
Ifbookingdateisonaspecialdaylistthengetthediscountedrate,otherwiseusethenormalfare.
Letsassumethisdiscountedrateandspecialdaylistisstoredinsomedatabaseandbotharebeingmaintainedbysomeotherapplication.Thisspecialrateisvalidonlyforyear2005anditmaychangeorcanbecompletelyeliminatedinyear2006.Insuchcaseitwillnotbewisetobuildtheapplicationtocatertotheabovebusinessrequirementsandchangeitlater.
Soletsaddressthisproblemwiththerules.Beforewewritearuleweneedtwovaluesavailableataruntime.Oneisaspecialdaylistandtheotheristhediscountrate.LetswriteaToolclass(com.RateHelper)similartowhatwehavealreadyinVelocitytools:Math,Dateetc.Thesignatureofthisclasswouldbeasfollows:
publicDoublegetRate();publicbooleanisInSpecialDayList(Stringday);
AnyclasswithpublicmethodcanbehavelikeatoolinVelocity.That’sthemagicofintrospection:)
AfterwritingthisclassletsadditasatoolinVelocityengine.Wealreadyhaveabeautycalled“XMLToolboxManager”toaddNnumberoftoolsinVelocityautomatically.Wejustneedtospecifyourtoolsinanxmlfilecalledtoolbox.xml.
<toolbox><tool><key>rateHelper</key><scope>application</scope><class>com.RateHelper</class></tool></toolbox
Now,letsmodifyourRuleEngineVelocityImplclasstoloadthistoolboxbyaddingthebelowlineintheconstructorafterinitializingVelocity.
XMLToolboxManagertoolboxManager=newXMLToolboxManager();toolboxManager.load(this.getClass().getClassLoader().getResourceAsStream("toolbox.xml"));toolboxContext=toolboxManager.getToolboxContext(null);
Andnowreplacethebelowlineinexecutemethod:
VelocityContextcontext=newVelocityContext(params);
withthethisline:
VelocityContextcontext=newVelocityContext(toolboxContext,params);
Thisiscontextchaining.Pleaserefertheapachedocumentationformoreinformationonit.
Okay,weareallset.Letswritethebusinessrule(usingourcustomtool)andstoreitinourdatabasewithRuleId“get_price”
#if($rateHelper.isInSpecialDayList($day))$rateHelper.getRate()#else2500##Regularprice###end
Now,letsmodifythemainmethodagaintoexecuteournewrule.
publicstaticvoidmain(String[]args){Mapparams=newHashMap();params.put("day","02/28/05");//InitializeRuleEngineandexecutetherule.RuleEngineengine=newRuleEngineVelocityImpl();Stringresult=engine.execute("get_price",params);System.out.println("Result:"+result);}
Theoutputwillbe(if02/28/05isnotinspecialdaylist):2500
Isn’titeasyandpowerful?
Inadditiontotoolbox,Iassociatedproperties(key-valuepair)toobjectslikeUser,UserGroup,Resource,ResourceGroupwhichImadeavailabletoruleauthor.Thisgivestheauthormoreflexibilitytowritesmartsrules.Forexample,thereisausergroupinacompanywheresomeoftheuserscanonly“buy”theproductandsomeofthemcanonly“sell”theproductandtherestofthemcandoboth.Wecanassociateapropertycalled“ActionDirection”witheveryuserofthegroupandthepossiblevaluesforthepropertywillbelike“BUY”,“SELL”and“BOTH”.Aruleauthorcanuseitfreelyinhisrulestodistinguishamongtheuseractions.
Velocitywasintenselywrittenasatemplateengineandit’soneofpioneersinthisareabutyoucanseethatitisalsoagreatRuleengine.Combinationofproperties,toolboxandparametersmakesitmorepowerfulandperfectlysuitableforthistask.Andmostimportantly,somebodyhasuseditsuccessfullyasruleengine.
Reference:
1)http://jakarta.apache.org/velocity/index.html
Thanksto:
-MarcandNormwhobroughtmeintothisproject.
-Margaretforherediting.:)
origionallink:Velocity:AtemplateengineORARuleengineORBoth?
j2EE和asp比较,其实也没什么比的,原因和我上面说那些比较差不了多少,也是稳定性,安全性,J2EE比asp高,速度上比不过asp,asp也是延续着它的拖拽控件的方法,提高速度。 不过,每次的执行编译后的字节码需要消耗一定的时间,这同时也在一定程度上降低了 Java 程序的运行效率。 J2SE开发桌面应用软件比起 VC,VB,DEPHI这些传统开发语言来说,优势好象并不明显。J2ME对于初学者来说,好象又有点深奥,而且一般开发者很难有开发环境。 Java 不同于一般的编译执行计算机语言和解释执行计算机语言。它首先将源代码编译成二进制字节码(bytecode),然后依赖各种不同平台上的虚拟机来解释执行字节码。从而实现了“一次编译、到处执行”的跨平台特性。 Java 不同于一般的编译执行计算机语言和解释执行计算机语言。它首先将源代码编译成二进制字节码(bytecode),然后依赖各种不同平台上的虚拟机来解释执行字节码。从而实现了“一次编译、到处执行”的跨平台特性。 Java是一个纯的面向对象的程序设计语言,它继承了 C++语言面向对象技术的核心。Java舍弃了C ++语言中容易引起错误的指针(以引用取代)、运算符重载(operator overloading) 有时间再研究一下MVC结构(把Model-View-Control分离开的设计思想) 让你能够真正掌握接口或抽象类的应用,从而在原来的Java语言基础上跃进一步,更重要的是,设计模式反复向你强调一个宗旨:要让你的程序尽可能的可重用。 Java是一种计算机编程语言,拥有跨平台、面向对java 科学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。 设计模式是高级程序员真正掌握面向对象核心思想的必修课。设计模式并不是一种具体"技术",它讲述的是思想,它不仅仅展示了接口或抽象类在实际案例中的灵活应用和智慧 是一种由美国SUN计算机公司(Sun Microsystems, Inc.)所研究而成的语言 自从Sun推出Java以来,就力图使之无所不包,所以Java发展到现在,按应用来分主要分为三大块:J2SE,J2ME和J2EE,这也就是Sun ONE(Open Net Environment)体系。J2SE就是Java2的标准版,主要用于桌面应用软件的编程;J2ME主要应用于嵌入是系统开发,如手机和PDA的编程;J2EE是Java2的企业版,主要用于分布式的网络程序的开发,如电子商务网站和ERP系统。 所以现在应用最广泛又最好学的就是J2EE了。 J2EE又包括许多组件,如Jsp,Servlet,JavaBean,EJB,JDBC,JavaMail等。要学习起来可不是一两天的事。那么又该如何学习J2EE呢?当然Java语法得先看一看的,I/O包,Util包,Lang包你都熟悉了吗?然后再从JSP学起。 还好,SUN提供了Javabean可以把你的JSP中的 Java代码封装起来,便于调用也便于重用。 是一种使网页(Web Page)产生生动活泼画面的语言 多重继承(以接口取代)等特性,增加了垃圾回收器功能用于回收不再被引用的对象所占据的内存空间,使得程序员不用再为内存管理而担忧。在 Java 1.5 版本中,Java 又引入了泛型编程(Generic Programming)、类型安全的枚举、不定长参数和自动装/拆箱等语言特性。 多重继承(以接口取代)等特性,增加了垃圾回收器功能用于回收不再被引用的对象所占据的内存空间,使得程序员不用再为内存管理而担忧。在 Java 1.5 版本中,Java 又引入了泛型编程(Generic Programming)、类型安全的枚举、不定长参数和自动装/拆箱等语言特性。 你可以去承接一些项目做了,一开始可能有些困难,可是你有技术积累,又考虑周全,接下项目来可以迅速作完,相信大家以后都会来找你的,所以Money就哗啦啦的。。。。。。 象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。
页:
[1]