Spring mvc使用@RequestBody验证原语不起作用

时间:2018-02-13 15:51:12

标签: java spring spring-mvc

我正在尝试验证我从邮寄申请机构收到的电子邮件,但它不起作用!

@RequestMapping(value = "myservice/emails", method = RequestMethod.POST)
public String requestFoo(@RequestBody @Email String email) {
    return email;
}

当我发送一个不符合电子邮件正则表达式的字符串的请求时,执行该函数并收到200状态代码。

即使添加@Valid注释,结果也始终相同。

@RequestMapping(value = "myservice/emails", method = RequestMethod.POST)
public String testValidation(@Valid @RequestBody @Email String email) {
    return email;
}

1 个答案:

答案 0 :(得分:0)

从Spring 3.2开始@RequestBody方法参数后面可能跟有Errors对象,因此允许在同一@RequestMapping中处理验证错误:

@RequestMapping(value = "myservice/emails", method = RequestMethod.POST)
public ResponseEntity<String> testValidation(@Valid @RequestBody @Email String email, Errors errors) {
  if (errors.hasErrors()) {
  return ResponseEntity.badRequest().body(ValidationErrorBuilder.fromBindingErrors(errors));
        }
    return email;
}

创建自定义验证器:

public class ValidationErrorBuilder {

    public static ValidationError fromBindingErrors(Errors errors) {
        ValidationError error = new ValidationError("Validation failed. " + errors.getErrorCount() + " error(s)");
        for (ObjectError objectError : errors.getAllErrors()) {
            error.addValidationError(objectError.getDefaultMessage());
        }
        return error;
    }
}