Wednesday, 13 May 2009

MVC in a Java world

I've been having a play with the Java vevrsion of the Google App Engine. As I said the other day, it has been interesting coming back to Java after being in a C# land for such a long time.

Coming from C#, and particularly ASP.NET MVC, I've been looking for an equivalent in the Java world. It seems that Spring is a common choice, although there appears to be a lot to learn, and what I have learnt doesn't fit my mindset. That might be because I'm still getting to grips with the Java-WayTM. In particular coming from IIS and virtual directories to application servers and servlets.

So after not really finding what I was looking for, I thought I'd do something simple from scratch, so I grabbed hold of a template engine that I quite liked the look of, called FreeMarker. It was pretty straight forward to get my servlet to render using FreeMarker:


// Create the data for the view
Map root = new HashMap();
root.put("title", "FreeMarker Template Test - no JSP, oh yeah!");
// Grab the template
Template template = config.getTemplate("test.ftl");
// Write out the template
Writer out = response.getWriter();
template.process(root, out);

Note - The config object is an instance of freemarker.template.Configuration, which needs to be setup to enable the loading of your templates, this is pretty boring so I've ommitted it, you can find out about in the FreeMarker docs.

This bit of code is obviously useless without a template, so here it is:


<html>
  <head>
    <title>${title}</title>
  </head>
  <body>
    <h1>${title}</h1>
    <p>Hello, World!</p>
  </body>
</html>

This will produce the obvious, replacing ${title} with the string we specified in our servlet code, in this case "FreeMarker Template Test - no JSP, oh yeah!".

To deploy this I had to put the freemarker.jar in the WEB-INF/lib directory, and the test.ftl template was in a views subdirectory of the WAR.

No comments:

Post a Comment