java - Spring Rest Web 服务输入验证

标签 java spring rest spring-mvc restful-url

我有一个 Spring Rest Web 服务。 Controller 类将 HTTP 请求中的参数映射到自定义请求对象。我的请求对象如下所示:

 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 将抛出无效请求异常。

最佳答案

您可以编写自己的自定义 validator 。

@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();
}

还有一个自定义 validator 。

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

关于java - Spring Rest Web 服务输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204359/

相关文章:

php - 使用 PHP 创建 RESTful API 和网站

java - FindBy 在 JPA 中使用外键

java - Spring Maven : Where to place credential properties

java - 到达 Controller 时子类型数据丢失

java - Spring Boot RestTemplate 交换 400 错误请求

api - 我应该为外部服务设置哪个超时?

java - 插入到 hashmap 中,计算 Set 中的重复项?

java - hibernate 映射 : referencing a set of Entities with OneToMany and one Entity of that set with OneToOne

java - 使用 Java 中的 Apache Maths 进行时间序列的简单回归

java - 无法连接到 postgresQL