如果从前端到后端有请求,是否可以在到达后端调用之前操纵请求或数据。我们是否有任何弹簧验证器来检查传入的请求是否正确
答案 0 :(得分:2)
是的,您可以使用拦截器来实现:拦截器用于
使用以下链接获得有关弹簧拦截器的全面指南
资源:https://www.tutorialspoint.com/spring_boot/spring_boot_interceptor.htm
对于您的用例,您应该在拦截器中使用@PostHandle
方法。
答案 1 :(得分:0)
使用适当的验证(NotNull等)创建您希望作为请求的一部分的实体。
@Entity
public class Entity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotBlank(message = "Name is mandatory")
private String name;
// standard constructors / setters / getters / toString
}
在定义请求映射时,添加@Valid注释,如下所示:
@PostMapping("/test")
ResponseEntity<Object> addUser(@Valid @RequestBody Entity entity) {
// persisting the user
return ResponseEntity.ok("User is valid");
}