gpt4 book ai didi

java - 如何在对象的数组属性中添加 Rest 验证?

转载 作者:行者123 更新时间:2023-11-30 05:30:23 28 4
gpt4 key购买 nike

我需要验证请求 msisdn 数组类型,我正在使用 Spring Boot 的其余验证以及如何在错误消息中添加该值。

我尝试了自定义验证,但找不到任何数组验证。

期望的错误响应

{
"errors": [
"Invalid msisdn: 0917854*****",
"Invalid msisdn: 0936895*****"
],
"success": false,
}

请求正文

{
"msisdn": ["0917854*****", "0936895*****"],
"message": "test message",
"title": "test title"
}

java对象

public class PushNotif {

//validate this List
private List<String> msisdn;

@NotNull(message = "Message is required")
private String message;

private String title;

public PushNotif(List<String> msisdn, String message, String title) {
this.msisdn = msisdn;
this.message = message;
this.title = title;
}
}

java Controller

@RestController
public class PushController extends BaseController{

@PostMapping(path = "/push")
public ResponseEntity<Object> indexAction(@valid @RequestBody PushNotif pushNotif){

return new ResponseEntity<Object>(null,HttpStatus.ok);
}
}

错误响应处理程序


@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler
{

@Override
@ResponseStatus(HttpStatus.BAD_REQUEST)
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
Map<String, Object> errors = new HashMap<>();
List<String> details = new ArrayList<>();

ex.getBindingResult().getAllErrors().forEach((error) -> {
details.add(error.getDefaultMessage());
});

errors.put("details", details);
errors.put("success", false);
errors.put("traceid", "aksjdhkasjdhs-akjsdjksa-asjkdh");

return new ResponseEntity<>(errors, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

更新:我向我的 java 对象添加了参数约束


@NotNull(message = "msisdn is required")
private List<@NotNull(message = "msisdn is required")
@Pattern(regexp = "^09[0-9]{9}",
message = "Invalid msisdn ${validatedValue}") String> msisdn;

最佳答案

为了验证列表中的值(在本例中值不为 null),您可以在对象引用类型中添加 @NotNull 注释。

private List<@NotNull String> msisdn;

引用文献 Hibernate Validations for Nested Container Elements

关于java - 如何在对象的数组属性中添加 Rest 验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57685477/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com