【问题标题】:can we validate incomplete DTO property?我们可以验证不完整的 DTO 属性吗?
【发布时间】:2021-10-24 20:42:56
【问题描述】:

我是 spring-boot 的新手,我正在尝试创建如下所示的验证自定义。

@ControllerAdvice
@RestController
public class SpecificResponse extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
            HttpHeaders headers,
            HttpStatus status, WebRequest request) {
            logger.info("1");
            List<String> errors = new ArrayList<String>();
            // String coba = requestContext.getInfo();
            for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            errors.add(error.getField() + ": " + error.getDefaultMessage());
            }
            for (ObjectError error : ex.getBindingResult().getGlobalErrors()) {
            errors.add(error.getObjectName() + ": " + error.getDefaultMessage());
            }
            ApiError apiError = new ApiError();
            apiError.setResponseCode("99");
            apiError.setResponseDesc(ex.getBindingResult().getFieldValue("field") + " Failed");
            apiError.setResponseError(errors.toString());
            return handleExceptionInternal(
                    ex, apiError, headers,HttpStatus.BAD_REQUEST, request);
        
        }
}

下面是我的 DTO 类

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.NotFound;
import lombok.Data;
@Data
public class LiteTimeCreateDTO {
    @NotNull
    @NotEmpty(message = "Customer Code is required")
    @NotFound
    @NotBlank
    private String customerCode;
     
    @NotNull
    @NotEmpty(message = "Customer Code2 is required")
    @NotFound
    @NotBlank
    private String customerCode2;
    
    @Email
    private String customerCode3;
}

下面是邮递员寄来的我的物品

{
    // "customerCode": "as",
    "customerCode3": "as@agasdf.com",
    "customerCode2" : "ds"
}

下面是我在控制器中的端点

@GetMapping("")
public ResponseEntity<ApiSuccess> getData( @Valid @RequestBody(required = true) LiteTimeCreateDTO liteTimeCreateDTO,  @RequestHeader(value = "User-Access") String header,  BindingResult result){
      ApiSuccess dataError = new ApiSuccess();
      dataError.setResponseCode("00");
      dataError.setResponseDesc("Get Lite Time Success");
//    dataError.setResponseData(datas);
      return new ResponseEntity<ApiSuccess>(dataError, HttpStatus.CREATED);
}

一切都很好,只是我很好奇如何验证发送的dto不完整?当我只发送 2 个数据时,我的邮递员没有结果响应。由于我的邮递员没有响应,如何修复并获得错误响应。

【问题讨论】:

  • 您能否添加代码来定义您尝试验证 DTO 的控制器的端点?谢谢!
  • 我已经添加了我的控制器。谢谢
  • 你的项目中有spring-boot-starter-validation 依赖吗?
  • 是的,我有它,当我发送 3 个对象时,此验证工作正常,但如果我们只发送 2 个对象,它将没有响应
  • “当我发送 3 个对象时验证工作正常”是什么意思?如果您发送"customerCode": "",它是否会引发有关无效 DTO 的任何错误?

标签: java spring spring-boot hibernate


【解决方案1】:

不要在 JSON 中使用 cmets。请改用以下请求正文:

{
    "customerCode3": "as@agasdf.com",
    "customerCode2": "ds"
}

【讨论】:

  • 哇,效果很好。非常感谢先生
【解决方案2】:

JSON 只是数据,如果您包含评论,那么它也是数据。

您可以有一个名为“_comment”(或其他名称)的指定数据元素,使用 JSON 数据的应用程序应忽略该数据元素。

您可能会更好地在生成/接收 JSON 的过程中添加注释,因为他们应该提前知道 JSON 数据将是什么,或者至少知道它的结构。

【讨论】:

    猜你喜欢
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    相关资源
    最近更新 更多