如何验证 Spring Boot Rest 响应?

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

@RestController
@RequestMapping("/example")
public class ExampleController {

    @Autowired
    private ExampleService exampleService;

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

和响应 DTO:

public class ExampleResponse {

    @NotNull
    private String id;

    @NotNull
    private String otherStuff;

    // setters and getters
}

未验证响应正文。我已经用注释了它,但值仍然通过。请求验证效果很好。@Validnull

如何验证响应正文?


答案 1

已实现的响应验证器:

@Aspect
@Component
public class ControllerResponseValidator {

    Logger logger = Logger.getLogger(ControllerResponseValidator.class);

    @Autowired
    private Validator validator;

    @AfterReturning(pointcut = "execution(* com.example.controller.*.*(..))", returning = "result")
    public void validateResponse(JoinPoint joinPoint, Object result) {
        validateResponse(result);
    }

    private void validateResponse(Object object) {

        Set<ConstraintViolation<Object>> validationResults = validator.validate(object);

        if (validationResults.size() > 0) {

            StringBuffer sb = new StringBuffer();

            for (ConstraintViolation<Object> error : validationResults) {
                sb.append(error.getPropertyPath()).append(" - ").append(error.getMessage()).append("\n");
            }

            String msg = sb.toString();
            logger.error(msg);
            throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, msg);
        }
    }
}

答案 2

在 Rest 控制器和必须验证返回对象的方法上使用。例如:@Validated@Valid

休息控制器:

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

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

}

数字孪生类:

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

}

我的返回对象具有空值和 .因此,错误消息将如下所示:TaskDTOdueDaterepeatUntil

{
  "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
}

我希望这有帮助。有关自定义类级别约束的详细信息,请观看此视频


推荐