SlideShare uma empresa Scribd logo
1 de 47
An Introduction to
Apache Velocity 1.6
      Henning Schmiedehausen
       henning@apache.org

 ApacheCon 2009, Oakland, CA, U.S.A.
Templating Engine?
•   Uses a simple language
    (Velocity Templating Language = VTL)


•   Templates are text which
    contains active elements

•   Active elements are
    replaced with values from
    the Model

•   No "industry standard"
    templating language

•   Templates are processed,
    not compiled
Templating engines
•   perl
    •   HTML-Template, Mason
•   PHP
    •   Smarty, SmartTemplate, TinyButStrong
•   Ruby
    •   Galena, LiquidMarkup, ERB, lots more
•   Python
    •   QuickSilver, Cheetah, TurboGears, Airspeed
•   Java
    •   WebMacro, StringTemplate, FreeMarker,
        Apache Velocity


                                         ApacheCon US 2009
A short history of Velocity
• Started in 2000
• One of the first Apache Jakarta projects
• ASF-licensed alternative to WebMacro
• Language syntax similar and very stable
• 100% pure Java, runs on Java 1.3 or better
• Apache TLP since 2006, from Jakarta
• Current release: 1.6.2 (March '09)
                           ApacheCon US 2009
Velocity Spotting
•   Velocity is integrated in many other Apache projects
    •   Web Frameworks: Click, Wicket, Struts, Turbine
    •   Other projects: Maven, Camel, Portals, Tiles
                                http://wiki.apache.org/velocity/PoweredByVelocity


•   Support for IDEs and Editors available
    (e.g. Eclipse, IntelliJ, emacs...)
                                 http://wiki.apache.org/velocity/VelocityEditors


•   View Component in Web Frameworks
•   Code Generation (Apache Torque, Eclipse)
•   Documentation Generation (Maven, Anakia, Texen)
•   E-Mail Templating (e.g. Spring Framework)

                                          ApacheCon US 2009
Velocity vs. JSP
• Easier to test
• No servlet container required
• Better separation of Code and Design
• No compilation into Java code
• Few, easy to learn language elements
• No embedded Java code!
• better read- and understandable
                          ApacheCon US 2009
Template Example
<div>${addr.title} ${addr.first} ${addr.last}</div>
<div>${addr.street}</div>
<div>${addr.town} ${addr.zip}, ${addr.state}</div>
<b>Invoice</b>
<div>Date: $format.date(${time.currDate})</div>
<table>
<tr><th>Pos</th><th>Description</th><th>Price</th>
<th>Qty</th><th>Total</th></tr>
#foreach($item in $invoice.items)
 <tr><td>$velocityCount</td><td>$item.desc</td>
     <td>$format.money($item.price)</td><td>$item.quantity</td>
     <td>$format.money($item.total)</td></tr>
#end
</table>
<div>Total $format.money($invoice.total)</div>
<div>Tax $format.money($invoice.tax)</div>


                                     ApacheCon US 2009
Template Result
Mr John Doe
1234 Evergreen Terrace
Springfield, 12345, AY
Invoice
Date: Nov 3rd, 2009

 Pos     Description      Price      Qty    Total

  1        TV Set        $499.95      1    $499.95

  2    BluRay Player     $299.95      1    $299.95
       Various BluRay
  3                       $9.95       5    $49.95
            Titles

Total $849.97
Tax $49.90


                                   ApacheCon US 2009
Template deciphered
<div>${addr.title} ${addr.first} ${addr.last}</div>
<div>${addr.street}</div>
<div>${addr.town} ${addr.zip}, ${addr.state}</div>
<b>Invoice</b>
   A "con $format.date(${time.currDate})</div>
<div>Date:xt
         te o
                  bject"
                          contai
<table>           getter          ns the
                         s for t          a
                                 he fiel ddress. It h
<tr><th>Pos</th><th>Description</th><th>Price</th>
    getTit
           le(), g                      ds:          as
<th>Qty</th><th>Total</th></tr>
                   etFirst
#foreach($item n(), (), getLast(),
         getTo in $invoice.items)
                  w      getZip           g
                                 (), get etStreet(),
 <tr><td>$velocityCount</td><td>$item.desc</td>
                                        State()
     <td>$format.money($item.price)</td><td>$item.quantity</td>
     <td>$format.money($item.total)</td></tr>
#end
</table>
<div>Total $format.money($invoice.total)</div>
<div>Tax $format.money($invoice.tax)</div>


                                     ApacheCon US 2009
Template deciphered
                              A ${addr.last}</div>
<div>${addr.title} ${addr.first} nother c
                             forma       ontex
<div>${addr.street}</div>          tters f      t obje
                                           or dat      ct con
<div>${addr.town} ${addr.zip}, ${addr.state}</div>e and       tains
                            Such a                       curren
                                   n obje                       cy.
<b>Invoice</b>                             ct is c
                                                   alled a
<div>Date: $format.date(${time.currDate})</div>            "Tool"
                                                                  .
<table>
<tr><th>Pos</th><th>Description</th><th>Price</th>
<th>Qty</th><th>Total</th></tr>
#foreach($item in $invoice.items)
 <tr><td>$velocityCount</td><td>$item.desc</td>
     <td>$format.money($item.price)</td><td>$item.quantity</td>
     <td>$format.money($item.total)</td></tr>
#end
</table>
<div>Total $format.money($invoice.total)</div>
<div>Tax $format.money($invoice.tax)</div>


                                          ApacheCon US 2009
Template deciphered
<div>${addr.title} ${addr.first} ${addr.last}</div>
<div>${addr.street}</div>
<div>${addr.town} ${addr.zip}, ${addr.state}</div>
                        The "i
                               n
                      iterab voice" obje
<b>Invoice</b>              le field          ct con
                        loop c      . The           tains a
                                           #forea
<div>Date: $format.date(${time.currDate})</div>
                               reates                         n
                                       the ite     ch...#e
                                               mized         nd
<table>                                                list.
<tr><th>Pos</th><th>Description</th><th>Price</th>
<th>Qty</th><th>Total</th></tr>
#foreach($item in $invoice.items)
 <tr><td>$velocityCount</td><td>$item.desc</td>
                             Fun fa
     <td>$format.money($item.price)</td><td>$item.quantity</td>
                                    ct: Vel
                             conve          o
                                   nient city p
     <td>$format.money($item.total)</td></tr> rovid
                                                           es a
                                          count
#end                                              for loo
                                                           ps!
</table>
<div>Total $format.money($invoice.total)</div>
<div>Tax $format.money($invoice.tax)</div>


                                     ApacheCon US 2009
Template deciphered
<div>${addr.title} ${addr.first} ${addr.last}</div>
<div>${addr.street}</div>
                             Th ${addr.state}</div>
<div>${addr.town} ${addr.zip}, e rema
                               This c inder is just
                                     an be
<b>Invoice</b>
                                  HTML     any ki formatted t
                                                 n
<div>Date: $format.date(${time.currDate})</div> d of text
                                        , XML                 ext.
                                              or pla        ,
                                                     in tex e.g.
<table>                                                    t.
<tr><th>Pos</th><th>Description</th><th>Price</th>
<th>Qty</th><th>Total</th></tr>
#foreach($item in $invoice.items)
 <tr><td>$velocityCount</td><td>$item.desc</td>
     <td>$format.money($item.price)</td><td>$item.quantity</td>
     <td>$format.money($item.total)</td></tr>
#end
</table>
<div>Total $format.money($invoice.total)</div>
<div>Tax $format.money($invoice.tax)</div>


                                       ApacheCon US 2009
Velocity Template Language
• Simple Constructs
 • #directive() - line directives
 • #directive() ... #end - block directives
 • $reference or ${reference} - references
• Embedded directly into template files
  (no open or close tags like php or JSP)
• References are "loosely typed"
                            ApacheCon US 2009
Assignments - #set()
•   #set creates or updates a reference
    •   #set( $foo = “text” )        String value
    •   #set( $foo = 100 )            Numeric value
    •   #set( $foo = [ 1, 2, 3 ] )   Array
    •   #set( $foo = { 1 : 2, 3 : 4 } ) Map
    •   #set( $foo = $bar )           Reference
    •   #set( $foo = $bar.foo )       Bean getter
    •   #set( $bar.foo = "200" )      Bean setter
    •   #set( $foo = $bar.doFoo() ) Method Result

                                        ApacheCon US 2009
Demo #1 - References

#set( $message = 'Hello World' )
This is a Velocity "$message" program.
#set( $favorite = 137 )
My favorite number is not ${favorite}.




                          ApacheCon US 2009
Control structures
• Loop
 • #foreach( $foo in $bars ) ... #end
 • loops can be terminated with #break
 • $velocityCount provides loop count
 • $velocityHasNext allows "peeking ahead"
• Conditional
 • #if ( ) … #elseif ( ) … #else … #end
                          ApacheCon US 2009
Control structures
• Inclusion of external elements
 • #include() Load external file
 • #parse() Load and parse file
• Turn VTL blocks into references
 • #define(name) ... #end
• Evaluate templates on the fly
 • #evaluate(...)
                          ApacheCon US 2009
Demo #2 - Loops

#set( $list = [ 'a ', ' b ', ' c ', ' d ' ] )
#foreach( $alpha in $list )
 The current letter is ${alpha}.
                    Hint: O
                            pening
#end                  a bloc
                             k can
                                   and cl
                                          osing
                                   be on        el
                                         the sa ement of
                                                me lin
Let’s count:     #foreach( $i in [ 1..10 ] )$i #end    e!




                                      ApacheCon US 2009
Demo #3 - Conditionals
#if( $lang eq "DE" ) ##Use german
 Hallo Welt!
#elseif( $lang eq "FR" )
 Bonjour Monde!
#else #*Use default greeting*#
 Hello World!
#end



                           ApacheCon US 2009
Bonus Slide: Comment Syntax
       #if( $lang eq "DE" ) ##Use german
         Hallo Welt!
       #elseif( $lang eq "FR" )
         Bonjour Monde!
       #else #*Use default greeting*#
        ThHello World!
          is is th
                   e Velo
                         city co
## com                           mmen
          ments
         #end to the                   t synta
#* ....                                         x:
        *# enc            end of
               loses             the lin
                      a mult             e,
                             iline c
                                     omme
                                            nt.


                                                     ApacheCon US 2009
Macros

• Builds a block directive on the fly
• Create: #macro (name) … #end
• Use: #name() … #end
• global and local scope supported
• Technically some sort of “method call”
                      (please don’t use it like this)


• factor out common template code/content
                           ApacheCon US 2009
Macros
• Macros can take parameters
• Create: #macro( name $arg1 $arg2 )
           … $arg1 … $arg2 …
         #end
• Use: #name( $foo $bar ) … #end
• Arbitrary number of parameters possible
• Number of call parameters must match
  definition!

                          ApacheCon US 2009
Demo #4: Macros

#macro( quote $value )
  &quot;$value&quot;
#end
A macro quotes #quote( 'this phrase' )!

Result:
A macro quotes &quot;this phrase&quot;!




                          ApacheCon US 2009
Reference Syntax & Evaluation

• Any reference represents a Java object
• Use ${reference} to avoid parsing
  ambiguities
• If a reference resolves to "null", the
  reference itself is inserted in the template
• $!ref or $!{ref} means "be quiet when null"
• Evaluation uses toString() method
                             ApacheCon US 2009
Reference Syntax & Evaluation

• Any reference represents a Java object
• Use ${reference} to avoid parsing
  ambiguities
• If a reference resolves to "null", the
                             Yeah,
                                     that w
                                           as a s
  reference itself is inserted in the template    tupid
                                                        idea.


• $!ref or $!{ref} means "be quiet when null"
• Evaluation uses toString() method
                             ApacheCon US 2009
Reference Syntax & Evaluation

• Any reference represents a Java object
• Use ${reference} to avoid parsing
  ambiguities
• If a reference resolves to "null", the
  reference itself is inserted in the template
• $!ref or $!{ref} means "be quiet when null"
• Evaluation uses toString() method
                             ApacheCon US 2009
Reference Syntax & Evaluation

• Any reference represents a Java object
• Use ${reference} to avoid parsing
   Trivia:
            C
  an end onfusing $
           less so        !{foo}
                   urce o         with !$
  ambiguities
 Also !$
         !{foo}
                           f fun!         {foo} c
                                                  an be
 and in          lo
        credib oks awkwa
• If a reference resolves to "null", the
                ly use
                       ful.
                                rd but
                                        is vali
                                                d VTL
  reference itself is inserted in the template
• $!ref or $!{ref} means "be quiet when null"
• Evaluation uses toString() method
                                               ApacheCon US 2009
Velocity Operators

• Arithmetic operators
 • #set ($foo = 5 / 2 ) ## is 2!
    #set ($foo = 5.0 / 2) ## is 2.5
  • The usual suspects: +, -, /, *, %
• Range Operator
 • #set ($numbers = [ 1..100 ])
    creates a list of integers from 1 to 100

                              ApacheCon US 2009
Velocity Operators
                   Fun fa
                  suppo
                          ct: Sin
                                 ce Ver
                         rts all         si
                  arithm         numb on 1.5, Velo
                                        er typ
                         etics w
                                  as inte      es. Be city

• Arithmetic operators                    ger on     fore, a
                                                 ly.         ll



 • #set ($foo = 5 / 2 ) ## is 2!
    #set ($foo = 5.0 / 2) ## is 2.5
  • The usual suspects: +, -, /, *, %
• Range Operator
 • #set ($numbers = [ 1..100 ])
    creates a list of integers from 1 to 100

                                    ApacheCon US 2009
Misc.Velocity

• Boolean operators for conditionals
 • !, &&, ||, ==, <=, <, >, >=
 • not, and, or, eq, ne, gt, ge, lt, le for
     convenience in e.g. XML templates
• For == and !=, if the operands are not of
   the same class, their toString() values are
   compared


                               ApacheCon US 2009
Velocity Strings
•   String interpolation for #set(),
    macro args and method args:
    •   #set( $foo = 3.5 )
        #set( $foo = "Value was $foo" )

        $foo is now "Value was 3.5"
•   Force a reference to be a String:
    •   #set ($foo = "$foo")
•   Use ' to avoid interpolation:
    •   #set ($foo = '$foo')

                                      ApacheCon US 2009
Velocity Context
• Context objects are accessible in templates
• Map of names (${foo}) to arbitrary objects
• Templates can only access what is in the
  context
• There is no way to create Java objects
  except through context elements
• Velocity can restrict which methods and
  fields on a context object are available

                           ApacheCon US 2009
Velocity Context Example
public static void main(String [] args)
 throws Exceptions{cre
                 Thi
                      ates $
                             {user}
                                    and $
 VelocityContext                          {cliche
                  context = new VelocityContext();
                                                 }
 context.put("user", "Velocity User");
 context.put("cliche", "Hello World!");
 VelocityEngine engine = new VelocityEngine();
 Template template = engine.getTemplate(args[0]);
 Writer out = new OutputStreamWriter(System.out);
 template.merge(context, out);
 out.flush();
}


                                 ApacheCon US 2009
Velocity Context Template


#if ($!{user})
 Hello, ${user}!
#end
Here is a cliche: ${cliche}




                              ApacheCon US 2009
Velocity Context Template
   $!{use
          r}  is a
   eleme           n
         nt in t ifty way to
                 he con        test w
                       text e          hether
                              xists a
                                      nd is n the user
                                             on-nu
                                                   ll.

#if ($!{user})
 Hello, ${user}!
#end
Here is a cliche: ${cliche}




                                         ApacheCon US 2009
Velocity Context Result



Hello, Velocity User!


Here is a cliche: Hello, World!




                           ApacheCon US 2009
Interaction with the Context
•   The real power of Velocity
•   Uses runtime reflection
•   All public methods in public classes are
    available
•   Shortcut notation for property access
    ($a.b vs $a.getB())
•   Type promotion as Java does
•   Method parameters can not be omitted!
                                      (this is not perl!)


                                 ApacheCon US 2009
Interaction with the Context
 Trivia:
             •   The real power of Velocity

Also, u
         p
             •
anoth ublic meth
       er gre    Uses runtime reflection
                       o
              at way ds in publi
                      to spe        c
        sing in              nd ho classes! Ign
             •  ner cla
                 All public methods in public classes are
                        sses c     urs de
                               an be
                                                   o
                                          buggi ring this is
                                     icky. T      ng!
                 available                   ry to a
                                                     void it
                                                             .

             •   Shortcut notation for property access
                 ($a.b vs $a.getB())
             •   Type promotion as Java does
             •   Method parameters can not be omitted!
                                                                 (this is not perl!)


                                                          ApacheCon US 2009
Velocity Tools
•   A "tool" is a context object that exposes useful
    methods to a template,
    e.g date formatting or localization
•   A "toolbox" is a collection of useful Java classes
•   The Velocity Tools sub-project offers:
    •   GenericTools      All-purpose tools
    •   VelocityView      Webapp centric tools
    •   VelocityStruts    Velocity as Struts 1.x View
•   Other toolboxes on the web

                                  ApacheCon US 2009
VelocityViewServlet
• VelocityViewServlet renders arbitrary
  Templates through web.xml mapping
• XML config file to define tools
• Different tool scopes/lifecycles:
 • application, session, request
• Request, Response, Session and
  ServletContext objects are exposed to
  templates

                            ApacheCon US 2009
Demo #5:VelocityView
•   Uses VelocityTools 2.0
    (beta4 is the current release)
•   VelocityViewServlet does the work
•   Uses LinkTool, ParameterTool, EscapeTool
    •   ($link, $params, and $esc)
•   A custom tool: AddressBook is a ~30 line POJO
•   Only one template: index.vm (~50 lines)
•   ~20 lines of config (including web.xml)

                                     ApacheCon US 2009
Advanced Velocity
•   Custom directives can be created and
    integrated in the Velocity parser
    (org.apache.velocity.runtime.directive.Directive)
•   Multiple Resource loaders to load templates
    from different sources
    (files, classpath, jars, database, remote URLs)
•   Event Handlers for Exception handling, XML
    escaping, etc.
•   Introspector for method and property access
    can be customized or replaced with user code

                                   ApacheCon US 2009
Hacking Velocity


• Velocity Template Language (VTL) is defined
  in JavaCC grammar
• VTL itself can be changed or extended
                      (requires recompilation of velocity.jar)


• More “Advanced Velocity“ at http://
  wiki.apache.org/velocity/HackingVelocity



                               ApacheCon US 2009
Other Velocity uses
• Velocity Subprojects
 • Texen for generic text generation
 • Anakia for XML to documentation
• Apache Torque – generates Java and SQL
  code from templates
• VelocityViewTag – Embed Velocity in JSP
• Velosurf – Generate SQL Web Views
                           ApacheCon US 2009
Questions?
Where to go from here
• Velocity Web Site
  • http://velocity.apache.org/
• Velocity Mailing Lists
  • http://velocity.apache.org/contact.html
• Velocity Wiki
  • http://wiki.apache.org/velocity/
• Slides at the US ApacheCon 2009 web site
  and on slideshare.net

                           ApacheCon US 2009
Thanks for your
interest in Velocity!

Mais conteúdo relacionado

Mais procurados

Sas macros part 4.1
Sas macros part 4.1Sas macros part 4.1
Sas macros part 4.1
venkatam
 

Mais procurados (20)

Sql dml & tcl 2
Sql   dml & tcl 2Sql   dml & tcl 2
Sql dml & tcl 2
 
Unit 4 external sorting
Unit 4   external sortingUnit 4   external sorting
Unit 4 external sorting
 
Html ppt
Html pptHtml ppt
Html ppt
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Data Match Merging in SAS
Data Match Merging in SASData Match Merging in SAS
Data Match Merging in SAS
 
MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTML
 
Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...
Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...
Concept of Structured Query Language (SQL) in SQL server as well as MySql. BB...
 
Web development Training in Ambala ! Batra Computer Centre
Web development Training in Ambala ! Batra Computer CentreWeb development Training in Ambala ! Batra Computer Centre
Web development Training in Ambala ! Batra Computer Centre
 
LIST IN PYTHON
LIST IN PYTHONLIST IN PYTHON
LIST IN PYTHON
 
Web design - Working with tables in HTML
Web design - Working with tables in HTMLWeb design - Working with tables in HTML
Web design - Working with tables in HTML
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Odata
OdataOdata
Odata
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
 
XML
XMLXML
XML
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
 
Html 5 tags
Html  5 tagsHtml  5 tags
Html 5 tags
 
Sas macros part 4.1
Sas macros part 4.1Sas macros part 4.1
Sas macros part 4.1
 

Destaque

E marketer mobile_display_advertising-aspirations_revelations_and_frustrations
E marketer mobile_display_advertising-aspirations_revelations_and_frustrationsE marketer mobile_display_advertising-aspirations_revelations_and_frustrations
E marketer mobile_display_advertising-aspirations_revelations_and_frustrations
AdCMO
 
Folleto School Travel Soluciones Para Grupos
Folleto School Travel Soluciones Para GruposFolleto School Travel Soluciones Para Grupos
Folleto School Travel Soluciones Para Grupos
ASTEX
 
2010 Potential China Pe Investment Themes Updated Aug
2010 Potential China Pe Investment Themes Updated Aug2010 Potential China Pe Investment Themes Updated Aug
2010 Potential China Pe Investment Themes Updated Aug
KC Yoon
 
Presentación1 juan angel
Presentación1 juan angelPresentación1 juan angel
Presentación1 juan angel
FYR2000
 
Regala una experiencia de golden gift
Regala una experiencia de golden giftRegala una experiencia de golden gift
Regala una experiencia de golden gift
senaespecializaciongp
 
FIND OTHER HEALTH LAWYERSpdf
FIND OTHER HEALTH LAWYERSpdfFIND OTHER HEALTH LAWYERSpdf
FIND OTHER HEALTH LAWYERSpdf
Rashid Rashid
 
Alimentos funcionales presentacion
Alimentos funcionales presentacionAlimentos funcionales presentacion
Alimentos funcionales presentacion
Mauro Orna Gamboa
 

Destaque (20)

Velocity tips and tricks
Velocity tips and tricksVelocity tips and tricks
Velocity tips and tricks
 
Cv Eg Nicolo 3
Cv Eg Nicolo 3Cv Eg Nicolo 3
Cv Eg Nicolo 3
 
New york
New yorkNew york
New york
 
Evaluacion 3
Evaluacion 3Evaluacion 3
Evaluacion 3
 
E marketer mobile_display_advertising-aspirations_revelations_and_frustrations
E marketer mobile_display_advertising-aspirations_revelations_and_frustrationsE marketer mobile_display_advertising-aspirations_revelations_and_frustrations
E marketer mobile_display_advertising-aspirations_revelations_and_frustrations
 
Folleto School Travel Soluciones Para Grupos
Folleto School Travel Soluciones Para GruposFolleto School Travel Soluciones Para Grupos
Folleto School Travel Soluciones Para Grupos
 
Rules of business amended 16th august, 2012
Rules of business amended 16th august, 2012Rules of business amended 16th august, 2012
Rules of business amended 16th august, 2012
 
2010 Potential China Pe Investment Themes Updated Aug
2010 Potential China Pe Investment Themes Updated Aug2010 Potential China Pe Investment Themes Updated Aug
2010 Potential China Pe Investment Themes Updated Aug
 
Presentación1 juan angel
Presentación1 juan angelPresentación1 juan angel
Presentación1 juan angel
 
Regala una experiencia de golden gift
Regala una experiencia de golden giftRegala una experiencia de golden gift
Regala una experiencia de golden gift
 
Higiene industrial
Higiene industrialHigiene industrial
Higiene industrial
 
Innovación 101: Innovación para empresarios que no tienen tiempo.
Innovación 101: Innovación para empresarios que no tienen tiempo.Innovación 101: Innovación para empresarios que no tienen tiempo.
Innovación 101: Innovación para empresarios que no tienen tiempo.
 
FIND OTHER HEALTH LAWYERSpdf
FIND OTHER HEALTH LAWYERSpdfFIND OTHER HEALTH LAWYERSpdf
FIND OTHER HEALTH LAWYERSpdf
 
GENERALIDADES DE AuUTOESTIMA
GENERALIDADES DE AuUTOESTIMAGENERALIDADES DE AuUTOESTIMA
GENERALIDADES DE AuUTOESTIMA
 
Trias - yearly report 2014
Trias - yearly report 2014Trias - yearly report 2014
Trias - yearly report 2014
 
Near Eastside Neighborhood Summit - December 12, 2013
Near Eastside Neighborhood Summit - December 12, 2013Near Eastside Neighborhood Summit - December 12, 2013
Near Eastside Neighborhood Summit - December 12, 2013
 
El placer de escribir.
El placer de escribir.El placer de escribir.
El placer de escribir.
 
Alimentos funcionales presentacion
Alimentos funcionales presentacionAlimentos funcionales presentacion
Alimentos funcionales presentacion
 
Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...
Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...
Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...
 
Nombres y logos
Nombres y logosNombres y logos
Nombres y logos
 

Semelhante a Apache Velocity 1.6

Rails Presentation - Technology Books, Tech Conferences
 Rails Presentation - Technology Books, Tech Conferences Rails Presentation - Technology Books, Tech Conferences
Rails Presentation - Technology Books, Tech Conferences
tutorialsruby
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentation
guestcf600a
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentation
guestcf600a
 
JQuery-Tutorial" />
  JQuery-Tutorial" />  JQuery-Tutorial" />
JQuery-Tutorial" />
tutorialsruby
 

Semelhante a Apache Velocity 1.6 (20)

8. Php MongoDB stergerea unui document
8. Php MongoDB stergerea unui document8. Php MongoDB stergerea unui document
8. Php MongoDB stergerea unui document
 
7. Php MongoDB editarea unui document
7. Php MongoDB editarea unui document7. Php MongoDB editarea unui document
7. Php MongoDB editarea unui document
 
5. Php MongoDB vederea unui singur document
5. Php MongoDB vederea unui singur document5. Php MongoDB vederea unui singur document
5. Php MongoDB vederea unui singur document
 
9. Php MongoDB cautarea unui document
9. Php MongoDB cautarea unui document9. Php MongoDB cautarea unui document
9. Php MongoDB cautarea unui document
 
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
 
6. Php MongoDB adaugarea unui document
6. Php MongoDB adaugarea unui document6. Php MongoDB adaugarea unui document
6. Php MongoDB adaugarea unui document
 
Shell Script Disk Usage Report and E-Mail Current Threshold Status
Shell Script  Disk Usage Report and E-Mail Current Threshold StatusShell Script  Disk Usage Report and E-Mail Current Threshold Status
Shell Script Disk Usage Report and E-Mail Current Threshold Status
 
Unfiltered Unveiled
Unfiltered UnveiledUnfiltered Unveiled
Unfiltered Unveiled
 
Jquery
JqueryJquery
Jquery
 
Meet Up - Spark Stream Processing + Kafka
Meet Up - Spark Stream Processing + KafkaMeet Up - Spark Stream Processing + Kafka
Meet Up - Spark Stream Processing + Kafka
 
Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languages
 
Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
Dealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter ScottDealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter Scott
 
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
Pitfalls to Avoid for Cascade Server Newbies by Lisa HallPitfalls to Avoid for Cascade Server Newbies by Lisa Hall
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
 
Ip lab
Ip labIp lab
Ip lab
 
Rails Presentation - Technology Books, Tech Conferences
 Rails Presentation - Technology Books, Tech Conferences Rails Presentation - Technology Books, Tech Conferences
Rails Presentation - Technology Books, Tech Conferences
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentation
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentation
 
JQuery-Tutorial" />
  JQuery-Tutorial" />  JQuery-Tutorial" />
JQuery-Tutorial" />
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

Apache Velocity 1.6

  • 1. An Introduction to Apache Velocity 1.6 Henning Schmiedehausen henning@apache.org ApacheCon 2009, Oakland, CA, U.S.A.
  • 2. Templating Engine? • Uses a simple language (Velocity Templating Language = VTL) • Templates are text which contains active elements • Active elements are replaced with values from the Model • No "industry standard" templating language • Templates are processed, not compiled
  • 3. Templating engines • perl • HTML-Template, Mason • PHP • Smarty, SmartTemplate, TinyButStrong • Ruby • Galena, LiquidMarkup, ERB, lots more • Python • QuickSilver, Cheetah, TurboGears, Airspeed • Java • WebMacro, StringTemplate, FreeMarker, Apache Velocity ApacheCon US 2009
  • 4. A short history of Velocity • Started in 2000 • One of the first Apache Jakarta projects • ASF-licensed alternative to WebMacro • Language syntax similar and very stable • 100% pure Java, runs on Java 1.3 or better • Apache TLP since 2006, from Jakarta • Current release: 1.6.2 (March '09) ApacheCon US 2009
  • 5. Velocity Spotting • Velocity is integrated in many other Apache projects • Web Frameworks: Click, Wicket, Struts, Turbine • Other projects: Maven, Camel, Portals, Tiles http://wiki.apache.org/velocity/PoweredByVelocity • Support for IDEs and Editors available (e.g. Eclipse, IntelliJ, emacs...) http://wiki.apache.org/velocity/VelocityEditors • View Component in Web Frameworks • Code Generation (Apache Torque, Eclipse) • Documentation Generation (Maven, Anakia, Texen) • E-Mail Templating (e.g. Spring Framework) ApacheCon US 2009
  • 6. Velocity vs. JSP • Easier to test • No servlet container required • Better separation of Code and Design • No compilation into Java code • Few, easy to learn language elements • No embedded Java code! • better read- and understandable ApacheCon US 2009
  • 7. Template Example <div>${addr.title} ${addr.first} ${addr.last}</div> <div>${addr.street}</div> <div>${addr.town} ${addr.zip}, ${addr.state}</div> <b>Invoice</b> <div>Date: $format.date(${time.currDate})</div> <table> <tr><th>Pos</th><th>Description</th><th>Price</th> <th>Qty</th><th>Total</th></tr> #foreach($item in $invoice.items) <tr><td>$velocityCount</td><td>$item.desc</td> <td>$format.money($item.price)</td><td>$item.quantity</td> <td>$format.money($item.total)</td></tr> #end </table> <div>Total $format.money($invoice.total)</div> <div>Tax $format.money($invoice.tax)</div> ApacheCon US 2009
  • 8. Template Result Mr John Doe 1234 Evergreen Terrace Springfield, 12345, AY Invoice Date: Nov 3rd, 2009 Pos Description Price Qty Total 1 TV Set $499.95 1 $499.95 2 BluRay Player $299.95 1 $299.95 Various BluRay 3 $9.95 5 $49.95 Titles Total $849.97 Tax $49.90 ApacheCon US 2009
  • 9. Template deciphered <div>${addr.title} ${addr.first} ${addr.last}</div> <div>${addr.street}</div> <div>${addr.town} ${addr.zip}, ${addr.state}</div> <b>Invoice</b> A "con $format.date(${time.currDate})</div> <div>Date:xt te o bject" contai <table> getter ns the s for t a he fiel ddress. It h <tr><th>Pos</th><th>Description</th><th>Price</th> getTit le(), g ds: as <th>Qty</th><th>Total</th></tr> etFirst #foreach($item n(), (), getLast(), getTo in $invoice.items) w getZip g (), get etStreet(), <tr><td>$velocityCount</td><td>$item.desc</td> State() <td>$format.money($item.price)</td><td>$item.quantity</td> <td>$format.money($item.total)</td></tr> #end </table> <div>Total $format.money($invoice.total)</div> <div>Tax $format.money($invoice.tax)</div> ApacheCon US 2009
  • 10. Template deciphered A ${addr.last}</div> <div>${addr.title} ${addr.first} nother c forma ontex <div>${addr.street}</div> tters f t obje or dat ct con <div>${addr.town} ${addr.zip}, ${addr.state}</div>e and tains Such a curren n obje cy. <b>Invoice</b> ct is c alled a <div>Date: $format.date(${time.currDate})</div> "Tool" . <table> <tr><th>Pos</th><th>Description</th><th>Price</th> <th>Qty</th><th>Total</th></tr> #foreach($item in $invoice.items) <tr><td>$velocityCount</td><td>$item.desc</td> <td>$format.money($item.price)</td><td>$item.quantity</td> <td>$format.money($item.total)</td></tr> #end </table> <div>Total $format.money($invoice.total)</div> <div>Tax $format.money($invoice.tax)</div> ApacheCon US 2009
  • 11. Template deciphered <div>${addr.title} ${addr.first} ${addr.last}</div> <div>${addr.street}</div> <div>${addr.town} ${addr.zip}, ${addr.state}</div> The "i n iterab voice" obje <b>Invoice</b> le field ct con loop c . The tains a #forea <div>Date: $format.date(${time.currDate})</div> reates n the ite ch...#e mized nd <table> list. <tr><th>Pos</th><th>Description</th><th>Price</th> <th>Qty</th><th>Total</th></tr> #foreach($item in $invoice.items) <tr><td>$velocityCount</td><td>$item.desc</td> Fun fa <td>$format.money($item.price)</td><td>$item.quantity</td> ct: Vel conve o nient city p <td>$format.money($item.total)</td></tr> rovid es a count #end for loo ps! </table> <div>Total $format.money($invoice.total)</div> <div>Tax $format.money($invoice.tax)</div> ApacheCon US 2009
  • 12. Template deciphered <div>${addr.title} ${addr.first} ${addr.last}</div> <div>${addr.street}</div> Th ${addr.state}</div> <div>${addr.town} ${addr.zip}, e rema This c inder is just an be <b>Invoice</b> HTML any ki formatted t n <div>Date: $format.date(${time.currDate})</div> d of text , XML ext. or pla , in tex e.g. <table> t. <tr><th>Pos</th><th>Description</th><th>Price</th> <th>Qty</th><th>Total</th></tr> #foreach($item in $invoice.items) <tr><td>$velocityCount</td><td>$item.desc</td> <td>$format.money($item.price)</td><td>$item.quantity</td> <td>$format.money($item.total)</td></tr> #end </table> <div>Total $format.money($invoice.total)</div> <div>Tax $format.money($invoice.tax)</div> ApacheCon US 2009
  • 13. Velocity Template Language • Simple Constructs • #directive() - line directives • #directive() ... #end - block directives • $reference or ${reference} - references • Embedded directly into template files (no open or close tags like php or JSP) • References are "loosely typed" ApacheCon US 2009
  • 14. Assignments - #set() • #set creates or updates a reference • #set( $foo = “text” ) String value • #set( $foo = 100 ) Numeric value • #set( $foo = [ 1, 2, 3 ] ) Array • #set( $foo = { 1 : 2, 3 : 4 } ) Map • #set( $foo = $bar ) Reference • #set( $foo = $bar.foo ) Bean getter • #set( $bar.foo = "200" ) Bean setter • #set( $foo = $bar.doFoo() ) Method Result ApacheCon US 2009
  • 15. Demo #1 - References #set( $message = 'Hello World' ) This is a Velocity "$message" program. #set( $favorite = 137 ) My favorite number is not ${favorite}. ApacheCon US 2009
  • 16. Control structures • Loop • #foreach( $foo in $bars ) ... #end • loops can be terminated with #break • $velocityCount provides loop count • $velocityHasNext allows "peeking ahead" • Conditional • #if ( ) … #elseif ( ) … #else … #end ApacheCon US 2009
  • 17. Control structures • Inclusion of external elements • #include() Load external file • #parse() Load and parse file • Turn VTL blocks into references • #define(name) ... #end • Evaluate templates on the fly • #evaluate(...) ApacheCon US 2009
  • 18. Demo #2 - Loops #set( $list = [ 'a ', ' b ', ' c ', ' d ' ] ) #foreach( $alpha in $list ) The current letter is ${alpha}. Hint: O pening #end a bloc k can and cl osing be on el the sa ement of me lin Let’s count: #foreach( $i in [ 1..10 ] )$i #end e! ApacheCon US 2009
  • 19. Demo #3 - Conditionals #if( $lang eq "DE" ) ##Use german Hallo Welt! #elseif( $lang eq "FR" ) Bonjour Monde! #else #*Use default greeting*# Hello World! #end ApacheCon US 2009
  • 20. Bonus Slide: Comment Syntax #if( $lang eq "DE" ) ##Use german Hallo Welt! #elseif( $lang eq "FR" ) Bonjour Monde! #else #*Use default greeting*# ThHello World! is is th e Velo city co ## com mmen ments #end to the t synta #* .... x: *# enc end of loses the lin a mult e, iline c omme nt. ApacheCon US 2009
  • 21. Macros • Builds a block directive on the fly • Create: #macro (name) … #end • Use: #name() … #end • global and local scope supported • Technically some sort of “method call” (please don’t use it like this) • factor out common template code/content ApacheCon US 2009
  • 22. Macros • Macros can take parameters • Create: #macro( name $arg1 $arg2 ) … $arg1 … $arg2 … #end • Use: #name( $foo $bar ) … #end • Arbitrary number of parameters possible • Number of call parameters must match definition! ApacheCon US 2009
  • 23. Demo #4: Macros #macro( quote $value ) &quot;$value&quot; #end A macro quotes #quote( 'this phrase' )! Result: A macro quotes &quot;this phrase&quot;! ApacheCon US 2009
  • 24. Reference Syntax & Evaluation • Any reference represents a Java object • Use ${reference} to avoid parsing ambiguities • If a reference resolves to "null", the reference itself is inserted in the template • $!ref or $!{ref} means "be quiet when null" • Evaluation uses toString() method ApacheCon US 2009
  • 25. Reference Syntax & Evaluation • Any reference represents a Java object • Use ${reference} to avoid parsing ambiguities • If a reference resolves to "null", the Yeah, that w as a s reference itself is inserted in the template tupid idea. • $!ref or $!{ref} means "be quiet when null" • Evaluation uses toString() method ApacheCon US 2009
  • 26. Reference Syntax & Evaluation • Any reference represents a Java object • Use ${reference} to avoid parsing ambiguities • If a reference resolves to "null", the reference itself is inserted in the template • $!ref or $!{ref} means "be quiet when null" • Evaluation uses toString() method ApacheCon US 2009
  • 27. Reference Syntax & Evaluation • Any reference represents a Java object • Use ${reference} to avoid parsing Trivia: C an end onfusing $ less so !{foo} urce o with !$ ambiguities Also !$ !{foo} f fun! {foo} c an be and in lo credib oks awkwa • If a reference resolves to "null", the ly use ful. rd but is vali d VTL reference itself is inserted in the template • $!ref or $!{ref} means "be quiet when null" • Evaluation uses toString() method ApacheCon US 2009
  • 28. Velocity Operators • Arithmetic operators • #set ($foo = 5 / 2 ) ## is 2! #set ($foo = 5.0 / 2) ## is 2.5 • The usual suspects: +, -, /, *, % • Range Operator • #set ($numbers = [ 1..100 ]) creates a list of integers from 1 to 100 ApacheCon US 2009
  • 29. Velocity Operators Fun fa suppo ct: Sin ce Ver rts all si arithm numb on 1.5, Velo er typ etics w as inte es. Be city • Arithmetic operators ger on fore, a ly. ll • #set ($foo = 5 / 2 ) ## is 2! #set ($foo = 5.0 / 2) ## is 2.5 • The usual suspects: +, -, /, *, % • Range Operator • #set ($numbers = [ 1..100 ]) creates a list of integers from 1 to 100 ApacheCon US 2009
  • 30. Misc.Velocity • Boolean operators for conditionals • !, &&, ||, ==, <=, <, >, >= • not, and, or, eq, ne, gt, ge, lt, le for convenience in e.g. XML templates • For == and !=, if the operands are not of the same class, their toString() values are compared ApacheCon US 2009
  • 31. Velocity Strings • String interpolation for #set(), macro args and method args: • #set( $foo = 3.5 ) #set( $foo = "Value was $foo" ) $foo is now "Value was 3.5" • Force a reference to be a String: • #set ($foo = "$foo") • Use ' to avoid interpolation: • #set ($foo = '$foo') ApacheCon US 2009
  • 32. Velocity Context • Context objects are accessible in templates • Map of names (${foo}) to arbitrary objects • Templates can only access what is in the context • There is no way to create Java objects except through context elements • Velocity can restrict which methods and fields on a context object are available ApacheCon US 2009
  • 33. Velocity Context Example public static void main(String [] args) throws Exceptions{cre Thi ates $ {user} and $ VelocityContext {cliche context = new VelocityContext(); } context.put("user", "Velocity User"); context.put("cliche", "Hello World!"); VelocityEngine engine = new VelocityEngine(); Template template = engine.getTemplate(args[0]); Writer out = new OutputStreamWriter(System.out); template.merge(context, out); out.flush(); } ApacheCon US 2009
  • 34. Velocity Context Template #if ($!{user}) Hello, ${user}! #end Here is a cliche: ${cliche} ApacheCon US 2009
  • 35. Velocity Context Template $!{use r}  is a eleme n nt in t ifty way to he con test w text e hether xists a nd is n the user on-nu ll. #if ($!{user}) Hello, ${user}! #end Here is a cliche: ${cliche} ApacheCon US 2009
  • 36. Velocity Context Result Hello, Velocity User! Here is a cliche: Hello, World! ApacheCon US 2009
  • 37. Interaction with the Context • The real power of Velocity • Uses runtime reflection • All public methods in public classes are available • Shortcut notation for property access ($a.b vs $a.getB()) • Type promotion as Java does • Method parameters can not be omitted! (this is not perl!) ApacheCon US 2009
  • 38. Interaction with the Context Trivia: • The real power of Velocity Also, u p • anoth ublic meth er gre Uses runtime reflection o at way ds in publi to spe c sing in nd ho classes! Ign • ner cla All public methods in public classes are sses c urs de an be o buggi ring this is icky. T ng! available ry to a void it . • Shortcut notation for property access ($a.b vs $a.getB()) • Type promotion as Java does • Method parameters can not be omitted! (this is not perl!) ApacheCon US 2009
  • 39. Velocity Tools • A "tool" is a context object that exposes useful methods to a template, e.g date formatting or localization • A "toolbox" is a collection of useful Java classes • The Velocity Tools sub-project offers: • GenericTools All-purpose tools • VelocityView Webapp centric tools • VelocityStruts Velocity as Struts 1.x View • Other toolboxes on the web ApacheCon US 2009
  • 40. VelocityViewServlet • VelocityViewServlet renders arbitrary Templates through web.xml mapping • XML config file to define tools • Different tool scopes/lifecycles: • application, session, request • Request, Response, Session and ServletContext objects are exposed to templates ApacheCon US 2009
  • 41. Demo #5:VelocityView • Uses VelocityTools 2.0 (beta4 is the current release) • VelocityViewServlet does the work • Uses LinkTool, ParameterTool, EscapeTool • ($link, $params, and $esc) • A custom tool: AddressBook is a ~30 line POJO • Only one template: index.vm (~50 lines) • ~20 lines of config (including web.xml) ApacheCon US 2009
  • 42. Advanced Velocity • Custom directives can be created and integrated in the Velocity parser (org.apache.velocity.runtime.directive.Directive) • Multiple Resource loaders to load templates from different sources (files, classpath, jars, database, remote URLs) • Event Handlers for Exception handling, XML escaping, etc. • Introspector for method and property access can be customized or replaced with user code ApacheCon US 2009
  • 43. Hacking Velocity • Velocity Template Language (VTL) is defined in JavaCC grammar • VTL itself can be changed or extended (requires recompilation of velocity.jar) • More “Advanced Velocity“ at http:// wiki.apache.org/velocity/HackingVelocity ApacheCon US 2009
  • 44. Other Velocity uses • Velocity Subprojects • Texen for generic text generation • Anakia for XML to documentation • Apache Torque – generates Java and SQL code from templates • VelocityViewTag – Embed Velocity in JSP • Velosurf – Generate SQL Web Views ApacheCon US 2009
  • 46. Where to go from here • Velocity Web Site • http://velocity.apache.org/ • Velocity Mailing Lists • http://velocity.apache.org/contact.html • Velocity Wiki • http://wiki.apache.org/velocity/ • Slides at the US ApacheCon 2009 web site and on slideshare.net ApacheCon US 2009
  • 47. Thanks for your interest in Velocity!

Notas do Editor

  1. mvn exec:java -Dexec.mainClass=org.apache.velocity.contextdemo.ContextDemo -Dexec.args=src/main/templates/Test.vm