我春天的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同样的问题。你有你的解决方案吗? – 2013-03-28 08:20:25
好吧,我放弃了,并采用了阿迪推荐的方式(查看接受的答案) – 2013-03-28 08:38:16