Chapter 9. Templating

Introduction

Systems designed without clear separation between presentation and application logic quickly become chores to maintain. Trivial look-and-feel updates in such applications take days or weeks, and trying to extend such a coupled architecture can introduce unmanageable risks and code that is impossible to unit test. To minimize the possibility of creating such disasters, avoid coupling presentation and application logic through the use of a good templating engine. Maintain clear separation between presentation and application logic from the beginning—be orthogonal. Don’t print out HTML, XML, or SQL from Java code, use a templating engine.

The simplest example of templating is Java’s MessageFormat. A simple message, such as Hello {0}, I speak {1}, can be parameterized using the MessageFormat class. A more complex templating example is found in applications that use Jakarta Velocity or FreeMarker to avoid mixing Java with HTML or textual output. Throughout this spectrum of complexity, the concept of templating remains the same; a template with references to variables is merged with a context containing these variables. There are many ways to decouple the rigors of logic from the prettiness of presentation, and after reading this chapter, you will have a range of options for different situations.

This chapter touches upon Jakarta Velocity, Jakarta Commons JEXL, and a technology outside of the Apache Software Foundation named FreeMarker. Templating engines ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.