【问题标题】:Spring Boot before Put, Post and Delete Validation放置、发布和删除验证之前的 Spring Boot
【发布时间】:2020-02-29 21:24:00
【问题描述】:

我在 Spring Boot 的控制器中创建了 Post、Put 和 Delete 请求。 我在我的模型中添加了验证,还在控制器的方法中添加了@Valid 参数。 我还想为 Post、Put 和 Delete 操作添加什么验证?

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;
}

我的发帖方式是:

@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 方法是:

@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);
    }

【问题讨论】:

    标签: java spring-boot validation post put


    【解决方案1】:

    您的具体问题是什么?

    请参阅以下来源以进一步阅读。

    Validation in Spring Boot

    【讨论】:

    • 在 Put 请求的情况下,它不会更新值。在 Post 请求的情况下,它会失败,因为它要求 id 不为空
    【解决方案2】:

    关于 PUT-update 无法正常工作的问题? 虽然,代码看起来不错。但是如果您使用的是 JPA,请记住 JPA 具有延迟数据写入数据库机制,这意味着它不会立即将数据写入数据库。如果您希望 JPA 立即写入/保存您的数据,那么您将不得不调用 respository.saveAndFlush() - 强制 JPA 在会话中写入所有数据。

    因此,不必在每次保存数据时调用 repository.saveAndFlush(),在这种情况下,您可以简单地返回相同的请求对象“updateEmployee”而不是“emp”对象来更新记录,例如:

    return new ResponseEntity(updateEmployee, HttpStatus.OK);

    POST :您不应该在 private Integer id 上使用“@NotNull(message = "Employee Id can not be null")”,因为您对 POST 和 PUT 方法使用相同的对象,因为 @ Valid 将验证类中的所有字段。

    【讨论】:

      猜你喜欢
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多