Converting a POJO into HTML

0

Axiom: Whatever your assignment, someone else has already done it.

Recently I needed to display the contents of some Plain Ol’ Java Objects on a web page for a customer.  The objects were from several classes, so  I was thinking of using Java reflection to keep from writing redundant code.  Reflection is old hat for me, but there had to be a simpler solution.

I considered using Jackson to create a JSON representation and then a JavaScript to render it all nice and pretty.  However, that required both back-end and front-end code.  There had to be something easier.  I stumbled on Apache’s ReflectionToStringBuilder class.  Bingo!  All it needs is a little styling to create an HTML table and we’re good to go.

For example, a person object with an embedded friend object might look like this:

FieldData
id1234
nameBob Smith
phones[213-555-1212]
bestFriend
FieldData
id1234
nameMary Jones
phones[408-555-1212, 415-555-1212]
bestFriend

 

Here is the class that does the work:

 

This pom file will grab the correct libraries and make it possible to run the test:

 

And finally some tests to make sure it’s all running smooth:

Share.

About Author

Steve Sando

Steve works with successful software startups and tech companies throughout Silicon Valley. Most recently he has been developing content migration tools for large websites. He has a deep passion for all things software engineering, from design concepts, to team management, to final delivery.

Leave A Reply