使用注释将Map作为请求参数进行Spring验证

时间:2017-08-28 14:09:43

标签: java spring validation spring-mvc

我使用javax.validation.constraints注释来验证请求参数。我需要验证电子邮件,以便我创建了一个注释@EmailValid,下面提供了一个代码段:

@Email(message = "Please provide a valid email address")
@Pattern(regexp = ".+@.+\\..+", message = "Please provide a valid email address")
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented
public @interface EmailValid {
    String message() default "Please provide a valid email address";

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

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

但它仅适用于单个字符串字段,例如:

@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "/sendEmail", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ResponseVO> sendEmail(@EmailValid String email) {
        // some code for sending email
    }

我需要的是验证电子邮件地图。我有一张地图Map<String, String> users,其中key为userId,value为电子邮件。所以我在我的控制器中有这样的方法:

@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "/sendEmails", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ResponseVO> sendEmails(Map<String, String> users) {
        // some code for sending email
    }

问题是如何使用我的注释@EmailValid和其他javax.validation.constraints注释验证地图值?

1 个答案:

答案 0 :(得分:3)

您必须实施如下的自定义验证。

首先更改您的EmailValid.java文件。

@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = { EmailValidCheck.class })
@Documented
public @interface EmailValid {
    String message() default "Please provide a valid email address";

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

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

现在实现此ConstraintValidator,如下所示。

public class EmailValidCheck extends ABaseController implements
        ConstraintValidator<EmailValid, Map<String,String>> {
    @Override
    public void initialize(EmailValid constraintAnnotation) {
    }

    @Override
    public boolean isValid(Map<String,String> mapOfEmail,
            ConstraintValidatorContext cvc) {
            //Implement Email Validation Login Here.
    }       
}

更改您的控制器,如下所示。

@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "/sendEmails", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ResponseVO> sendEmails(@EmailValid Map<String, String> users) {
        // some code for sending email
    }