I have a rest resource with a method that should return some data as html. We’re talking about a list of Reports, which is a simple class consisting of 6 string member variables.
I am asking because the prospect of appending elements and values to a string seems slow and error prone, and I would really prefer to do it in an object oriented way.
The normal way of generating HTML for a web response is to use a JSP or a Java templating engine like Velocity or FreeMarker.
If you are currently returning responses as XML, another approach would be to use XSLT to transform the XML to HTML. The XSLT processing can be done on the client side (in the browser) if you include an appropriate “processing” instruction in the XML that links to the XSLT resource.
I used to think that bashing strings together was a reasonable solution, but then I came to realize that that results in you hard-wiring your HTML layout into your Java code. The JSP, templating and transformation approaches all avoid this, allowing you to adjust the generated HTML later in the development cycle; e.g. at system integration time, or even post deployment.