BeansBinding ELProperty as simple template engine

I just read an article about using adding EL support on your projects and I was looking for a nice alternative to Velocity anyways.

I know EL basics from BeansBinding, which I use in most of my UI projects. EL itself looks pretty interesting, but, well, sort of complicated. Even finding the proper jar files seems to be a problem, or at least “another of life’s obscure mysteries” and using EL for a simple search and replace example implies implementing some internals. I was looking for something that I can just use.

Luckily, the first comment mentions the ELProperty class from BeansBinding, and that jar is just a few mouse clicks away, so I thought I give it a try…and…well…it works ;)

public static void main(String[] args) {
    Person mom = new Person("Ann", null);
    Person son = new Person("Dave", mom);
    Dog dog = new Dog("Foxy");

    ELProperty el = ELProperty
            .create("${name}'s mom is ${mother.name}");
    System.out.println(el.getValue(son));

    ELProperty mapEL = ELProperty
            .create("${mother.name}'s dog is ${dog.name}");
    Map map = new HashMap();
    map.put("mother", mom);
    map.put("dog", dog);
    System.out.println(mapEL.getValue(map));
}

ELProperty.create() creates a new instance from a template string. You can fill the template with values using getValue() method. This one takes either an Object with proper getter methods or a Map to resolve variables. And this is the result of the simple example:

Dave's mom is Ann
Ann's dog is Foxy

Full Sample Code ( You need the beansbinding jar in the classpath)

Tags: ,

Thursday, October 30th, 2008 Other

1 Comment to BeansBinding ELProperty as simple template engine

  1. Thanks, it is very understandable for beginners

  2. Mikhail on September 29th, 2009

Leave a comment