【问题标题】:Use Spring 3 MVC Annotation Validation with Freemarker将 Spring 3 MVC 注释验证与 Freemarker 一起使用
【发布时间】:2011-09-02 11:44:48
【问题描述】:

我正在使用 Spring 3 MVC 注释验证。我知道如何在 JSP 中做到这一点(在 JSP 中使用 modelAttribute 属性),但我不知道如何在 Freemarker 中应用这种数据绑定。

JSP 等价示例

<c:url var="addUrl" value="/admin/workerAdd" />
<form:form modelAttribute="worker" action="${addUrl}" method="post">
    <p>
 <form:label for="code" path="code">Code</form:label>
     <form:input path="code" readonly="false" />
    </p>
...

控制器示例:

@Controller
@RequestMapping("/admin/*")
public class AdminController {    
    @Autowired
    private CommonService commonService;

    /**
     * For every request for this controller, this will 
     * create a person instance for the form.
     */
    @ModelAttribute
    public Worker newRequest(@RequestParam(required=false) String id) {
        return (id != null ? commonService.getWorkerById(id) : new Worker());
    }

    @RequestMapping(value="/workerAdd", method=RequestMethod.POST)
    public final String performAddUser(@Valid Worker worker, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            return null;
        }

            // Create the worker here.

        return "redirect:/administration/manageUser";
    }

现在我想使用相同的控制器,但视图是由 Freemarker(ftl) 编写的。我下面的 freemarker 中的数据绑定不起作用(这是可以理解的,因为它应该有不同的语法)。我做了一些研究并了解了 FTL 中的命令对象,但我不明白这一点。我认为它应该是一个类似的属性,告诉 Spring 进行绑定,但我仍然没有找到它。

<form id="worker" modelAttribute="worker" action="${rc.getContextUrl('/admin/workerAdd')}" method="post" >          
            <div class="Entry">
            <label for="code">Code</label>
            <input type="text" id="code" name="code" value="${worker.code}" />
            </div>

是否有任何简单的方法可以使这种注释验证方式(以及数据绑定)与 FTL 一起使用?任何帮助将不胜感激。

谢谢,

黄龙

【问题讨论】:

    标签: validation data-binding spring-mvc freemarker spring-3


    【解决方案1】:

    你的 JSP 代码可以在 Freemarker 中重写如下:

    <#import "spring.ftl" as spring />
    ...
    <form id="worker" action="${rc.getContextUrl('/admin/workerAdd')}" method="post" > 
        <p>
            <label for = "code">Code</label>
            <@spring.formInput "worker.code" />
        </p> 
    ...
    

    请注意,Freemarker 的 Spring 库没有 form 的特定元素,因此您需要使用普通的 html form 并将模型属性名称添加到各个字段的路径中。

    另请参阅:

    【讨论】:

    • 成功了,非常感谢!您知道提供完整示例项目的任何其他资源吗?阅读链接时我有点困惑
    • @Hoàng:不。就我个人而言,我必须阅读源代码和测试才能获得它。
    【解决方案2】:

    我想添加以下说明以节省人们一些时间。 在阅读文档时,它说除非您覆盖 @ModelAttribute(value=...),否则 bean 将在您的视图中作为“command”访问。

    对于 Freemarker(用 3.1M1 测试),默认是 className(例如,如果 Command 类名为“Change PasswordCommand”,那么 bean 将绑定到 changePasswordCommand 默认情况下。

    【讨论】:

    • 感谢您的解释。我认为它肯定会帮助其他人:)
    猜你喜欢
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 2013-11-06
    • 2012-09-09
    • 2010-10-04
    • 2011-09-13
    相关资源
    最近更新 更多