【发布时间】:2012-12-31 00:48:22
【问题描述】:
我有以下情况,在我看来我有以下形式:
<form id="readJson" class="readJsonForm" action="<c:url value="/messageconverters/json" />" method="post">
<input id="readJsonSubmit" type="submit" value="Read JSON" />
</form>
与这个form表单的提交事件相关(有class="readJsonForm) 我有如下Jquery回调函数:
$("form.readJsonForm").submit(function() {
// Riferimento all'elemento che ha scatenato l'evento submit (il form)
var form = $(this);
var button = form.children(":first");// Seleziona il bottone submit
// OPERATORE CONDIZIONALE: il form ha classe "invalid" ?
var data = form.hasClass("invalid") ?
"{ \"foo\": \"bar\" }" : // SI: foo = bar
// NO: foo= bar ; fruit = apple
"{ \"foo\": \"bar\", \"fruit\": \"apple\" }";
/* AJAX CALL PARAMETER:
type: Say to the servlet tath the request is a POST HTTP Request
url: The address to which to send the call
data: the content of my data variable
contentType: an object having JSON format
dataType: the type of content returned by the server
*/
$.ajax({
type: "POST",
url: form.attr("action"),
data: data, contentType: "application/json",
dataType: "text",
success: function(text) { // CASO DI SUCCESSO:
/* Passa al metodo il testo ritornato dalla chiamata AJAX ed il
riferimento nel DOM al bottone accanto ala quale mostrare
tale output */
MvcUtil.showSuccessResponse(text, button);
},
error: function(xhr) { // CASO DI ERRORE
MvcUtil.showErrorResponse(xhr.responseText, button);
}
});
return false;
});
因此,这个 Jquery 函数创建了一个新的 JSON 对象,该对象具有以这种方式评估的两个属性(foo 和fruit):
foo = bar
水果 = 苹果
HTTP 请求由我的控制器类的以下方法处理:
/* Metodo che gestisce HTTP Request di tipo POST dirette verso
* l'URL: "/messageconverters/json"
* @param L'oggetto JSON inserito all'interno del campo body dell'HTTP
* su cui viene eseguita una validazione
*
*/
@RequestMapping(value="/json", method=RequestMethod.POST)
public @ResponseBody String readJson(@Valid @RequestBody JavaBean bean) {
return "Read from JSON: " + bean;
}
此方法只是从 HTTP 请求的正文字段中获取 JSON 对象,并使用 Jaxb2RootElementHttpMessageConverter 将其传输到新的 JavaBean 对象中
在我的例子中,JavaBean 对象是一个只有两个属性的对象:foo 和 fruit 以及 getter、setter 和 toString() 方法,如下所示:
@XmlRootElement 公共类 JavaBean {
@NotNull
private String foo;
@NotNull
private String fruit;
public JavaBean() {
}
public JavaBean(String foo, String fruit) {
this.foo = foo;
this.fruit = fruit;
}
// GETTER, SETTER & toString() methods
好的,所以 JSON 对象中的值被放在同名的 JavaBean 对象变量中……这对我来说很清楚。
@Valid注解的规则有点问题。
我的 JavaBean 参数使用 @Valid 注释进行注释,阅读文档我知道这不是 Spring 注释,但这与验证框架 JSR-303 验证 API 相关
我对这个 API 知之甚少,我记得 @Valid 触发了对象字段的验证
但我记得我的对象字段(我在 JavaBeans 对象中的变量)必须使用一些验证注释进行注释,例如 @NotNull 或使用实现我的个人验证器的个人验证 Java 类.
在这种情况下,我什么都没有,我的方法参数上只有 @Valid 注释...
在这种情况下具体做什么?
我唯一能想到的是检查我的 JSON 对象是否正确映射到 JavaBean 对象(如果具有相同的 valorized 属性),例如...如果 JSON 对象只有一个属性 valorized 进入错误...
有人可以帮助我吗?
Tnx 安德烈亚
【问题讨论】:
标签: json spring validation spring-mvc bean-validation