gpt4 book ai didi

Spring - 整数属性的验证

转载 作者:行者123 更新时间:2023-12-02 21:16:46 25 4
gpt4 key购买 nike

我有实体:

public class User{
@NotNull
private Integer age;
}

在休息 Controller 中:

@RestController
public UserController {
.....
}

我有 BindingResult,但字段 Age Spring 未验证。你能告诉我为什么吗?

感谢您的回答。

最佳答案

如果您发布类似代表 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 表中。

希望有帮助!

关于Spring - 整数属性的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41749278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com