In the original incarnation of my simple time tracker application I had used freemarker as a template engine for the email report. For this new incarnation I thought I'd take the newly open sourced Google XML Pages (GXP) for a spin.
Unlike JSP pages which generate and compile .java files on the fly, GXP generates .java files up front as part of your build process and forms a type safe API to the rest of your application to use. Just as Apache Wicket brings type safety to your web applications Session and Pages, GXP brings it the same power to your templates.
A short example is the Work Item Summary template:
<gxp:template name='com.theoryinpractice.timetrackr.gxp.WorkItemSummary'
xmlns='http://www.w3.org/1999/xhtml'
xmlns:gxp='http://google.com/2001/gxp'>
<gxp:import package="java.util"/>
<gxp:import package="com.theoryinpractice.timetrackr.vo"/>
<gxp:import package="com.theoryinpractice.timetrackr.pages"/>
<gxp:param name="reportForDate" type='String'/>
<gxp:param name="formattedTimeFor" type='String'/>
<gxp:param name="activities" type='List{ActivityReport}'/>
...
Once generated and compiled, this is called in java with:
List<ActivityReport> activities = new ArrayList<ActivityReport>(); ... StringBuilder buffer = new StringBuilder(); WorkItemSummary.write( buffer, new GxpContext(Locale.getDefault()), reportForDate, TimeFormat.format(userManager.calculateTimeForUser(user, Boolean.FALSE)), activities );
The generated API is clean and simple to use, a single method to call with the required parameters and you're away laughing. Comparing this with how I've used velocity and freemarker in the past, I can already see several benefits:
The GXP template may be a little bit more wordy than the original freemarker version, but the safety it brings to the build is well worthy the XML.
"Templates can easily be bundled"