Java Spring MVC+;AJAX如何显示错误?
我的spring web应用程序在spring中使用ajax,它通常基于spring提供的演示应用程序: (其他信息:) 在客户端,我有一个表单(JSP): 在服务器端,我有一个验证,如下所示:Java Spring MVC+;AJAX如何显示错误?,java,spring-mvc,validation,Java,Spring Mvc,Validation,我的spring web应用程序在spring中使用ajax,它通常基于spring提供的演示应用程序: (其他信息:) 在客户端,我有一个表单(JSP): 在服务器端,我有一个验证,如下所示: public final class LevelDto extends AbstractDto implements Serializable { private static final long serialVersionUID = 1L; private int id;
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);
}
}
我的问题是,我不知道如何正确绑定收到的错误消息。显然,我可以通过js来实现,但我认为Spring会自动将所有错误消息绑定到视图
非常感谢您的帮助
-Cyril创建AjaxResponse类作为表单字段、状态和描述的容器
class AjaxResponse {
model; //form attribute
status; // OK or ERROR
description; // message description such as error message
}
您可以循环故障验证结果,根据JSON格式的故障验证结果生成AjaxResponse列表,作为控制器操作的响应。谢谢,但这是一个直接的解决方案。我希望仍然有一种方法可以自动配置SpringBind消息+1同样的问题。你有你的解决方案吗?好吧,我放弃了,用了Adi推荐的方法(见接受的答案)
@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"}
class AjaxResponse {
model; //form attribute
status; // OK or ERROR
description; // message description such as error message
}