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.

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.


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.)


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.


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.


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 -- a tool to track Java exceptions. You can follow him on Twitter, G+, and LinkedIn.

13 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..

  2. Great article! Thank you for posting it!

    I was thinking about doing something similar for another JAXRS impl: Dropwizard. And your article clarified some thoughts for me.

    Have you had any thoughts about CSRF protection for the destructive verbs?

    For example is there is a DELETE/POST/PUT form, then to protect against CSRF we need some extra layer/tool on top of just the session cookie ?


    • Thanks for your comments sBham, it’s good to hear others thinking about the REST + templates approach.

      For CSRF protection, you might be able to use a RESTEasy interceptor or regular servlet filter to generate and validate request token. You might then make it available as a FreeMarker shared variable for your forms to include as a hidden field.

      Jeff Atwood describes a couple CSRF protection approaches on his blog ( Both should fit in with the filter/interceptor approach.


      • interesting indeed.
        I went down the rabbit hole and got to see this solutions from the jersey folks.

        It is not as fully featured as the hidden authenticity token approach you are suggesting. that means that the server (restEasy or jersey) will have to keep track of a token and check it out with every POST/PUT/DELETE. I will need to see if anybody already did that in the wild first… we can’t be the only ones thinking of doing that 🙂 !

        public class CsrfProtectionFilter implements ContainerRequestFilter {

        private static final Set METHODS_TO_IGNORE;
        private static final String HEADER_NAME = “X-Requested-By”;

        static {
        HashSet mti = new HashSet();
        METHODS_TO_IGNORE = Collections.unmodifiableSet(mti);

        public ContainerRequest filter(ContainerRequest request) {
        if (!METHODS_TO_IGNORE.contains(request.getMethod()) && !request.getRequestHeaders().containsKey(HEADER_NAME)) {
        throw new WebApplicationException(Status.BAD_REQUEST);
        return request;

  3. Thanks a lot. I tried to use JSP in my Jersey REST services. Was quite a mess. Then I tried to integrate standalone GSP – even worse. Last try was Jade4J for server side rendering. Quite nice but it lacks in support for POJO as model-objects. So this is by far the best solution I found

  4. Michael Kaufman Reply May 16, 2017 at 2:09 PM

    HI Dele, great article! And I know it was a while ago, but I have a question. If I tried to use this approach for an email would it fail because the email downloads the css/js or does that get downloaded on the server and I don’t have to worry?

    • Hi Michael — I’m no email expert.

      I do use the same templated approach to send emails, but they don’t include images and I always embed the styles. No linking out to images, CSS or JS.

      You can read about a few ways to send images in emails here:

      My emails are usually short with a link out to a website where I can include all the imagery and click tracking I need.

      Thanks for reading, cheers.


  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 […]

  2. 10 Reasons to Replace Your JSPs With FreeMarker Templates - November 5, 2014

    […]   Read about How To Build Template Driven Java Websites with FreeMarker and RESTEasy. […]

  3. How To Build Template Driven Java Websites with FreeMarker and RESTEasy | Dinesh Ram Kali. - July 8, 2015

    […] via How To Build Template Driven Java Websites with FreeMarker and RESTEasy. […]