posts - 14, comments - 0, trackbacks - 0, articles - 0

在FreeMarker中绑定表单域

Posted on 2007-01-11 00:04 忆了又忆 阅读(2063) 评论(0)  编辑  收藏

你想使用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>

<@spring.bind "command.email" />

      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宏。