Bean Template Parser
Jodd is an open-source java library with lot of reusable components and feature rich utilities.
This requires the library jodd-3.3.2.jar to be in classpath.
The following example shows how to use BeanTemplateParser class.
It acts as a simple template parsing engine.
package com.bethecoder.tutorials.jodd.common;
import java.util.Date;
public class ContainerBean {
private Student student;
private Date parsedOn = new Date () ;
public Student getStudent () {
return student;
}
public void setStudent ( Student student ) {
this .student = student;
}
public Date getParsedOn () {
return parsedOn;
}
public void setParsedOn ( Date parsedOn ) {
this .parsedOn = parsedOn;
}
}
package com.bethecoder.tutorials.jodd.common;
public class Student implements java.io.Serializable {
private static final long serialVersionUID = - 5962595557796049374L ;
private String name;
private int age;
private String hobby;
public Student () {
}
public Student ( String name, int age, String hobby ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
}
public String getName () {
return name;
}
public void setName ( String name ) {
this .name = name;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public String toString () {
return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]" ;
}
}
package com.bethecoder.tutorials.jodd.beans;
import jodd.bean.BeanTemplateParser;
import com.bethecoder.tutorials.jodd.common.ContainerBean;
import com.bethecoder.tutorials.jodd.common.Student;
public class BeanTemplateParserTest {
/**
* @param args
*/
public static void main ( String [] args ) {
// prepare template string
String template = "${student.name} is a good student. He likes to play ${student.hobby}." +
"\nTemplate parsed on : ${parsedOn}" ;
// prepare bean context
ContainerBean container = new ContainerBean () ;
container.setStudent ( new Student ( "Sriram" , 2 , "Chess" )) ;
// merge template and bean context
BeanTemplateParser templateParser = new BeanTemplateParser () ;
String result = templateParser.parse ( template, container ) ;
System.out.println ( result ) ;
}
}
It gives the following output,
Sriram is a good student. He likes to play Chess.
Template parsed on : Sat Apr 07 23:25:54 IST 2012