简体   繁体   English

对REST客户端的Spring-MVC验证响应

[英]Spring-MVC Validation response to a REST client

I'm using Spring 3 MVC (No views and Models, only machine interaction), REST API. 我正在使用Spring 3 MVC(没有视图和模型,只有机器交互),REST API。
My Controller performs validation on the input object and may produce several validation errors (eg: "invalid email", "phone umber is missing"). 我的控制器在输入对象上执行验证,并且可能会产生一些验证错误(例如:“无效的电子邮件”,“缺少电话号码”)。
My question is, what is the best way to return several error descriptions in my HTTP response object? 我的问题是,在HTTP响应对象中返回多个错误描述的最佳方法是什么? Assuming that I cant return an "Error Map" as a return type (method already returning a response object or it is void) 假设我无法将“错误映射”作为返回类型返回(方法已返回响应对象,否则为空)

I would recommend populating an object with your error messages mapped to their respective errors. 我建议您使用映射到各自错误的错误消息填充对象。 (For example, {"email" : "A Valid Email Address Must be Provided"}). (例如,{“电子邮件”:“必须提供有效的电子邮件地址”})。

And in the Controller method where you are performing the validation, if you tag the method with @ResponseBody annotation (and make sure that your Spring MVC application is mvc:annotation-driven), then you can just return that object after completing a validation check. 在执行验证的Controller方法中,如果使用@ResponseBody批注标记该方法(并确保您的Spring MVC应用程序是由mvc:annotation驱动的),则只需在完成验证检查后返回该对象即可。 。

By tagging your method with @ResponseBody, Spring 3 will automatically serialize the object to JSON. 通过使用@ResponseBody标记您的方法,Spring 3将自动将该对象序列化为JSON。 Then at your front-end, you can use a simple jQuery call to parse the errors and post error messages accordingly. 然后在您的前端,您可以使用一个简单的jQuery调用来解析错误并相应地发布错误消息。

Here is a good example of how all of this works on Spring 3 blog . 这是Spring 3博客上所有这些工作原理的一个很好的例子。

This may be a bit outdated, but it is better to use Http response codes as much as possible if you are developing strictly REST services. 这可能有些过时,但是如果您正在开发严格的REST服务,则最好尽可能使用Http响应代码。 I would return a 422 with an array of error messages in the body if there are problems with the input. 如果输入有问题,我将返回一个422,其中包含错误消息数组。 If not, I would send back a 200 without anything in the body. 如果没有,我会寄回200,身上没有任何东西。

Also for creating a new record, new mapping etc, I would send back a 201 with the URI reference of the new entity in the Location header. 同样,为了创建新记录,新映射等,我将在Location标头中发送带有新实体的URI引用的201。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM