【问题标题】:Spring MVC + Ajax. How to display errors?Spring MVC + Ajax。如何显示错误?
【发布时间】:2011-09-03 19:36:12
【问题描述】:

我的 Spring Web 应用程序使用 ajax 和 spring,它通常基于 spring 提供的演示应用程序:

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

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

<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方法提交表单到服务器:

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

在服务器端,我有如下所示的验证:

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 是自动将所有错误消息绑定到视图。

非常感谢任何帮助。

-西里尔

【问题讨论】:

  • +1 同样的问题。你找到解决方案了吗?
  • 好吧,我放弃了,使用了阿迪推荐的方式(见接受的答案)

标签: java spring-mvc validation


【解决方案1】:

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

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

您可以循环失败验证结果,根据 JSON 格式的失败验证结果生成 AjaxResponse 列表作为控制器操作的响应。

【讨论】:

  • 谢谢,但这是一个直接的解决方案。我希望仍然存在一种自动配置spring绑定消息的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-07
  • 2017-04-09
  • 1970-01-01
  • 2014-03-28
  • 2012-05-17
  • 1970-01-01
相关资源
最近更新 更多