Spring 休息 Web 服务输入验证

Spring Rest Web service input validation

我有一个 Spring 休息网络服务。控制器 class 将 HTTP 请求中的参数映射到自定义请求对象。我的请求对象如下所示:

 public class DMSRequest_global {
     protected String userName = "";
     protected String includeInactiveUsers = "";
     protected String documentType = ""; And the getter and setter of the fields above 
 }

Spring 使用反射将传入请求的值设置为这个 object.My 问题是我们是否可以使用注释或其他东西来验证上面示例中的 documentType 之类的字段只接受可接受值列表中的一个值,例如 {".doc", ".txt",".pdf"} 。如果在请求中发送其他值 spring 将抛出无效请求异常。

您可以编写自己的自定义验证器。

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Contraint(validatedBy = DocumentTypeValidator.class)
@Documented
public @interface ValidDocumentType {

    String message() default "{com.mycompany.constraints.invaliddocument}";

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

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

    String[] value();
}

还有一个自定义验证器。

public class DocumentTypeValidator implements ConstraintValidator<ValidDocumentType, String> {

    private String[] extenstions;

    public void initialize(ValidDocumentType constraintAnnotation) {
        this.extenstions = constraintAnnotation.value();
    }

    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {

        if (object == null)
            return true;

        for(String ext:extenstions) {
            if(object.toLowerCase().matches(ext.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

}

最后,您可以使用自定义注释来注释您的 bean。

@ValidDocumentType({"*.doc", "*.txt","*.pdf"})
protected String documentType = "";

您可以在 post

中阅读更多相关信息