Spring boot, 如何使用 @Valid 有名单

我正在尝试在项目中验证 Spring Boot. 所以我提出了注释
@NotNull

在实体领域。 在控制器中,我如下检查:


@RequestMapping/value="", method = RequestMethod.POST/
public DataResponse add/@RequestBody @Valid Status status, BindingResult bindingResult/ {
if/bindingResult.hasErrors/// {
return new DataResponse/false, bindingResult.toString///;
}

statusService.add/status/;

return new DataResponse/true, ""/;
}


这项工作。 但是当我进入时
List<status> statuses

, 他不工作。


@RequestMapping/value="/bulk", method = RequestMethod.POST/
public List<dataresponse> bulkAdd/@RequestBody @Valid List<status> statuses, BindingResult bindingResult/ {
// some code here
}


原则上,我想验证验证,如方法 add, 到列表中的每个状态对象 requestbody. 因此,发件人现在将知道哪些对象有错误,并且哪些对象不是。

如何简单快捷地做到这一点?
</status></dataresponse></status>
已邀请:

小明明

赞同来自:

我的直接提议 - 想要另一个鲍勃的名单 POJO. 并将其用作查询正文参数。

在你的例子中。


@RequestMapping/value="/bulk", method = RequestMethod.POST/
public List<dataresponse> bulkAdd/@RequestBody @Valid StatusList statusList, BindingResult bindingResult/ {
// some code here
}


和 StatusList.java 将


@Valid
private List<status> statuses;
//Getter //Setter //Constructors


但我没有尝试。

更新:

接受答案
https://coderoad.ru/17207766/
给出一个很好的解释为什么列表中不支持Bean检查。
</status></dataresponse>

郭文康

赞同来自:

只需用注释勾选控制器 @Validated.

他会扔掉
ConstraintViolationException

, 所以,你可能想要与它进行比较
400: BAD_REQUEST

:


import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice/annotations = Validated.class/
public class ValidatedExceptionHandler {

@ExceptionHandler
public ResponseEntity<object> handle/ConstraintViolationException exception/ {

List<string> errors = exception.getConstraintViolations//
.stream//
.map/this::toString/
.collect/Collectors.toList///;

return new ResponseEntity&lt;&gt;/new ErrorResponseBody/exception.getLocalizedMessage//, errors/,
HttpStatus.BAD_REQUEST/;
}

private String toString/ConstraintViolation<? > violation/ {
return Formatter.format/"{} {}: {}",
violation.getRootBeanClass//.getName//,
violation.getPropertyPath//,
violation.getMessage///;
}

public static class ErrorResponseBody {
private String message;
private List<string> errors;
}
}


</string></string></object>

窦买办

赞同来自:

@RestController
@Validated
@RequestMapping/"/products"/
public class ProductController {
@PostMapping
@Validated/MyGroup.class/
public ResponseEntity<list<product>&gt; createProducts/
@RequestBody List&lt;@Valid Product&gt; products
/ throws Exception {
....
}
}


</list<product>

要回复问题请先登录注册