apache velocity

33
Apache Velocity A Java Template Engine Nathan Bubna [email protected] , Henning P. Schmiedehausen [email protected] OSCON 2007, July 25th 2007 Portland, Oregon http://people.apache.org/~nbubna/ oscon2007(.zip)

Upload: bhavya-siddappa

Post on 25-May-2015

7.504 views

Category:

Technology


8 download

DESCRIPTION

Velocity is used to generate web pages in applications, usually as a direct replacement for JSP.

TRANSCRIPT

Page 1: Apache Velocity

Apache VelocityA Java Template Engine

Nathan [email protected],

Henning P. [email protected]

OSCON 2007, July 25th 2007 Portland, Oregon

http://people.apache.org/~nbubna/oscon2007(.zip)

Page 2: Apache Velocity

Template Engine?• Defines a simple languageDefines a simple language

(VTL – Velocity Template (VTL – Velocity Template Language)Language)

• Templates are text containing Templates are text containing active elementsactive elements

• Active elements are replaced with Active elements are replaced with values from the modelvalues from the model

• No “industry standard” template No “industry standard” template languagelanguage

• Templates are processed, not Templates are processed, not compiledcompiled

Page 3: Apache Velocity

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)

Page 4: Apache Velocity

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)

Page 5: Apache Velocity

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

Page 6: Apache Velocity

Real Template Engines- perl: HTML-Template, Mason

- php: Smarty, SmartTemplate, TinyButStrong

- Ruby: Galena, LiquidRuby

- Python: QuickSilver, Cheetah, TurboGears, Airspeed

- Java: WebMacro, FreeMarker, Apache Velocity

Page 7: Apache Velocity

Velocity Template Language- Simple constructs

- #directive() (line directives)

- #directive() … #end (block directives)

- $reference or ${reference}

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

- References are “loosely typed”

- VTL can be learned in minutes

Page 8: Apache Velocity

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

Page 9: Apache Velocity

Demo #1 - References

- #set( $message = ’Hello World’ )

- This is a Velocity “$message” program.

- #set( $favorite = 137 )

- My favorite number is not $favorite.

Page 10: Apache Velocity

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

Page 11: Apache Velocity

Demo #2 - Loops

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

- #foreach( $alpha in $list )

- The current letter is $alpha

- #end

- Let’s count #foreach( $i in [ 1..10 ] )$i #end

Page 12: Apache Velocity

Demo #3 - Conditionals

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

- Hallo Welt!

- #elseif( $hello )

- $hello

- #else #*Use default greeting*#

- Hi World!

- #end

Page 13: Apache Velocity

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 don’t use it like this)

- For factoring out common template code/content

Page 14: Apache Velocity

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!

Page 15: Apache Velocity

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

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

Page 16: Apache Velocity

Reference Syntax & Evaluation- A $reference represents a Java object

- Use a${formalReference}to avoid parsing ambiguities

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

- Evaluation always invokes toString()method

Page 17: Apache Velocity

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”

Page 18: Apache Velocity

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

the template

- It is essentially a map of reference identifiers (i.e. the “foo” 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

Page 19: Apache Velocity

Demo – Using 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());

- }

Page 20: Apache Velocity

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

Page 21: Apache Velocity

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

Page 22: Apache Velocity

VelocityView- VelocityViewServlet renders arbitrary Templates

through web.xml mapping

- Configuration of tools with an XML based configuration file

- Different tool scopes/lifecycles possible(application, session, request)

- Request, Session, Response and ServletContext objects and their attributes are available automatically

Page 23: Apache Velocity

Advanced Velocity- Custom directives possible

(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

- Custom Introspector for method and property access possible

Page 24: Apache Velocity

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“ at http://wiki.apache.org/velocity/HackingVelocity including the excellent ApacheCon 2004 session slides by Will Glass-Husain

Page 25: Apache Velocity

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)

Page 26: Apache Velocity

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

Page 27: Apache Velocity

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

Page 28: Apache Velocity

Velocity with Turbine- Preferred View Layer of Turbine

- No separate Servlet

- Turbine fully integrates Velocity

- Turbine provides infrastructure

- Tools

- Template Loaders

- Configuration and Logging

Page 29: Apache Velocity

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)

Page 30: Apache Velocity

Other Velocity Uses- Texen for generic text generation

- Anakia for XML to documentation

- Torque – generate Java and SQL code

- VelocityViewTag – Easily embed Velocity in JSP - (Part of the upcoming VelocityTools 2.0)

- Velosurf – Tool for abstracting database interaction

Page 31: Apache Velocity

Any questions?

Page 32: Apache Velocity

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

Page 33: Apache Velocity

Thanks for your attention!