Tuesday, 25 August 2009

Paying The Bills

A distinct lack of activity on the blogging front lately. This is because I've been (a) moving house and (b) actually enjoying myself at work! ;-)

As Tech Lead on a brand new project, I've been writing a web app using Spring MVC, Freemarker + Hibernate and I thought I would share a few thoughts. I should start by saying that it's been nowhere near as easy as Grails, GSP + GORM, but nonetheless, it's a big improvement on the 'bad old days' of Java web app development.

To be honest, although Spring MVC is both powerful and flexible, I've always found it a little fiddly in the past. However, this time I decided to use annotation-driven controllers and these were way easier to work with than the MultiActionController I've used before. All you need is something like this in your context:
<context:component-scan package="com.royale.sam.web.controller">
And then you can annotate your controller class like this:
@Controller
@RequestMapping(method = RequestMethod.GET)
public class PageController {

...

@RequestMapping(value={"/page.html", "/item.html"})
public ModelAndView pageHandler(HttpServletRequest request, HttpServletResponse response) {
...
}
}
And that's it! Using this technique you can group handler methods in one controller (much like you can in Grails) which makes it easier to reuse domain logic and leads to a well organised application. We found this was particularly useful when implementing handlers for our AJAX functionality.

Freemarker was also pretty good, although - possibly because it's application agnostic - we found that it didn't support a number of features that you take for granted when using JSP. (In fact, I would've used JSP, but requirements dictated that we used a templating language.) For example, we couldn't find an easy + reliable way to get the context path, so we ended up introducing a servlet filter that made this information (and more) available to every page in our app. We also steered clear of using taglibs in our Freemarker templates, preferring to write our own directives.

And Hibernate was Hibernate. Always trickier than you expect to set it up, but once it's done, you generally don't have to worry about it anymore.