Monday, March 21, 2011

Spring Web MVC with Content

The idea that sparked me writing the Blossom Module for Magnolia CMS was to bring the CMS and especially the content into Spring Web MVC not the other way around. Controllers should be the building blocks when composing pages. The latest version 1.2.2 brings a small but significant piece to the puzzle. By adding a custom WebArgumentResolver you can add content objects to the argument list in annotated handler methods.

This is an example of a paragraph that displays a contact form where the author that created the page specified which office will be receiving the filled in form. The office is fetched from a database and passed to the view where details such as its address are displayed.

public String contactForm(ModelMap model, Content page, Content paragraph) {
    model.put("office", officeDao.getOfficeById(paragraph.getNodeData("office").getString()));
    return "contactForm";

To enable it you need to add the BlossomWebArgumentResolver to your AnnotationMethodHandlerAdapter.

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="customArgumentResolver">
    <bean class="info.magnolia.module.blossom.web.BlossomWebArgumentResolver" />

BlossomWebArgumentResolver provides support for a few more arguments that is handy to have handed directly to your handler method. They are: AggregationState, WebContext, Context, User and MgnlUser.