java - @ValidateOnExecution 什么时候应该与 Jersey 一起使用?

标签 java validation rest jersey

我无法理解 @ValidateOnExecution 注释的本质。有人可以解释一下它的用例吗?

根据 jersey 的文档,资源方法的约束会自动验证。此代码片段来自jersey's example .

@GET
@NotNull
@HasId
public List<ContactCard> getContacts() {
    return StorageService.findByName("");
}

@GET
@Path("{id}")
@NotNull(message = "{contact.does.not.exist}")
@HasId
public ContactCard getContact(
        @DecimalMin(value = "0", message = "{contact.wrong.id}")
        @PathParam("id") final Long id) {
    return StorageService.get(id);
}

如果约束在 pojo 中,您可以使用 @Valid ( See ) 触发验证。

@Path("/")
class MyResourceClass {

@POST
@Consumes("application/xml")
public void registerUser(@Valid User user) {
    ...
}
}

那么@ValidateOnExecution 除了显式关闭验证之外还有什么用?

最佳答案

根据 Jersey latest documentation @ValidateOnExecution 注释应该用于下一个目的:

According to Bean Validation specification, validation is enabled by default only for the so called constrained methods. Getter methods as defined by the Java Beans specification are not constrained methods, so they will not be validated by default. The special annotation @ValidateOnExecution can be used to selectively enable and disable validation. For example, you can enable validation on method getEmail shown in Example

@Path("/")
class MyResourceClass {

    @Email
    @ValidateOnExecution
    public String getEmail() {
        return email;
    }
    ...
}

The default value for the type attribute of @ValidateOnExecution is IMPLICIT which results in method getEmail being validated.

因此 @ValidateOnExecution 也可以至少用于启用 getter 方法的验证。

关于java - @ValidateOnExecution 什么时候应该与 Jersey 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30300503/

相关文章:

javascript - 在 Node.js + MongoDB 中使用 REST API 插入和查询 JSON 数据

java - 如何同时运行两个代码段: one returns a String the other returns void

java - 如何通过 api url 索引使用 recyclerview 实现分页

java - 通过枚举方式的单例是惰性初始化的吗?

php - Zend Framework 2 自定义表单验证器

java - 如果正文中传递的 id 不存在/无效,请更正 http 错误代码?

java - 通过 eclipse 启动 jsp 程序时 Tomcat 8 端口问题

javascript - AngularJS表单向导验证

javascript - 如何在js中的一个函数中验证多个字段

java - 在 restful web 服务中访问 HttpServletRequest 对象