gpt4 book ai didi

java - Spring MVC + Ajax。如何显示错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:23:05 25 4
gpt4 key购买 nike

我的 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;
}

和 Controller

   @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);

}
}

当我向服务器提交不正确的数据时,我发现一切都在正确进行——我的 validator 正在处理数据,而客户端正在接收错误响应;此外,在响应内容中我看到以下内容:

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

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

非常感谢任何帮助。

-西里尔

最佳答案

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

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

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

关于java - Spring MVC + Ajax。如何显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6159640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com