Spring Form Binding with FreeMarker

04 March 2015

I was using FreeMarker with my previous project as my email templating engine but for now I'm using it for all my views. I will show here the macros that bind a Spring form.

One might wonder why I'm leaving JSP but the whole truth is I'm typing less with FreeMarker. I read this post from stackhunter.com and among the 10 reasons mentioned I like these:

Importing Spring

<#import "/spring.ftl" as spring/> is the import statement to be able to use <@spring> within the view.

Binding your modelAttribute or command

<@spring.bind "form"/> where form is the key to the mapped object exposed by your controller. You can pass the
binded form in your HTTP post within your controller using @ModelAttribute or @Command. Nested fields can be
used to access an object within binded form such as form.object.property.

macro definition
<@spring.message code/> output a string from a resource bundle based on the code parameter
<@spring.messageText code, text/> output a string from a resource bundle based on the code parameter, falling back to the value of the default parameter
<@spring.url relativeUrl/> prefix a relative URL with the application's context root
<@spring.formInput path, attributes, fieldType/> standard input field for gathering user input
<@spring.formHiddenInput path, attributes/> hidden input field for submitting non-user input
<@spring.formPasswordInput path, attributes/> standard input field for gathering passwords. Note that no value will ever be populated in fields of this type
<@spring.formTextarea path, attributes/> large text field for gathering long, freeform text input
<@spring.formSingleSelect path, options, attributes/> drop down box of options allowing a single required value to be selected
<@spring.formMultiSelect path, options, attributes/> a list box of options allowing the user to select 0 or more values
<@spring.formRadioButtons path, options separator, attributes/> a set of radio buttons allowing a single selection to be made from the available choices
<@spring.formCheckboxes path, options, separator, attributes/> a set of checkboxes allowing 0 or more values to be selected
<@spring.formCheckbox path, attributes/> a single checkbox
<@spring.showErrors separator, classOrStyle/> simplified display of validation errors for the bound field

Source: docs.spring.io