如何验证Spring Boot Rest响应?

时间:2017-09-14 08:17:45

标签: java spring validation spring-boot spring-rest

我使用Spring Boot Rest实现了控制器:

public class ExampleResponse {

    @NotNull
    private String id;

    @NotNull
    private String otherStuff;

    // setters and getters
}

并回复DTO:

@Valid

未验证响应正文。我已使用null对其进行了注释,但{{1}}值仍然通过。请求验证效果很好。

如何验证响应正文?

5 个答案:

答案 0 :(得分:3)

已实施响应验证器:

<?php if(isset($_POST('submit'))){

    $sql = "select * from database_table WHERE field_name_to_search = 
        $_POST('field_name_to_search')";
}
 ?>

答案 1 :(得分:2)

在 Rest Controller 上使用 @Validated,在必须验证返回对象的方法上使用 @Valid。例如:

RestController:

@RestController
@RequestMapping("/tasks")
@Validated
public class TaskController {

    @GetMapping("/{taskId}")
    @Valid
    public TaskDTO getTask(@PathVariable UUID taskId) {
        return convertToDto(taskService.findById(taskId));
    }  

}

DTO 类:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ValidTaskDTO
public class TaskDTO {

    @FutureOrPresent
    @NotNull
    private ZonedDateTime dueDate;

    @NotBlank(message = "Title cannot be null or blank")
    private String title;

    private String description;

    @NotNull
    private RecurrenceType recurrenceType;

    @Future
    @NotNull
    private ZonedDateTime repeatUntil;

}

我的返回对象 TaskDTO 为空 dueDaterepeatUntil。所以错误信息如下所示:

{
  "timestamp": "2021-01-20T11:09:37.303929",
  "status": 400,
  "error": "Bad Request",
  "message": "getTask.<return value>.dueDate: must not be null, getTask.<return value>.repeatUntil: must not be null",
  "path": null
}

我希望这会有所帮助。有关自定义类级别约束的详细信息,请查看 this video

答案 2 :(得分:0)

您不应该将其注释为以下代码段吗?

 public @ResponseBody ExampleResponse getExample(@NotNull @PathVariable("id") String id) {
        return exampleService.getExample(id);
    }

答案 3 :(得分:0)

您可以添加&#34; @Validated @ ResponseBody&#34;注释

public @Validated @ResponseBody getExample(@NotNull @PathVariable("id") String id) {

答案 4 :(得分:0)

您期望发生什么?我认为你应该考虑的事情很少。

  1. 如果一个对象必须真的没有值为null的字段,那么当对象保存到您的存储库时(您喜欢哪种类型),您应该验证这一点。然后,如果你的服务返回一些东西,你知道它已经有效,如果它什么也没有返回;您可以为客户端返回正确的状态代码和消息(4xx / 5xx)。您还可以将特定异常映射到某种类型的status code,这样您就可以抛出代码中的异常,并让它们被spring-boot中的默认异常处理程序捕获和处理

  2. 如果您的字段可以是null,但您希望在序列化中省略它们,则可以使用jackson annotations@JsonInclude(JsonInclude.Include.NON_NULL)只会序列化响应中的非空值。