【问题标题】:Custom validation with RESTful APIs使用 RESTful API 进行自定义验证
【发布时间】:2017-04-08 09:53:34
【问题描述】:

我是 Java 世界的新手(来自 .Net 背景)。我使用 Jersey 框架创建了一个 RESTful 服务。它有几种方法。以下是客户服务的示例代码 sn-p。我的代码中还有更多服务。

@Path("/CustomerService")
public interface ICustomerService {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/getCustomerInfo")
    Response query(String constraints);

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/getCustomerDetails")
    Response fetchDetails(String customerID);

}

我有一些验证逻辑,我想在每个向客户端公开的 API 上执行这些逻辑。在 C# 世界中,我们可以定义自己的验证逻辑。如下所示,可以在方法或控制器级别应用。

[MyValdationLogic()]

Java 中的等价物是什么?我如何编写可以在该方法的多个位置应用的代码。

另外,我不想让管理员使用该配置。我发现有一种叫做过滤器的东西,但它是在配置文件中配置的。管理员可以禁用它。

【问题讨论】:

标签: java rest validation jersey


【解决方案1】:

您可以创建一个Validator class 并在您的bean 上使用该Validator class 进行验证。虽然,这个过程有点冗长。

以下是这样做的一个例子-

球衣资源

@POST
@Path("/addEmp")
@Produces("text/plain")
public String doOrder(@BeanParam final @Valid Employee emp) {

    // Some implementation here
}

样品豆 - 假设,我想对地址应用验证,即地址或城市或邮政编码必须在那里。

@Address
public final class Employee {

    @FormDataParam("id")
    private String id;

    @FormDataParam("address")
    private String address;

    @FormDataParam("city")
    private String city;

    @FormDataParam("postcode")
    private String postcode;

        // Other member variables

        // Getters and setters

}

地址注释- 定义自定义地址注解

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RUNTIME)
@Constraint(validatedBy = AddressValidator.class)
@Documented
public @interface Address {

    String message() default "Address required";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

验证器类 - 这是包含实际验证逻辑的验证器类 -

public class AddressValidator implements ConstraintValidator<Address, Employee> {

    @Override
    public boolean isValid(Employee emp, ConstraintValidatorContext constraintValidatorContext) {

    // Check for at least one value
    if((emp.getAddress() != null && !emp.getAddress().equals("") ||
            (emp.getCity() != null && !emp.getCity().equals("")) ||
            (emp.getPostcode() != null && !emp.getPostcode().equals("")))) {
        return true;
    }

    return false;
    }
    public void initialize(Address emp) {
          ...
    }
}

通过这种方式,您可以创建可重复使用的Validator class。您可以在Validator class 中直接使用 Employee,而不是直接使用 Object class 或某个父类,然后相应地更改逻辑。

您可以在bean-validation查看更多详情

【讨论】:

    猜你喜欢
    • 2016-03-15
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多