How To Build Template Driven Java Websites with FreeMarker and RESTEasy

How To Build Template Driven Java Websites with FreeMarker and RESTEasyLast week I wrote about why you should switch to a templating engine from Java Server Pages. This week I’ll take it a step further and show you how to use FreeMarker, along with Bootstrap and RESTEasy, to create truly template driven websites. By adding a thin layer on top of FreeMarker, you’ll be able to theme your Java web apps like anything built on top of a CMS like WordPress or Drupal.

 

 

The Final Product

The example I’ll use here is a simple article submission website. Something like what you’d see on Javalobby or TheServerSide to add news and announcements.  In this case, the app does only three things:

  1. Displays submitted articles
  2. Accepts new article submissions
  3. Accepts confirmation for new article submissions

Articles Page Flow

Bootstrap Theme

This web app uses Twitter’s Bootstrap front-end framework for it’s look and feel (theme).  Since the app is template driven, you can swap out the four template files to completely re-theme it with another style.

Screen 1 - ArticlesScreen 2 - FormScreen 3 - Confirmation

 

Templates Files

All of the the app’s HTML output — forms, tables, links — are stored in four FreeMarker template files.  These files can be located anywhere FreeMarker can access (see FreeMarker Template Loaders), but “WEB-INF/content” is a safe default to start with.  When being used, the files will be referenced without the “WEB-INF/content” prefix, as “site.html” and “articles/form-article.html”.  Here’s an overview of the files, you’ll see how they are used in the REST resources later.

#
Template
Description
1WEB-INF/content/site.htmlOverall website template. Includes references to JS and CSS files.
2WEB-INF/content/articles/grid-articles.htmlArticle list table.
3WEB-INF/content/articles/form-article.htmlNew article entry form.
4WEB-INF/content/articles/form-article-confirmation.htmlNew article confirmation form.

site.html

This file houses the bulk of the HTML/FreeMarker code.  It contains a body region — ${body} — where each page’s content (like grid-articles.html) will be injected.  (Click the Expand Code icon in the toolbar to see the full source code.)

grid-articles.html

The grid template draws the article table using a combination of HTML and FreeMarker code.  It expects a collection named “article” and uses the FreeMarker list directive to create a table row for each element it finds.

The actual “articles” collection can be Java beans, JSON objects, or any other kind of sequence or collection FreeMarker understands.

form-article.html

The new article template renders the input form for new entries.  On submit it does a POST back to it’s GET URL if no addNewArticleFormAction value is specified.  It also looks for, and tries to use, the article’s properties (like article.url) if provided to the template.

form-article-confirmation.html

The confirmation template uses the supplied article to display it’s values, then POSTs back to it’s GET location on submit.

RESTful Resources

All page requests and form posts are handled by the RootResource class.  RootResource can be though of as the controller in the model-view-controller pattern.  It’s implemented as a JAX-RS resource running on JBoss’ RESTEasy framework.

POST requests always redirect the browser to a GET method on completion, while GET requests typically return content — complete HTML pages in this case.  The interesting methods here are the GET handlers.  They use the content API to interact with FreeMarker and link the model to the various template views.

Content API

The Content class is the central piece in that thin layer on top of FreeMarker I mentioned earlier.  It allows multiple templates and/or values to be added to the same named slot (like ${body}) and it allows nested templates to find models added to their parent.  It also handles all the boilerplate FreeMarker code.  Its possibly the only class you’ll need to use templates in your own servlets or RESTful resources.

Let’s breakdown the getConfirmNewArticle method to get a better idea of how things work.

  1. The outer website template is created (line 6).  This template will hold data and other templates.  It will evaluate itself and any nested templates in the right order sometime after line 14.  You can force a manual evaluation by calling it’s toString method.
  2. Two templates are nested into the outer template inside it’s body region (lines 9 & 10).
  3. The pending article is added to the outer template as a variable named article (line 12).
  4. The outer template is returned, evaluated, and it’s string contents sent to the browser (automatically, after line 14).

Content API

There are several other classes in the API.  They are used internally and exposed to keep the API flexible for special cases.  The ITemplateSource, for example, is a factory for creating FreeMarker Templates.  In most cases calling the Content constructor with the file path argument will suffice.

Template Driven Websites

Template driven websites plus RESTful resources is the sweet spot for Java web development.  Not only do you gain the ability to theme and re-theme your web application, you also get:

  1. Rapid development — leverage modern front-end frameworks.
  2. View-controller separation — view templates and REST controllers are completely separated.
  3. Role separation — developers handle the REST code and designers handle the content.
  4. On-the-fly UI changes — just refresh the browser — no lost sessions, server restarts, or class loader issues.

 

 

About Dele Taylor

Dele Taylor is the founder of StackHunter.com -- a tool to track Java exceptions. You can follow him on Twitter, G+, and LinkedIn.

3 Responses to “How To Build Template Driven Java Websites with FreeMarker and RESTEasy”

  1. This is wonderful. I should use this in my next project. Tnx Taylor..

Trackbacks/Pingbacks

  1. In praise of Java template engines | NerdlyNews - July 1, 2014

    […] “How To Build Template Driven Java Websites with FreeMarker and RESTEasy,” Java developer Dele Taylor argues that combining template-driven development with RESTful […]