首页 > 解决方案 > 如何在 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,所有的方法都会得到所有字段的验证。

标签: javaspring-bootvalidation

解决方案


实现此目的的一种方法是使用@Validatedorg.springframework.validation而不是@Valid在方法参数中使用注释。

这样,您可以根据模型中的要求对约束进行分组(第一组用于 POST 方法,第二组用于 PUT 方法等)在模型中,您需要使用groups属性并指定您想要的组的名称绑定。

有详细的解释,并给出了使用的示例代码:这里


推荐阅读