This is about some of the usage of velocity, the use of more basic.
Velocity Generation JavaBean
First, define a simple bean class
Public classClassbean {PrivateString name; PrivateString Comment; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString getcomment () {returncomment; } Public voidsetcomment (String comment) { This. Comment =comment; }}
Ii. Velocity code for generating JavaBean
Privatevelocityengine init () {Velocityengine ve=NewVelocityengine (); Ve.setproperty (Runtimeconstants.resource_loader,"Classpath"); Ve.setproperty ("Classpath.resource.loader.class", Classpathresourceloader.class. GetName ()); Ve.init (); returnve;}
@Test Public voidvelocity_test_2 () {velocityengine ve=init (); Template T= Ve.gettemplate ("TEMPLATE/CLASSVELOCITY.VM"); Velocitycontext CTX=NewVelocitycontext (); //DataList<classbean> Classbeans =NewArraylist<>(); Classbean ClassBean1=NewClassbean (); Classbean1.setname ("Username"); Classbean1.setcomment ("User Name"); Classbean classBean2=NewClassbean (); Classbean2.setname ("Password"); Classbean2.setcomment (Password); Classbean classBean3=NewClassbean (); Classbean3.setname ("Address"); Classbean3.setcomment (Address); Classbeans.add (CLASSBEAN1); Classbeans.add (CLASSBEAN2); Classbeans.add (CLASSBEAN3); Ctx.put ("ClassName", "person"); Ctx.put ("List", Classbeans); StringWriter SW=NewStringWriter (); T.merge (CTX, SW); System.out.println (Sw.tostring ());}
Third, the contents of CLASSVELOCITY.VM are as follows
# #首字母大写 #macro (inituppercase $field) $field. toUpperCase (). substring (0,1) $field. Substring (1) # # #end Public class$className {#foreach($beaninch$list)PrivateString $bean. GetName ();//$bean. Getcomment ()#end #foreach($beaninch$list) #Set($filed =$bean. GetName ()) PublicStringGet#initUpperCase ($filed) () {return$filed; } Public void Set#initUpperCase ($filed) (String $filed) { This. $filed =$filed; } #end}
Iv. the generated code is as follows:
Public classPerson {PrivateString username;//User name PrivateString password;//Password PrivateString address;//Address PublicString GetUserName () {returnusername; } Public voidSetusername (String username) { This. Username =username; } PublicString GetPassword () {returnpassword; } Public voidSetPassword (String password) { This. Password =password; } PublicString getaddress () {returnaddress; } Public voidsetaddress (String address) { This. Address =address; }}
Friendship Link
- For a basic use of velocity, see blog http://www.cnblogs.com/huhx/p/baseusewebvelocity1.html
Use of the Web base-----> template engine Velocity (ii)