【问题标题】:Validator for MethodArgumentNotValidException only handles constraint of same typeMethodArgumentNotValidException 的验证器仅处理相同类型的约束
【发布时间】:2013-09-07 21:54:06
【问题描述】:

我正在尝试根据我的 bean 上设置的约束来验证我的表单。我使用的 Spring-MVC 版本是 3.2.4。问题是默认的 Spring 验证器不会验证所有约束;只有那些是相同类型的。

我有以下控制器代码:

@Controller
@SessionAttributes()
public class FormSubmitController {

    @RequestMapping(value = "/saveForm", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap saveForm(@Valid @RequestBody Form form, HttpSession session) {
        session.setAttribute("form", form);
        ModelMap map = new ModelMap();
        map.addAttribute("hasErrors", false);
        return map;
    }
}

还有以下 bean:

public class Form implements IForm, Serializable {

    @NotNull(message = "Category should not be empty")
    protected String category;
    @NotNull(message = "Sub-Category should not be empty")
    protected String subCategory;

    @Size(min=0, message="Firstname should not be empty")
    protected String firstName;
    @Size(min=0, message="Lastname should not be empty")
    protected String lastName;

   @Pattern(regexp="^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d$",     message="Date of birth should be in dd-mm-jjjj format")
    protected String dateOfBirth;

    //getters and setters
}

MethodArgumentNotValidException 的处理程序如下所示:

@ControllerAdvice
public class FormExceptionController {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ModelMap     handleMethodArgumentNotValidException(MethodArgumentNotValidException error) {
        List<FieldError> errors = error.getBindingResult().getFieldErrors();
        ModelMap map = new ModelMap();
        ModelMap errorMap = new ModelMap();
        map.addAttribute("hasErrors", true);
        for (FieldError fieldError : errors) {
            errorMap.addAttribute(fieldError.getField(), fieldError.getDefaultMessage());
        }
        map.addAttribute("bindingErrors", errorMap);
        return map;
    }
}

因此,空表单会导致前两条错误消息。 填写的表单的前两个属性会导致第三条和第四条错误消息。

只有当我对我的 bean 上的所有属性使用相同的约束类型(即 NotNull)时,它才会返回所有错误消息。

这里有什么问题?

【问题讨论】:

    标签: java spring validation spring-mvc


    【解决方案1】:

    @Size@Pattern 的验证器默认接受 null 为有效。所以你实际上需要两个注解(@NotNull 和@Pattern/@Size)。这些注释仅触发对非空值的验证,这些验证并不意味着 null 值无效,而这正是 @NotNull 的用途。

    这是假设您使用的是 hibernate-vaildator(因为它是开箱即用的支持验证器)。

    【讨论】:

      猜你喜欢
      • 2013-07-06
      • 2017-08-16
      • 2019-03-23
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 2021-02-04
      相关资源
      最近更新 更多