Just discovered from the website, I hope to be useful to everyone. Created: Wang Yi mailing box: javamail@263.netqq number: 179985017Velocity? Velocity is a Java-based template engine (TEMPLATE ENGINE). It allows anyone to simply use the template language (Template language) to reference objects defined by Java code. When Velocity is applied to web development, interface designers can develop a Web site that follows the MVC architecture with Java program developers. That is to say, page designers can only pay attention to the display of the page, but by Java program developers pay attention to business Logic coding. Velocity separated Java code from the web page, which provides a convenient for long-term maintenance of the Web site, and also provides an optional solution for our JSP and PHP. Velocity's ability to develop this area, for example, it can generate SQL and PostScript, XML from template (Template), which can also be used as a stand-alone tool to generate source code and report, or as other system integrated components use. Velocity can also provide template services for Turbine Web Development Architecture (TEMPLATE ". Velocity Turbine provides a template service to allow a web application to develop in a real MVC model. What can Velocity do for us? The Mud Store Example assumes that you are a page designer specially sold by MUD online store, let us call it "Online MUD Store." Your business is very prosperous, our customers have undergone various types and quantities of MUD orders. They are all logged into your website after entering the username and password, and then allow them to view orders and purchase more MUD. Now, a very popular MUD is being discounted. In addition, some customer regular purchase is also a discount but not very popular Bright Red Mud, because there are not many people purchased, it is placed on the edge of the page. All users are tracked and stored in the database, so a certain day has a problem. Why don't you use Velocity to make users better browse the goods they are interested in? Velocity makes it easy to customize the WEB page. As a designer of a web site, you want each user to have its own page when you log in. You will meet some software engineers in some companies, you find that each of them agrees that customers should have personalized information. That let us send the software engineer to the side, look at what you should do. You may be nested in the page with the following VTL declaration:
$ flogger.getPromo ($ MUD) td> tr> # end # end table> Velocity Template Language (VTL): An IntroductionVTL means the easiest, easiest and most tidy Merge page dynamic content. VTL uses References to nested dynamic content in Web Site, and a variable is a type of Reference. Variables are certain types of refreence, which can point to definitions in the Java code, or values from VTL Statement defined within the current page.
Below is an example of VTL Statement, which can be nested into the HTML code: #set ($ a = "velocity"), like all VTL Statement, this Statement starts with # characters and contains a Directive: SET. When an online user requests your page, Velocity Templating Engine will query the entire page to find all # characters, then make sure which is VTL Statement, which does not require VTL to make anything. # When you follow a Directive: Set, this set directive uses an expression (enclosed using parentheses) - a equation assigns a value to the variable. The variable is listed on the left, and its value is listed on the right, and finally they use = number segmentation. In the above example, the variable is $ A, and its value is Velocity. The same start with other References, while the value is always closed by double quotes. Only String in Velocity can be assigned to the variable. Remember the following rules: References starting with $ characters to get what to get; Directives starting with # characters is used to do something. Hello Velocity World! Once a variable is assigned a value, you can reference it anywhere in the HTML file. In the following example, a value is assigned to the $ foo variable and will be referenced thereafter.
#set ($ foo = "velocity") Hello $ foo world! body> html> The implementation result is printed on the page "Hello Velocity World!" in order to make VTL Directives Statement is more readable, we encourage you to start every VTL Statement in the new row, although you don't have to do this. SET DIRECTIVE will be described in detail later. Note: ## this is a single line comment. Multi-line comments: # * thus begins a multi-line comment. Online Visitors Won't See TEXT BECAUSE The Velocity Templating Engine Willignore It. * # Document Format: # * * This is a VTL comment block and may be used to store such informationas the document author and versioning information: @version 5 @author * # references there are three types of references in the VTL: variables (variables), attributes (properties), a method Methods. As a page designer using VTL, you and your engineers must reach a consensus on the name of References so that you can use them in your Template. Everything coming to and from a reason is processed as a String object. If there is an object $ foo is an Integer object, then Velocity will call its toString () method to transform this object to the String type. Variable format requires Java. Attribute example: $ Customer.Address $ Purchase.total $ Customer.Address has two meanings.
It can be represented: Find the value of the HashTable Object Customer in address as the keyword; or the getaddress () method that calls the Customer object. When your page is requested, Velocity will determine the above two ways, and then return the appropriate value. Method A method is to be defined in a piece of code in Java, and it has the ability to complete some useful work, such as whether an execution calculation and judgment conditions are established, satisfying, etc. The method is a References consisting of $ start and following the VTL identifier, typically also includes a VTL method. For example: $ customer.getaddress () $ purchase.gettotal () $ page.settitle ("My Home Page") $ Person.settributes ([Strange "," Weird "," EXCITED "]) First two example $ Customer .Getaddress () and $ purchase.gettotal () look tall to the property $ Customer.Address and $ PURCHASE.TOAL. If you think there is some kind of contact between them, then you are correct. The VTL attribute can be an abbreviation for the VTL method. $ Customer.Address property and use the $ Customer.GetadDress () method have the same effect. If possible, it is reasonable to use properties. The difference between the properties and methods is that you can give a method to specify a list of parameters. The formal Reference Mark Reference is the following: $ {mudslinger} Variable $ {Customer.Address} Attribute $ {purchase.gettotal ()} method is not a common format is more common, but sometimes it is a format. For example: You want to organize a string through a variable $ Vice. Jack is A $ ViceManiac. Original variable is $ VICE now becomes $ ViceManiac, so Veloctiy doesn't know what you want. So, you should use a format Writing Jack is a $ {vice} Maniac now Velocity knows that the variable is $ VICE instead of $ ViceManiac. Quiet Reference NOTATION, for example: When the page is initially loaded, the variable $ Email has no value, then you must hope it can be displayed. A Blank text instead of the output of "$ EMAIL". Then use the Quiet Reference Notation to be appropriate. The initial value of this text box will not be email but null value. The official and quiet format Reference Notation can also be used together, like this: getting litral velocity uses special characters $ and # to help It works, so if you want to use these special characters in Template to be careful. This section will discuss $ characters. The currency characters use $ 2.5 such a currency identifier in VTL, VTL does not miss it, because the Reference in VTL always begins with a uppercase or lowercase. Escaping Valid VTL Reference VTL uses "/" as an escape.
For example: #SET ($ email = "foo") $ EMAIL / $ EMAIL / / $ EMAIL / / / $ EMAIL will be: foo $ email / foo // $ Email If the email variable is not defined $ EMAIL / $ EMAIL / $ Email // $ email /// $ EMAIL will be taken as: $ email / $ email // $ email /// $ email Note: The unfounded variable in VTL will be considered a string, so the following example: #SET ($ foo = "gibbous") $ moon = $ foo output results: $ moon = Gibbouscase Substitution Now you have been familiar with Reference, you can use them to apply them to your Template. Velocity takes advantage of many Java specifications to facilitate the use of designers. For example: $ foo $ foo.getbar () ## is The Same as $ foo.bar $ data.getuser ("jon") ## is The Same as $ data.user ("jon" $ data.getRequest () .getServerName () # is The Same as $ data.request.servername ## is The Same as $ {data.request.serverName} However, notice that the REFERENCE does not interpret the instance variable of the object in VTL. For example: $ foo.name will be interpreted as a GetName () method of the Foo object, not the Name instance variable of the Foo object. DirectiveSReference allows designers to use dynamic content, while Directive makes you applying Java code to control your display logic to achieve the display effect you expect. #Set #set Directive is used to set the value of a Reference. For example: #SET ($ primate = "monkey") #set ($ CUSTOMER.BEHAVIOR = primate) assigning (lhs) on the left side of the value must be a variable or attribute Reference.
The right side (RHS) can be in the following: L Variables Referencel String Literall Properties ReferenceEncel method Referencel Number Litrall ArrayList The following is an example of applying various types of RHS: #SET ($ monkey = $ bill) ## variable refrence # Set ($ monkey.friend = "monica") ## string literal #set ($ monkey.blame = $ whitehouse.leak) ## 属 r rerence #set ($ monkey.plan = $ spindoctor.weave ($ Web)) # # Method Reference #set ($ monkey.number = 123) ## Number Literal #set ($ monkey.say = ["not", $ my, "fault"] ## arraylist Note: Method for the last example For: $ monkey.say.get (0) RHS can also be a simple arithmetic expression: #set ($ value = $ foo 1) #set ($ value = $ bar -1) #set ($ value = $ foo * $ bar) #set ($ value = $ foo / $ bar) If your RHS is a NULL, VTL processing will be special: it will point to a already existing Reference, which may be Comparison. For example: #set ($ resut = $ query.criteria ("name")) The Result of The First Query IS $ Result #set ($ Resut = $ query.criteria ("address") The Result of the second query is $ RESULT If $ query.criteria ("name") returns a "Bill", $ query.criteria ("address") returns NULL, the result of the display is as follows: The Result of the first query is Bill The Result of THE RESUERY IS BILL THE FIRST Query Is Bill Take a look at the example below: #SET ($ criteria = ["name", "address"]) #foreach ($ criterion in $ criteria) #set ($ results = $ query.criteria ($ criterion) ) #IF ($ result) Query Was Successful # end # End In the above example, the program will not be intelligent to determine whether the query is successful according to the value of $. After $ Result (Added to The Context), it cannot be set back to NULL (Removed from the context). The results of printing will show that the results of the query are successful, but there is a query that has failed.
To solve the above problems, we can use pre-defined ways: #set ($ criteria = ["name", "address"] #set ($ result = false) #set ($ results) #set ($ Result = $ query.criteria ($ criterion)) #IF ($ Result) Query Was Successful #end #end string Litrals When you use #set Directive, String Litral is enclosed in a pair of double quotes. #SET ($ DIRECTORYROOT = "WWW") #set ($ templatename = "index.vm") #set ($ template = "$ DIRECTORYROOT / $ TEMPATENAME") $ TEMPLATE The output of this code is: WWW / INDEX .vm However, when String Literal is packaged in single quotation, it will not be parsed: #set ($ foo = "bar") $ foo #set ($ blang = '$ foo') Result: Bar $ foo This feature can change whether the above features are valid by modifying the value of the stringliterals.interpolate = false of the Velocity.Properties file. Conditional Statements If / Elseif / Else When a web page is generated, use Velocity's #if Directr, if the condition is established, you can embed text on the page. For example: #IF ($ foo) velocity! Strong> #END The condition statement in the previous example will be established in the following two conditions: l $ foo is a Boolean type variable, and its value is Truel The value of the $ foo variable is not NULL. You need to note: Velocity Context can only contain objects, so when we say "Boolean" actually represents a Boolean object. Even if a method returns a boolean value, Velocity will use the internal provincial mechanism to convert it to a Boolean. If the condition is established, the content between #IF and #end will be displayed. #ELSEIF and #ELSE elements can be used with #if. For example: #if ($ foo <10) Go north strong> #elseif ($ foo == 10) Go East strong> #elseif ($ foo == 6) Go South strong> #else Go West strong> #end Note The number of Velocity here is compared to Integer - Other types of objects will make the condition false, but it is different from Java. "= = "To compare two values, and Velocity requires the same type of value on both sides. Relationship, logical operator Velocity uses an equal signage to determine the relationship between the two variables.
For example: #SET ($ foo = "deoxyribonucleic acid") #set ($ bar = "ribonucleic acid") #if ($ foo == $ foo) in this case it's clear the aren't equivalent.so ... # else they Are Not Equivalent and this will be the output. # endVelocity has an AND, OR and NOT logic operators. Here are some examples: ## logical and bar this and that strong> #end ## logical or #if ($ foo || $ bar) this or what strong> #end ## logical not #if (! $ foo) not that strong> #end loop Foreach loop example:
#foreach ($ Product in $ allproducts)
$ product li> #end ul> A value in a loop $ allProducts will assign a product variable. $ allProducts can be a vector, havehtable or array. The value assigned to the $ produter is a Java object and can be referenced by variables. For example: If $ product is a Java's Product class, and the name of this product can be obtained by calling his getName () method. Now we assume $ allproducts to be a HashTable, if you want to get it, Key should be like this:
#foreach ($ key in $ allproducts.keyset ())
KEY: $ KEY -> Value: $ allproducts .get ($ key) li> #end ul> Velocity also provides a method of getting a number of cycles so that you can do this like this:
#foreach ($ Customer In $ Customerlist)
$ VELOCITYCOUNT TD>
$ Customer.Name td> tr> #end table> $ velocityCount variable name is Velocity default name, you can also modify the velocity.properties file To change it. By default, the count starts from "1", but you can set it from "1" or from "0" at Velocity.properties. The following is the configuration file: # Default name of loop counter # variable reference directive.foreach.counter.name = velocityCount # Default starting value of the loop # counter variable reference directive.foreach.counter.initial.value = 1include # include script ELEMENT allows template designers to introduce local files.
The content that is introduced into the file will not be rented by the template engine. For security reasons, the introduced local file can only be in the template_root directory. #included ("one.txt") If you need to introduce multiple files, you can separate it by comma: #include ("one.gif", "two.txt", "three.htm") can be files in parentheses Name, but more time is using variables: #inclue ("Greetings.txt", $ SeasonalStock) Parse # Parse Script Element allows template designers a local file containing VTL. Velocity will resolve the VTL and the Render template. #Parse ("me.vm") is like # include, # parse accepts a variable instead of a template. Any template pointed to by #PARS must be included in the template_root directory. Different from #include, # Parse can only specify a single object. You can control the number of Template's maximum #PARSE-default value by modifying the value of the velocity.properties file PARSE_DIRECIVE.MAXDEPTH - the default value is 10. #parse is a recursive call, for example, if Dofoo.vm contains downlight: count down. #set ($ count = 8) #PARSE ("Parsefoo.vm") All done with dofoo.vm! So in Parsefoo.vm In the template, you can include the following VTL: $ count #set ($ count = $ count - 1) #if ($ count> 0) #parse ("Parsefoo.vm") #ELSE All Done with parsefoo.vm! #End The display result is: Count Down. 8 7 6 5 4 3 2 1 0 All done with parsefoo.vm! All done with Dofoo.vm! Stop # stop script element allows the template designer to stop executing the template engine and returns. It is very helpful to apply it to Debug. # Stopvelocros # Macro Script Element allows template designers to define a reusable VTL Template. For example: #macro (d)
TD> tr> #end in the example above, VelociMacro is defined as d, then you can call it in any VTL Directive: # d () When your template is called, Velocity will replace with
td> tr> to #d (). Each VelocimaCro can have any number of parameters - or even 0 parameters, although the number of parameters can be set at will, but the correct parameters must be specified when calling this VelociMacro.
Below is a VelociMacro with two parameters. One parameter is the other parameter is Array: #macro (TableRows $ SOMELIST) #foreach ($ something in $ somelist)
#tableRows ($ color $ greatlakes) table> After the above call will produce the following display results:
superior td> < / TR>
MICHIGAN TD> Tr>
Huron TD> TR>
Erie TD> tr>
Ontario TD> tr> table> VelociMacros can implement line definitions within the Velocity template, It means that other Velocity templates in the same web site cannot get the definition of VelocimaS. Define a VelociMacro that can be shared by all templates. It is obviously a lot of benefits: it reduces the number of repetitions defined in a large heap template, saving working hours, reducing the chances of error, ensuring single modification. The #tableROWS ($ Color $ LIST) VelociMacro defined above is defined in a VelocimaS template library (defined in velocity.properties), so this MacRo can be called in any specification template. It can be applied multiple times and can be applied to different purposes.
For example, the following calls: #SET ($ parts = ["Volva", "Stipe", "Annulus", "Gills", "Pileus"]) #set ($ Cellbgcol = "# cc00ff")
#tableROWS $ Cellbgcol $ Parts) table> The above VTL will produce the following output:
Volva td tr>
Stipe td tr>
Annulus td tr>
Gills td tr>
Pileus TD TR> table> VelociMacro Arguments Velocro You can use any of the following elements as parameters: l Reference: Any Referencel String Litral: l Number Litral with $ : L IntegerRange: [1 ... .3] or [$ FOO ... $ bar] l object array: [A "," B "," C "] l Boolean Value: true, false When a Reference is passed as parameters When you give Velocimacro, note that Reference is passed as a parameter. This means that the value of the parameters will be generated when executed within each Velocimacro. This feature allows you to pass a method call as a parameter to VelociMacro, and each VelociMacro is executed by this method call to generate different values. For example: #macro (Callme $ a) $ A $ A #end #callme ($ foo.bar ()) The result is: The bar () method of the Reference $ FOO is executed three times. If you don't need this feature, you can pass the following methods: #set ($ myval = $.bar ()) #callme ($ myval) VelociMacro Properties Velocity.properties files can make VelocimaS's implementation more flexible. Note that more content can see developer guide. VelociMacro.Libraary in a Velocity.properties file: a list of comma-separated template libraries. By default, Velocity looks for a single library: VM_GLOBAL_LIBRARY.VM. You can specify your template library by configuring this property. VelociMacro.Permissions.Allow.inline attribute in the Velocity.properties file: There are two optional value true or false, which can determine if VelociMacros can be defined within Regular Template. The default is TURE - allowing designers to define VelocimaS in their own templates.
VelociMacro.Permissions.Allow.inline.Replace.global attributes in the velocity.properties file There are two optional values true and false. This property allows the user to determine if the VelocRo definition of Inline can replace the global VelocroRO definition (such as in VelociMacro.library VelociMacro defined in the file specified in the property. By default, this value is false. This prevents the local VelociMacro definition override global definition. VelociMacro.Permissions.Allow.inline.Local.scale properties in the velocity.properties file also have both TRUE and FALSE two optional values, default False. Its role is to determine if the VelociMacros defined by your inline is only visible in the defined template. In other words, if this property is set to True, a Inline defined VelocimaS can only be used within the Template defined. You can use this setting to implement a wonderful VM knock: a Template CAN define a private implementation of the second vm what will be called by the first vm when invoked by That Template. All Templates Are UnAffected. VelociMacro.Context.localscro.Context.localscope attribute in the velocity.properties file has two optional values of true and false, the default value of false. When set to TRUE, any modification of CONTET () in VelociMacro is considered to be a local setting for this VelocimaCro without permanent impact. The VelociMacro.Library.AutoreLoad property in the velocity.properties file controls the automatic load of the VelocimaCro library. The default is False. When set to TURE, the call to a VelociMacro will automatically check if the original library changes, and if the change will reload it. This property allows you to reach the reloaded effect without restarting the servlet container, just like you use the Regular template. The premise of this attribute is that the Resource Loader cache is OFF state (file.Resource.Loader.cache = false). Note that this property is actually for development instead of product. Velocimracro Trivia VelociMacro must be defined before they are used. That is, your #macro () statement should appear before using VelocimaS. It is important to note that if you try to #parse () a template containing #macro (). Because #parse () occurs during the runtime, but the parser determines whether the element of the VM element is a VM element in Parsetiem, such #parse () - ING a set of VM declarations will not work according to the expected look. In order to get the expected result, you only need to use VelociMacro.Library to make Velocity load your VMS at startup. Escaping VTL DirectiveSvtl Directives Can Be Escaped with "/", usage method with VTL's Reference uses the format of escape characters.
## #include ("a.txt") Renders as (Note) #include ("a.txt") ## / # include ("a.txt") Renders as / # include ("A.txt") / # include ("a.txt") ## // # include ("a.txt") Renders as / // # include ("a.txt" ) At particular careful when using VTL Directives that contains multiple Script elements in a Directive (such as within an IF-Else-End Statement). Below is a typical application of VTL's if-statement: #if ($ JAZZ) Vyacheslav Ganelin #end If $ JAZZ is TURE, the output will be: Vyacheslav Ganelin If $ jazz is false, there will be no output. Use escapes will change the output. Consider the following situation: / # i ($ jazz) Vyacheslav Ganelin / # END No matter whether $ jazz is true or false, the output is: #if ($ jazz) Vyacheslav Ganelin #END in fact, because you use escape The value, $ JAZZ is not parsed to the Boolean value. Using escape before escape, it is legal, for example: // # if ($ jazz) Vyacheslav Ganelin /// END The display result of the above program is: / Vyacheslav Ganelin / But if $ jazz is false, then there will be no output. (The book says there will be no output, but I think there should be "/" characters to be output.) VTL: Formatting Issues Although VTL usually starts a new line, as follows: #set ($ imperial = ["MUNETAKA", "Koreyasu", "Hisakira", "Morikune"]) #foreach ($ SHOGUN IMPERIAL) $ SHOGUN #END But it is also possible like this: Send me #set ($ foo = ["$ 10 and", "a cake"]) # foreach ($ a in $ foo) $ A #END PLEASE. The above code can be rewritten as: Send Me #set ($ foo = ["$ 10 and", " a cake "]) #foreach ($ a in $ foo) $ A #nd ple #set ($ foo = [" $ 10 and "," a cake "]) #foreach ($ a in $ foo) $ A #END PLEASE. These two output structures will be the same. Other features and miscellaneous MATH can use Velocity built-in arithmetic functions in templates, such as: add, minus, multiply, except #set ($ foo = $ bar 3) #set ($ foo = $ bar - 4) #set ($ foo = $ bar * 6) #set ($ foo = $ bar / 2) The result of an Integer type will be returned when the division is performed.
And you can use% to get: #set ($ foo = $ bar% 5) When using mathematical calculation formulas in Velocity, you can only use the like-N, -2, -1, 0, 1, 2, n. Integers, not other types of data. When a non-integer object is used, it will be logged and will use NULL as the output result. The Range OperatorRange Operator can be used in combination with #set and #foreach statement. It is useful for processing a integer array, and the Range Operator has the following configuration: [n..m] M and N must be intellectual, and whether M is greater than n. Example: First Example: #foreach ($ foo in [1..5]) $ foo #end second example: #foreach ($ BAR IN [2 ..- 2]) $ bar #end third example: #set ($ Arr = [0..1]) #Foreach ($ I IN $ ARR) $ I #end fours EXAMPLE: [1..3] The output result of the above four examples is: First Example: 1 2 3 4 5 SECOND EXAMPLE : 2 1 0 -1 -2 Third Example: 0 1 FOURTH EXAMPLE: [1..3] Note: Range Operator is only valid in #SET and #Foreach. Advanced Issue: escaping and! When a Reference is "!", The Reference will handle in a special manner when there is an escape in it. Note that this approach is different from the standard escape method. The contrast is as follows: #SET ($ foo = "bar") Special form Standard format render before render before render before render $ /! Foo $! Foo / $ foo / $ foo $ /! {Foo} $! {Foo} / $! foo / $! foo $ //! foo $ /! foo / $! {foo} / $! {foo} $ ///! foo $ //! foo // $! {foo} / barvelociMacro miscellaneous CAN I User A Directive or Another VM AS An Argument TO A VM? For example: #Center (#bold ("Hello")). A Directive parameter uses another Directive if it is not legal. But it is still something you can do. The simplest way is to use double quotes: #set ($ stuff = "#bold ('Hello')") #Center ($ stuff) above formats can also be abbreviated as a line: #Center ("#bold ('Hello' )) Please note that the parameters in the examples below are inside the VelociMacro instead of Calling Level.