10 Reasons to Replace Your JSPs With FreeMarker Templates

10 Reasons to Replace Your JSPs With FreeMarker TemplatesStill using Java Server Pages?  I was too, but a few years ago I ditched them and haven’t looked back since.  JSPs are a fine concept, but they take the joy out of web development.  For me, it was the little things, like having to breakup my page templates into separate files: header.jsp and footer.jsp, not being able to call methods in the expression language, and not being able to combine and arrange page parts at runtime.  FreeMarker templates are what I turned to.  FreeMarker has been around for a while, but if you haven’t looked at them recently, here are a few reasons to consider them for your next web app.

 
1. No Classloading PermGen Issues

You’re probably no stranger to the JVM’s PermGen issues if you’ve developed Java web apps for a while.  Since FreeMarker templates aren’t compiled to classes, they don’t take up permgen space and don’t require a new class loader to reload.

2. Template Loaders

Wouldn’t it be nice to load your pages and templates from a central place?  Maybe from a CMS or database.  Maybe you just want to put them on a file mount where they can be updated  without redeploying the whole app.  Well with JSPs you’re in for a hard time, but FreeMarker provides template loaders for just this purpose.  You can create your own implementation or use one of the built-in classes.

FreeMarker also has a multi loader to chain together a series of template loaders.

I typically use the WebappTemplateLoader to point to a content folder under WEB-INF.

3. Templates Can Be Nested At Runtime

FreeMarker let’s you create real templates, not just fragments — remember the header and footer JSPs?  It does this by allowing you to take one template (head.ftl in this case).

And add it to a placeholder of another template (the body region of site.ftl).

You can choose which template goes into the body region programmatically.  You can also add multiple templates together into the same region.  You can even put a string or calculated value into the body region instead.  Try doing that in a JSP.

4. No Imports

JSPs requires you to import every class you intend to use, just like a regular Java class.  FreeMarker templates on-the-other-hand are just, well, templates.  You can include one template in another, but there are no classes that need to be imported.

5. Supports JSP Tags

One argument for using JSPs is the availability of tag libraries out there.  The good news is that FreeMarker supports JSP tags.  The bad news is they’re referenced using FreeMarker syntax, not JSP syntax.

6. Method Calls in the Expression Language

Unless you’re targeting a Servlet 3.0/EL 2.2 container, method calls in the expression language are out.  Not everyone agrees that method calls in the EL are a good thing, but when you really need them, the JSP workarounds were painful.

FreeMarker, however, treats each of these references the same.

7. Built-in Null And Empty String Handling

Both FreeMarker and JSPs can handle null values in their expression languages, but FreeMarker goes a step further in usability.

The exclamation symbol tells FreeMarker to do automatic null and empty string checking on the attached expression.  If any of customer, invoice, or date are either null or empty string, you’ll just get the label:

Another option is to include your default text after the exclamation.

Again, if any of the values are missing, you get back:

See Handling missing values for more details.

8. Shared Variables

FreeMarker’s shared variables are one of my favourite “hidden” features.  This feature let’s you set values that are automatically added to all templates.

For example you can set your app’s name as a shared variable.

Then access it like any other variable.

I’ve used shared variables in the past to reference resource bundles using expressions like ${i18n.resourceBundle.key}.

The above lines all refer to the the key “CA” inside the countries_en.properties resource bundle.  You’ll need to implement your own TemplateHashModel then add it as a shared variable to achieve this.

9. JSON Support

FreeMarker has built-in JSON support.

Let’s say you have the following JSON stored as a String in variable named user.

Use ?eval to convert it from a string to a JSON object, then use it in expressions as you would any other data.

10. Not Just for the Web

Finally, unlike JSPs, FreeMarker templates can be used outside of a servlet container.  You can use them to generate emails, config files, XML mapping, etc.  You can even use them to generate and save your web pages in a server-side cache.

Try using FreeMarker on your next web project and put the fun back into web development.

 

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.

14 Responses to “10 Reasons to Replace Your JSPs With FreeMarker Templates”

  1. You can also try http://trimou.org/. It’s a Mustache implementation written in Java with some additional features. And the feature set is very similar to freemarker (or velocity) but a little bit “logic-less”.

    And compared to your 10 reasons:
    1. Templates are not compiled to classes as well
    2. There’s a similar concept – TemplateLocator
    3. Template inheritance and partials (aka includes) are supported
    4. No imports as well
    5. No JSP tag support
    6. Should work too
    7. Supports custom MissingValueHandler component
    8. Yes, but we call it “global data” :-)
    9. There’s a built-in JSON extension
    10. The same applies to Trimou :-)

    • Hi Martin,

      That’s awesome, thanks for sharing.

      I took a quick scan of the docs, Trimou looks like a promising alternative. The lambdas and use of the builder pattern are cool. I also kinda like the double brace.

      At this point, I’m pretty invested in FreeMarker, but I’ll take a closer look when time permits.

      Cheers.

  2. What about compared to JSF?

    • That’s a fair question Eric, but I wonder what’s driving our desire to use server-side component frameworks?

      Back when I developed using GWT, I argued that GWT made it easier for back-end Java developers to create rich web applications. Unfortunately, the server-side framework approach doesn’t lend itself to using modern UI frameworks (Bootstrap, AngularJS, NVD3, etc). It doesn’t work well for non-Java developers — like web designers. And it can’t easily leverage templates from other languages/platforms (like WordPress).

      An experienced developer can manage these challenges, but it’s a lot of work without much return.

      These days I much prefer working with a web designer who’s good at HTML, CSS, Javascript, plus a front-end framework. If I’m in rush, I’ll skip the designer and use an off-the-shelf WordPress theme as my Java site template :D

  3. Hi, nice article!

    I’ve used freemarker with spring mvc with sucess, but know on a project using straight MCV with servlets and freemarker i can’t seem to import a external css file on my base.ftl.
    Do you know a working example for this?

    PS: css inline works, but i need it to be external.

  4. At my new job, we are using Freemarker 1.6, but I have to say that it seems to behave in ways that are not documented.
    Maybe you know where it is documented that (apparently) modules can be imported in one FTL but still defined/accessable in other imported (not included) FTL files. I.E. import namespaces sometimes “leak” into an FTL file’s scope (and Im not talking about #GLOBAL nor java defined data model namespace).

  5. Hai

    this is kannathasan .. i want to learn JAVA.. now i am begining java program so can you help me..

Trackbacks/Pingbacks

  1. How To Build Template Driven Java Websites with FreeMarker and RESTEasy - Stack Hunter - January 21, 2014

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

  2. 10 Reasons to Replace Your JSPs With FreeMarker... - January 22, 2014

    […] Still using Java Server Pages? I was too, but a few years ago I ditched them and haven’t looked back since. JSPs are a fine concept, but they take the joy out of web development. For me, it was the little things, like having to breakup my page …  […]

  3. Liferay Spring MVC Freemarker and JSP portlets | GSMBlog - February 18, 2014

    […] really sure if you should be upgrading your portlets or not, I highly recommend reading 10 reasons to replace your JSPs with Freemarker templates on the Stack Hunter blog. Finally, if you are extending a legacy portlet that uses JSP, and you […]

  4. Liferay Spring MVC portlets | GSMBlog - March 2, 2014

    […] You can also use Freemarker instead of JSP preferable. If you don’t know why you should read 10 reasons to replace your JSPs with Freemarker templates on the Stack Hunter blog. Finally, your portlets end up much more maintainable simply because there […]

  5. Wer braucht schon JSP — und wer braucht “template engines” | Genug Unfug - July 6, 2014

    […] Javaworld.com bin ich auf diesen Blog gestoßen, der uns nahebringen will, dass wir statt JSP nun eine bestimmte Template Engine vewenden […]