你想使用FreeMarker做的最后一件事是將表單域綁定到命令屬性中。在第8章中,你使用JSP的 <spring:bind> 標簽,而在第9.1.6節中,你是使用#springBind Velocity宏來實現這一點的。類似地,Spring提供了一組FreeMarker宏來進行這種綁定。
等價的FreeMarker宏是< @spring.bind>和<@spring.bindEscaped>。例如,程序清單9.4節選了 registerStudent.ftl中的一段,演示了如何使用<@spring.bind>指令將status信息綁定到表單中。
程序清單9.4? 在FreeMarker模板中使用<@spring.bind>
<@spring.bind "command.phone" />
? phone: <input type="text"
????? name="${spring.status.expression}"
??? ??value="${spring.status.value}">
? <font color="#FF0000">${spring.status.errorMessage}</font><br>
????? email: <input type="text"
????? name="${spring.status.expression}"
????? value="${spring.status.value}">
? <font color="#FF0000">${spring.status.errorMessage}</font><br>
你可能已經注意到程序清單9.4和程序清單9.2非常相像。但這里有兩個不同。首先,FreeMarker版中不是使用Velocity的#springBind宏,而是使用< @spring.bind>指令。其次,<@spring.bind>將狀態信息綁定到${spring.status}而不是$ {status}。
正如Sping的Velocity宏,為了使用這些宏,必須設置FreeMarkerViewResolver的exposeMacroHelpers屬性為true:
?
? <bean id="viewResolver" class="org.springframework.
????????? ?web.servlet.view.freemarker.FreeMarkerViewResolver">
? …
??? <property name="exposeSpringMacroHelpers">
????? <value>true</value>
??? </property>
? </bean>
?
最后,你還需要做一件事才能使用FreeMarker宏。在所有需要使用<@spring.bind>和<@spring.bindEscaped>的FreeMarker模板的頂部增加以下一行:
?
? <#import "/spring.ftl" as spring />
?
這一行會在模板中導入Spring的FreeMarker宏。