validation - 将 Spring 3 MVC 注释验证与 Freemarker 结合使用

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

我正在使用 Spring 3 MVC 注释验证。我知道如何在 JSP 中执行此操作(在 JSP 中使用 modelAttribute 属性),但我不知道如何在 Freemarker 中应用这种数据绑定(bind)。

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 示例:

@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";
    }

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

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

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

谢谢,

黄龙

最佳答案

我想添加以下说明以节省人们一些时间。 在阅读文档时,它说除非您重写 @ModelAttribute(value=...),否则将在您的 View 中将 bean 作为“命令”进行访问。

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

关于validation - 将 Spring 3 MVC 注释验证与 Freemarker 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6137153/

相关文章:

validation - p :commandButton doesn't call action on validation error

ruby-on-rails - 验证外键是否存在,如果不为零

c# - 允许 1 个字符和空格的正则表达式字符串

javascript - AngularJs 从 Controller 返回 HTML

spring-mvc - JsonMappingException : Current token not START_OBJECT (needed to unwrap root name 'Transaction[]' ), 但 START_ARRAY

spring - 多个应用程序上下文,多个调度程序 servlet?

javascript - Jquery 下拉列表日期验证

c# - 有没有办法将 2 个(或更多)WPF 项绑定(bind)到 C# 中的单个属性?

typescript - 如何将 ionic3-star-rating 动态值绑定(bind)到 ionic 中的数据对象

java - "No Session found for current thread"更改 session 访问方法后