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

查看:102
本文介绍了如何在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:


  • 对字段进行定期验证,例如检查属性是否为null,检查 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 的表示(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验证的集成在数据访问级别执行验证。验证是否应该序列化过程之前/之后数据库操作之前/之后两者

  2. 如何处理数据完整性验证手动? (即明确地咨询数据库检查数据完整性)或者我们是否应该尝试插入它然后捕获数据库(或DAO)异常? Bean验证与此类验证无关,对吧?

  3. 如果您对JAX-RS / REST和Bean验证有任何经验,如果您让我知道,我会很高兴。使用群组?

  1. Right now I'm performing the validation in the Data Access level, through JPA's integration with Bean Validation. Should the validations be done before/after serializations processes, before/after database operations or both?
  2. How to handle Data Integrity Validations? Manually? (i.e. explicitly consulting the database checking data integrity) Or should we just try to insert it anyway and then catch database (or DAO) exceptions? Bean Validation has nothing to do with this kind of validation, right?
  3. If you have any experience with JAX-RS/REST and Bean Validation I would be glad if you let me know. Using groups?

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

推荐答案

解决方案最终成为杰克逊的 JacksonJaxbJsonProvider 的子类,它实现了JAX-RS MessageBodyReader MessageBodyWriter
我的灵感来自惊人的 dropwizard的方法。在这个提供程序中,我们需要以某种方式注入一个Validator实例(我使用Spring for Injection和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> ,它将每个 InvalidEntityException 映射到正确的HTTP响应中。在我的例子中,我返回了一个Bad Request和一个包含错误描述的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请求中必须为null,但在其他地方为非null。

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- validation.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天全站免登陆