2011-05-28 63 views
6

我春天的Web应用程序是使用Ajax和春天,它基于一般由弹簧所提供的演示应用程序:Spring MVC + Ajax。如何显示错误?

https://src.springframework.org/svn/spring-samples/mvc-ajax/trunk/ (附加信息:http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/

在客户端我有一个表格(JSP):

$("#createLevel").submit(function() { 
     var level = $(this).serializeObject(); 
     $.postJSON("create.do", level, function(data) { 
      alert(data); 
     }); 
     return false;    
    }); 
01:

<form:form modelAttribute="createLevel" action="createLevel" method="post"> 
    <div class="form-item"> 

    <form:label id="nameLabel" for="name" path="name" cssErrorClass="error">Level Name</form:label><br/> 
    <form:input path="name" /><form:errors path="name" /> 
    </div> 
    <div class="form-item"> 
    <input type="submit" value="Submit"> 
    </div> 
</form:form> 

我通过以下方法JS提交表单到服务器

在服务器端我有一个验证,因为它如下图所示:

public final class LevelDto extends AbstractDto implements Serializable { 
    private static final long serialVersionUID = 1L; 

    private int id; 

    @NotNull 
    @Size(min = 2, max = 30) 
    @LevelExistsConstraint(message = "Level with provided name is exists") 
    private String name; 
    // set; get; 
} 

和控制器

@RequestMapping(value = "/admin/create.do", method = RequestMethod.POST) 
    public @ResponseBody 
Map<String, ? extends Object> createLevel(@RequestBody LevelDto level, 
     HttpServletResponse response) { 
    //JSR-303 
    Set<ConstraintViolation<LevelDto>> failures = validator.validate(level); 

    if (!failures.isEmpty()) { 
     response.setStatus(HttpServletResponse.SC_BAD_REQUEST); 
     return validationMessages(failures); 

    } else { 

     return Collections.singletonMap("id", 10); 

    } 
} 

当我不正确的数据提交给我看所有的东西都正确事情的服务器 - 我的验证器正在处理数据,并且客户端正在收到错误响应;此外,在回复内容我看到以下内容:

{"name":"size must be between 2 and 30"} 

我的问题是,我不知道如何正确绑定收到的错误消息。显然,我可以通过js来完成,但我认为Spring会将所有错误消息自动绑定到视图。

任何帮助真的很感激。

-Cyril

+1

+1同样的问题。你有你的解决方案吗? – 2013-03-28 08:20:25

+0

好吧,我放弃了,并采用了阿迪推荐的方式(查看接受的答案) – 2013-03-28 08:38:16

回答

4

创建AjaxResponse类作为表单字段,状态和描述的容器。

class AjaxResponse { 
    model; //form attribute 
    status; // OK or ERROR 
    description; // message description such as error message 
} 

基于JSON格式为您的控制器动作的响应失败验证结果可以循环的失败验证结果,产生AjaxResponse的名单。

+0

谢谢,但这是一个直接的解决方案。我希望仍然存在一种自动配置弹簧绑定消息的方法 – 2011-05-28 07:36:56