java - 如何在 Spring Boot 中对 POST 、 PUT 、 DELETE 执行不同的验证
问题描述
I am trying to validate Employee Request and the validations should be different for post method,put method and delete method
public class Employee {
@NotNull(message = "Employee Id can not be null")
private Integer id;
@Min(value = 2000, message = "Salary can not be less than 2000")
@Max(value = 50000, message = "Salary can not be greater than 50000")
private Integer salary;
@NotNull(message = "designation can not be null")
private String designation;
}
For post method want to validate all the fields present in the request
@PostMapping("/employees")
public ResponseEntity<Void> addEmployee(@Valid @RequestBody Employee newEmployee) {
Employee emp= service.addEmployee(newEmployee);
if (emp== null) {
return ResponseEntity.noContent().build();
}
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
对于我的 put 方法,我只想验证 Salary 字段,其余字段不会被验证
@PutMapping("/employees/{id}")
public ResponseEntity<Vehicle> updateEmployee(@Valid @RequestBody Employee updateEmployee) {
Employee emp= service.EmployeeById(updateEmployee.getId());
if (null == emp) {
return new ResponseEntity<Employee>(HttpStatus.NOT_FOUND);
}
emp.setSalary(updateEmployee.getSalary());
emp.setDesignation(updateEmployee.getDesignation());
service.updateEmployee(emp);
return new ResponseEntity<Employee>(emp, HttpStatus.OK);
}
对于删除,我不想执行任何验证
@DeleteMapping("/employees/{id}")
public ResponseEntity<Employee> deleteEmployee(@Valid @PathVariable int id) {
Employee emp = service.getEmployeeById(id);
if (null == employee) {
return new ResponseEntity<Employee>(HttpStatus.FOUND);
}
service.deleteEmployee(id);
return new ResponseEntity<Employee>(HttpStatus.NO_CONTENT);
}
但是如果我使用@Valid,所有的方法都会得到所有字段的验证。
解决方案
实现此目的的一种方法是使用@Validated
库org.springframework.validation
而不是@Valid
在方法参数中使用注释。
这样,您可以根据模型中的要求对约束进行分组(第一组用于 POST 方法,第二组用于 PUT 方法等)在模型中,您需要使用groups
属性并指定您想要的组的名称绑定。
有详细的解释,并给出了使用的示例代码:这里。
推荐阅读
- javascript - 更改 options-reading.php 中的输入“min”属性
- excel - VBA循环直到0或“”
- datetime - GQL 函数和数据存储日期时间查询问题
- homebrew - MacOS - 无法安装 brew
- python - Python Pandas Dataframe 按 Timedelta 列值删除行
- python - django-push-notification 401 未经授权
- ruby-on-rails - ActiveRecord PostgreSQL 查询数组
- java - Gradle:具有配置文件支持的多项目构建的多个 application.properties
- arrays - .get 调用后反应转换 JSON 数组
- python - 如何在每个请求上使用 selenium python 轮换各种用户代理