Spring - 验证Integer属性

时间:2017-01-19 18:37:38

标签: spring validation integer notnull

我有实体:

public class User{
   @NotNull
   private Integer age;
} 

在Restcontroller中:

@RestController
public UserController {
 ..... 
} 

我有BindingResult,但是字段时代Spring没有验证。你能告诉我为什么吗?

感谢您的回答。

2 个答案:

答案 0 :(得分:2)

如果您发布的内容类似于代表User类的JSON数据,您可以将注释@Valid与@RequestBody结合使用,以触发注释验证,例如您对@NotNull的注释age财产。然后使用BindingResult,您可以检查实体/数据是否有错误并进行相应处理。

@RestController
public UserController {

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<?> create(@Valid @RequestBody User user, BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            // handle errors
        }
        else {
            // entity/date is valid
        }
    }
}

我确保您的User课程也有@Entity注释。

@Entity
public class User {
    @NotNull
    @Min(18)
    private Integer age;

    public Integer getAge() { return age; }

    public setAge(Integer age) { this.age = age; }
}

您可能希望将属性设置为输出/记录SQL,以便您可以看到正在将约束添加到User表中。

希望这有帮助!

答案 1 :(得分:0)

如果需要,您可以指定默认消息

@NotNull("message": "age: 需要正数")

@Min(value=18, message="age: 正数,需要最小 18")

请使用 dto 的

相关问题