原始类型的 Play Framework Bean 验证

Play Framework Bean Validation of Primitive Types

我正在使用以下 class 来验证此处所述的表单提交:https://www.playframework.com/documentation/2.3.4/JavaForms

public class ExampleForm {
    @Required
    public int height;
    public String payload;
}

当我执行 bindFromRequest() 时,@Required 约束被忽略。但是,当我将原始类型更改为盒装类型时它起作用了:

public class ExampleForm {
    @Required
    public Integer height;
    public String payload;
}

bean 验证是否不适用于原始类型?

解释很简单:数据库允许 NULL 值,而基本类型不允许。由于表单实际上是 UI 和数据库模型之间的某种连接器,因此它需要对象而不是基元。

@Required 检查第一步中 object 是否为 null 且 int 是否为 NOT null。

保持在模型和表单中使用 Integer 而不是 int 的规则,您的验证器将始终按预期工作。