java - 我们可以验证不完整的 DTO 属性吗?
问题描述
我是 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 个数据时,我的邮递员没有结果响应。由于我的邮递员没有响应,如何修复并获得错误响应。
解决方案
不要在 JSON 中使用注释。请改用以下请求正文:
{
"customerCode3": "as@agasdf.com",
"customerCode2": "ds"
}
推荐阅读
- javascript - 在页面上将 php 变量传递给 json 时的安全问题
- wordpress - 多个 WordPress 子目录 AWS Linux/Apache
- java - 带有 Kotlin 数据类的 ArangoDB Java 驱动程序
- python - 无法使用 cx-oracle
- haskell - 如何在 Haskell 中编写一个简单的依赖类型函数?
- amazon-web-services - 使用 Get Request 在 ElasticSearch 中搜索
- ruby - 尝试安装 ruby gem gosu 时出错
- javascript - 如何旋转形状?
- sql - 动态 XML 到 SQL - SQL Server
- wordpress - 自定义 Woocommerce 存档页面 URL ('/page/')