如何处理 REST Web 服务中的资源验证? [英] How to handle Resource validation in REST webservices?

查看:28
本文介绍了如何处理 REST Web 服务中的资源验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring、Jersey 和 Hibernate (JPA) 在 Java 中构建一个 REST Web 服务.

I'm building a REST webservice in Java using Spring, Jersey and Hibernate (JPA).

现在我正在尝试在我的资源中添加对验证的支持.JSR-303(Bean 验证)自然是一个合适的选择(我使用的是 Hibernate Validator,它是 JSR-303 的参考实现).不过,我想先巩固一些概念.

Now I'm trying to add support for validation in my resources. JSR-303 (Bean validation) naturally appeared as a suitable choice (I'm using Hibernate Validator which is the reference implementation of JSR-303). However, I'm trying to consolidate some concepts first.

在我看来,至少有两种可能的验证:

It seems to me that there are at least two kinds of possible validations:

  • 定期验证字段,例如检查属性不为空,检查 String 属性是否是有效的电子邮件,检查 Integer 属性是否大于 10 等.这是按预期工作的.我已经注册了一个 JAX-RS ExceptionMapper,它将 javax.validation.ConstraintViolationException 映射到正确的 HTTP 响应中.
  • 数据完整性验证
  • Regular validation on fields, e.g. check that a property isn't null, check if a String property is a valid e-mail, check if an Integer property is greater than 10, etc. This is working as expected. I've registered a JAX-RS ExceptionMapper which maps javax.validation.ConstraintViolationException's into proper HTTP responses.
  • Data Integrity Validation

我将通过一个示例来解释数据完整性验证"的确切含义.当两个或多个资源之间存在关系时,就会发生这种情况.想象两个资源:一个 Product 和一个 Category.Product Category.当客户端向服务器发送要创建的Product 的表示(POST HTTP 请求)时,它必须通知产品的Category.当然,客户必须事先知道类别.想象一下在 JSON 中是这样的:

I'll explain what I mean exactly by "Data Integrity Validation" with an example. This happens when there are relationships between two or more resources. Imagine two resources: a Product and a Category. A Product has a Category. When the client sends to the server the representation of the Product to create (a POST HTTP request), it must inform the Category of the product. The client must know the categories beforehand, of course. Imagine in JSON something like:

{
   "quantity": "10",
   "state": "PRODUCED",
   "category": {
      "id": "123"
   }
}

嗯,id 为 123 的类别可能不存在.如果我们尝试将其插入数据库,显然我们会得到与外键相关的异常.所以我假设我们必须验证这些问题并向客户端返回正确的消息,就像在常规属性验证中一样.

Well, the category with id 123 might not exist. If we try to insert this into the database, obviously we get a foreign key related exception. So I assume we have to validate these issues and return a proper message to the client, just as in regular property validations.

现在,我的主要问题是:

Now, my main questions are:

  1. 现在我正在通过 JPA 与 Bean Validation 的集成在数据访问级别执行验证.验证应该在序列化过程之前/之后在数据库操作之前/之后还是两者进行?
  2. 如何手动处理数据完整性验证??(即明确咨询数据库检查数据完整性)还是我们应该尝试插入它然后捕获数据库(或 DAO)异常?Bean Validation 和这种验证无关吧?
  3. 如果您对 JAX-RS/REST 和 Bean 验证有任何经验,我会很高兴告诉我.使用群组?

这些问题与 Java 有点相关,但我也希望对这些问题有一些新的看法.一些技术独立的.:)如果您可以为您的 REST Web 服务上的这些问题提供自己的解决方案,那就太好了.

推荐答案

最终解决方案是继承 Jackson 的 JacksonJaxbJsonProvider,它实现了 JAX-RS MessageBodyReaderMessageBodyWriter.我受到了惊人的 dropwizard 的方法.在这个提供程序中,我们需要以某种方式注入一个 Validator 实例(我使用 Spring 进行注入,使用 Hibernate Validator 进行 JSR-303 实现).如果您使用 Hibernate ORM,请不要忘记禁用实体验证,否则您将验证同一个实体两次.不过,这可能是我们想要的.

The solution ended up to be subclassing Jackson's JacksonJaxbJsonProvider which implements a JAX-RS MessageBodyReader and MessageBodyWriter. I was inspired by the amazing dropwizard's approach. In this provider we need to somehow Inject a Validator instance (I used Spring for Injection and Hibernate Validator for JSR-303 implementation). If you use Hibernate ORM don't forget to disable entity validation, otherwise you will be validating the same entity twice. It may be what is desired, though.

然后,在这个子类 MessageBodyReader 中,我验证对象并抛出来自验证器的错误的自定义 InvalidEntityException.我还创建了一个 JAX-RS ExceptionMapper,它将每个 InvalidEntityException 映射到正确的 HTTP 响应中.在我的例子中,我返回了一个错误请求和一个包含错误描述的 JSON 对象.

Then, in this subclassed MessageBodyReader, I validate the object and throw a custom InvalidEntityException with the errors from the validator. I also created a JAX-RS ExceptionMapper<InvalidEntityException> that maps every InvalidEntityException into a proper HTTP response. In my case I returned a Bad Request and a JSON object containing the errors description.

请注意,此 MessageBodyReader 检查 @Valid@Validated 注释.这意味着它正确地支持组.这很重要,因为我们可能不想在整个应用程序中进行相同类型的验证.一个例子是当我们想要进行部分更新(PUT)时.或者,例如,一个 id 属性在 POST 请求中必须为空,但在其他任何地方都非空.

Notice that this MessageBodyReader checks for @Valid and @Validated annotations. This means that it correctly supports groups. This is important because we probably don’t want to do the same kind of validation across our entire application. An example is when we want to do a partial update (PUT). Or, for example, an id property must be null in a POST request but non-null everywhere else.

数据完整性验证尚未完全处理.但我计划捕获数据库异常并将它们转换为我自己的域异常(比如 DataIntegrityException),因为它看起来更高效且与我松散耦合.

Data Integrity Validations aren't completely dealt with yet. But I'm planning to catch database exceptions and converting them to my own domain exceptions (say a DataIntegrityException) as it seems more efficient and loosely coupled to me.

更新:

从 JAX-RS 2 开始,推荐的方法是使用它的 Bean Validation 支持.在这里查看:https://jersey.java.net/documentation/latest/bean-验证.html

Since JAX-RS 2, the recommended way to do this is to use its Bean Validation support. Check here: https://jersey.java.net/documentation/latest/bean-validation.html

这篇关于如何处理 REST Web 服务中的资源验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆