The best Markup Builder I could build in Java

Using Groovy MarkupBuilders spoiled me for other ways to create HTML pages from code. Others think the same. But in some organizations you have to use Java and can’t use Groovy – at least when you can’t sneak it in.

So I tinkered around in Java to see what’s the best MarkupBuilder I can write with Java. Using DSLs and Fluent Interfaces (times(5).loop), I came up with a nice solution. It’s not Groovy, but it works.

There are some tricks to make it better than most such Markup Builders in Java. I tried to use ideas from building DSLs in Java. Those are using static imports and varargs. The body, html and other elements are static imports from a MarkupBuilder class.

The varargs helps with adding a variable number of childs to an element:

Another problem is how to put object values into the generated markup. String concatenation leads to noisy code

so I decided to use a expression language where the Java unified expression language comes to mind. There is an open source version available called JUEL. Now I can use

Attributes are also treated as expressions and seperated by commas, their names and values seperated with a colon.

Loop and Action classes allow for dynamic content.

I’ve used the template design pattern for this, again with expressions, in a way Spring provides JDBC templates. Another nice idea is with static methods it’s also easy to develop custom, semantic tags, so the developer doesn’t need to know or see the actual HTML markup which is created. For example I used a box “tag” which translates to

Closures in Java 7 will make it much easier to write a MarkupBuilder. The Action and Loop inner classes will go away and the code will be more Groovy like. When they add syntactic sugar to create maps I can drop the “name:value, name:${value}” style for attributes and move to [ "name" : value, "name": value ] instead, which doesn’t need the EL to work. With some small things to add the MarkupBuilder can be used for JSON or XML.

I’m interested and open to all techniques and ideas to improve the markup builder.

Thanks for listening.

One thought on “The best Markup Builder I could build in Java”

Comments are closed.