【问题标题】:Spring Rest Web service input validationSpring Rest Web 服务输入验证
【发布时间】:2015-05-13 01:58:54
【问题描述】:

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

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

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

【问题讨论】:

标签: java spring rest spring-mvc restful-url


【解决方案1】:

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

@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 中阅读更多相关信息

【讨论】:

    猜你喜欢
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    • 2013-06-22
    • 2013-11-12
    • 1970-01-01
    • 2010-11-17
    相关资源
    最近更新 更多