apache velocity - oscon2007

Upload: karthikstsm

Post on 02-Jun-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 Apache Velocity - OSCON2007

    1/33

    Apache VelocityA Java Template Engine

    Nathan Bubna

    [email protected],

    Henning P. [email protected]

    OSCON 2007, July 25th 2007

    Portland, Oregon

    http://people.apache.org/~nbubna/oscon2007

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 8/11/2019 Apache Velocity - OSCON2007

    2/33

    Template Engine? Defines a simple language

    (VTLVelocity Template Language)

    Templates are text containing active

    elements Active elements are replaced with

    values from the model

    No industry standard templatelanguage

    Templates are processed, notcompiled

  • 8/11/2019 Apache Velocity - OSCON2007

    3/33

    Velocity Background- Velocity was started in 2000

    - One of the first Jakarta projects

    - ASF-licensed alternative to WebMacro

    - Language syntax is similar and still very stable

    - 100% Pure Java (runs on Java 1.3 or better)

    - Velocity became an Apache TLP in 2006

    - Current release is 1.5 (as of March 07)

  • 8/11/2019 Apache Velocity - OSCON2007

    4/33

    Velocity Spotting- Velocity is integrated with many other projects (Turbine, Struts 2,

    Maven) and others (http://wiki.apache.org/velocity/PoweredByVelocity)

    - Support for IDEs and Editors available (e.g. Eclipse, IntelliJ

    IDEA, emacs) (http://wiki.apache.org/velocity/VelocityEditors)

    - Response content in webapp frameworks (e.g. Struts, Turbine)

    - Code generation (e.g. Torque, MyEclipse)

    - Documentation (e.g. Maven, Anakia)

    - Email (e.g. Spring)

    http://wiki.apache.org/velocity/PoweredByVelocityhttp://wiki.apache.org/velocity/VelocityEditorshttp://wiki.apache.org/velocity/VelocityEditorshttp://wiki.apache.org/velocity/PoweredByVelocity
  • 8/11/2019 Apache Velocity - OSCON2007

    5/33

    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!

    - Easy on the eyes

  • 8/11/2019 Apache Velocity - OSCON2007

    6/33

    Real Template Engines- perl: HTML-Template, Mason

    - php: Smarty, SmartTemplate,

    TinyButStrong- Ruby: Galena, LiquidRuby

    - Python: QuickSilver, Cheetah,TurboGears, Airspeed

    - Java: WebMacro, FreeMarker,Apache Velocity

  • 8/11/2019 Apache Velocity - OSCON2007

    7/33

    Velocity Template Language- Simple constructs

    - #directive() (line directives)

    - #directive() #end (block directives)

    - $referenceor ${reference}

    - Embedded directly into template files(no open / close tags like JSP or PHP)

    - References are loosely typed

    - VTL can be learned in minutes

  • 8/11/2019 Apache Velocity - OSCON2007

    8/33

    Assignments - #set()- #set is used to create or update 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 Property

    - #set( $foo = $bar.doFoo() ) Method Result

  • 8/11/2019 Apache Velocity - OSCON2007

    9/33

    Demo #1 - References

    - #set( $message = Hello World )

    - This is a Velocity $message program.

    - #set( $favorite = 137 )

    - My favorite number is not $favorite.

  • 8/11/2019 Apache Velocity - OSCON2007

    10/33

    Display Control Elements- Loop

    - #foreach( $foo in $bars ) ... #end

    - Conditional

    - #if ( ) #elseif ( ) #else #end

    - Inclusion of external elements

    - #include( ) Load external file

    - #parse( ) Load and parse file

  • 8/11/2019 Apache Velocity - OSCON2007

    11/33

    Demo #2 - Loops

    - #set( $list = [ a, b, c, d] )

    - #foreach( $alpha in $list )

    - The current letter is $alpha

    - #end

    - Lets count #foreach( $i in [ 1..10 ] )$i #end

  • 8/11/2019 Apache Velocity - OSCON2007

    12/33

    Demo #3 - Conditionals

    - #if( $speaker eq Henning )##Use german

    - Hallo Welt!

    - #elseif( $hello )

    - $hello

    - #else #*Use default greeting*#

    - Hi World!

    - #end

  • 8/11/2019 Apache Velocity - OSCON2007

    13/33

    Macros- Builds a block directive on the fly

    - Create: #macro (name) #end

    - Use: #name() #end

    - Velocity supports global and local scope

    - Technically some sort of method call(please dont use it like this)

    - For factoring out common template code/content

  • 8/11/2019 Apache Velocity - OSCON2007

    14/33

    Macros- Macros can take parameters

    - Create:

    - #macro( name $arg $arg2 ) $arg$arg2#end

    - Use:

    - #name( $foo $bar ) #end

    - Arbitrary number of parameters possible

    - Number of call parameters must match definition!

  • 8/11/2019 Apache Velocity - OSCON2007

    15/33

    Demo #4 - Macros- #macro( quote $value )"$value"#end

    - We use a macro to quote #quote( 'thisphrase' ).

  • 8/11/2019 Apache Velocity - OSCON2007

    16/33

    Reference Syntax & Evaluation- A $referencerepresents a Java object

    - Use a${formalReference}to avoid parsing ambiguities

    - $!ref or $!{ref}means be quiet when null(do not confuse with !$reference)

    - Evaluation alwaysinvokes toString()method

  • 8/11/2019 Apache Velocity - OSCON2007

    17/33

    Velocity Miscellany- A range operator exists- #set ($foo = [ 1..100 ]) List of integers 1 to 100

    - Arithmetic (both integer and floating point)

    - #set ($foo = 1.5+ 2 ) $foo is now 3.5

    - +, -, /, *, %

    - Boolean operators for conditionals

    - !, &&, ||, ==, =

    - not, and, or, eq, ne, gt, ge, lt, le

    - For == and !=, if the operands are not of the same class,their toString()values are compared

    - String interpolation for #set(), macro args and method args

    - #set( $foo = foo was $foo ) $foo is now foo was 3.5

  • 8/11/2019 Apache Velocity - OSCON2007

    18/33

    Velocity Context- The Context is the means of importing values into the

    template

    - It is essentially a map of reference identifiers (i.e. thefoo in ${foo}) to Java objects

    - All access to data in the template comes this way

    - There is no natural or native way to access or create

    Java objects

  • 8/11/2019 Apache Velocity - OSCON2007

    19/33

    DemoUsing A Context- public static void main(String [] args) throws Exception {

    - VelocityEngine engine = new VelocityEngine();

    - VelocityContext context = new VelocityContext();- context.put(speaker", Nathan);

    - context.put("hello", "Hello World!");

    - Template template = engine.getTemplate(args[0]);

    - StringWriter out = new StringWriter();

    - template.merge(context, out);

    - System.out.println(out.toString());

    - }

  • 8/11/2019 Apache Velocity - OSCON2007

    20/33

    Interacting With Context Objects- The real power of Velocity

    - All public methods in public classes are available

    - All works via runtime reflection

    - 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!)

  • 8/11/2019 Apache Velocity - OSCON2007

    21/33

    VelocityTools- A tool is just a context object that is useful in a

    template

    - Collection of useful Java classes.

    - Comes in three flavors:

    - GenericTools All-purpose tools

    - VelocityView Tools and more for webapps

    - VelocityStruts Velocity as Struts View layer

    - Other tools out there on the web

  • 8/11/2019 Apache Velocity - OSCON2007

    22/33

  • 8/11/2019 Apache Velocity - OSCON2007

    23/33

    Advanced Velocity- Custom directives possible

    (org.apache.velocity.runtime.directive.Directive)

    - Multiple Resource loaders to load templates fromdifferent sources(files, classpath, jars, database, remote URLs)

    - Event Handlers for Exception handling, XML escaping,etc

    - Custom Introspector for method and property accesspossible

  • 8/11/2019 Apache Velocity - OSCON2007

    24/33

    Advanced Velocity- Velocity Template Language (VTL) is defined in JavaCC

    grammar

    - VTL itself can be changed or extended(needs recompilation of velocity.jar)

    - More Advanced Velocity athttp://wiki.apache.org/velocity/HackingVelocityincluding theexcellent ApacheCon 2004 session slides by Will Glass-Husain

    http://wiki.apache.org/velocity/HackingVelocityhttp://wiki.apache.org/velocity/HackingVelocity
  • 8/11/2019 Apache Velocity - OSCON2007

    25/33

    Demo #5 - VelocityView- Uses VelocityTools 2.0 (only alpha release available)

    - VelocityViewServlet does the work

    - Uses LinkTool, ParameterTool, EscapeTool- (aka $link, $params, and $esc)

    - One custom tool: AddressBook is a ~30 line POJO

    - One template: index.vm is just ~50 lines

    - ~20 lines of config (including web.xml)

  • 8/11/2019 Apache Velocity - OSCON2007

    26/33

    Velocity with Struts 1.x- VelocityTools provides Struts tools for integration

    - Seamless, not mutually exclusive with JSP

    -

    - (Image from http://velocity.apache.org/tools/devel/struts/!)

  • 8/11/2019 Apache Velocity - OSCON2007

    27/33

    Velocity with Struts 1.x- ActionMessagesTool - Action Messages

    - ErrorsTool - Error Messages

    - FormTool - Forms handling- MessageTool - i18n Message Support

    - StrutsLinkTool,SecureLinkTool - Links

    - TilesTool - Struts-Tiles Framework

    - ValidatorTool - Validator Framework

  • 8/11/2019 Apache Velocity - OSCON2007

    28/33

    Velocity with Turbine- Preferred View Layer of Turbine

    - No separate Servlet

    - Turbine fully integrates Velocity

    - Turbine provides infrastructure

    - Tools

    - Template Loaders

    - Configuration and Logging

  • 8/11/2019 Apache Velocity - OSCON2007

    29/33

    Velocity with- Velocity is supported as a first-class view layer in

    - Struts 2.x (uses custom directives instead of tools)

    - Spring MVC (also supports VelocityTools 1.x well)- Click (http://click.sourceforge.net/)

    - Restlet (http://www.restlet.org/)

    - Mentawai (http://www.mentaframework.org/)- And at least a dozen others

    - (http://wiki.apache.org/velocity/PoweredByVelocity)

    http://click.sourceforge.net/http://www.restlet.org/http://www.restlet.org/http://click.sourceforge.net/
  • 8/11/2019 Apache Velocity - OSCON2007

    30/33

    Other Velocity Uses- Texenfor generic text generation

    - Anakiafor XML to documentation

    - Torquegenerate Java and SQL code

    - VelocityViewTagEasily embed Velocity in JSP- (Part of the upcoming VelocityTools 2.0)

    - VelosurfTool for abstracting database interaction

  • 8/11/2019 Apache Velocity - OSCON2007

    31/33

    Any questions?

  • 8/11/2019 Apache Velocity - OSCON2007

    32/33

    Where to go from here?- Velocity Homepage

    - http://velocity.apache.org/

    - Velocity Mailing Lists

    - http://velocity.apache.org/contact.html

    - Velocity Wiki

    - http://wiki.apache.org/velocity/

    - These Slides and Demo Code

    - http://people.apache.org/~nbubna/oscon2007

    - Velocity 1.5 Release Notes

    - http://wiki.apache.org/jakarta-velocity/Velocity15ReleaseNotes

    http://velocity.apache.org/http://velocity.apache.org/contact.htmlhttp://wiki.apache.org/velocity/http://people.apache.org/~nbubna/oscon2007http://wiki.apache.org/jakarta-velocity/Velocity15ReleaseNoteshttp://wiki.apache.org/jakarta-velocity/Velocity15ReleaseNoteshttp://wiki.apache.org/jakarta-velocity/Velocity15ReleaseNoteshttp://wiki.apache.org/jakarta-velocity/Velocity15ReleaseNoteshttp://wiki.apache.org/jakarta-velocity/Velocity15ReleaseNoteshttp://people.apache.org/~nbubna/oscon2007http://wiki.apache.org/velocity/http://velocity.apache.org/contact.htmlhttp://velocity.apache.org/
  • 8/11/2019 Apache Velocity - OSCON2007

    33/33

    Thanks for your attention!