import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
为什么如果我发送负年龄或空白姓名,@Valid 注释不起作用并且该人保存到数据库?
有以下 JSON 发送到服务器。
{
"name": "",
"age": -30
}
@实体人:
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
@NotEmpty(message = "Name mustn't be empty!")
@Size(min = 2, max = 20, message = "Name must be between 2 and 20 characters long!")
private String name;
@Column(name = "age")
@Min(value = 1, message = "Age must be greater than 0!")
private int age;
控制器方法:
@PostMapping
public ResponseEntity<HttpStatus> create(@RequestBody @Valid Person person, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
StringBuilder errorMsg = new StringBuilder();
List<FieldError> errors = bindingResult.getFieldErrors();
for (FieldError error : errors) {
errorMsg.append(error.getField()).append(" - ").append(error.getDefaultMessage()).append(";");
}
throw new PersonNotCreatedException(errorMsg.toString());
}
personService.savePerson(person);
return ResponseEntity.ok(HttpStatus.OK);
}
org.springframework.validation.BeanPropertyBindingResult:0 个错误
考虑在控制器顶部使用
@Validated
注释以及验证 Maven 依赖项,除非您已经在使用 starter-web 注释:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>