이 기사에서는 Spring에서 @RequestBody 주석이 달린 엔터티 클래스의 모든 매개 변수가 null이 아닌지 확인하는 방법에 대해 설명합니다. null 매개변수에 대한 @RequestBody의 기본 동작을 설명하고 null 매개변수를 처리하기 위한 여러 옵션을 제공합니다. @RequestBody 주석이 달린 엔터티 클래스가 null이 아닌 경우
javax.validation패키지의@NotNull주석을 사용할 수 있습니다.import javax.validation.constraints.NotNull; public class MyEntity { @NotNull private String name; // Other fields }
@NotNull주석이 필드에 적용되면 Spring Validation은 필드가 null이 아닌지 자동으로 확인합니다. null인 경우
ConstraintViolationException이 발생합니다.
@RequestBody는 Null 매개변수를 어떻게 처리합니까?
@RequestBody주석이 달린 필드가 있고 해당 요청 매개변수가 null인 경우 해당 필드는 엔터티 클래스에서 null로 설정됩니다.일부에서 Null 매개변수를 처리하는 방법 @RequestBody가 포함된 엔터티 클래스?@NotNullannotation from thejavax.validationpackage.
import javax.validation.constraints.DefaultValue; public class MyEntity { @RequestBody private String name; @DefaultValue("unknown") private String description; // Other fields }
When the@NotNullannotation is applied to a field, Spring Validation will automatically check if the field is non-null. If it is null, aConstraintViolationExceptionwill be thrown.
By default, @RequestBody will bind a null value to a non-primitive field in the entity class. For example, if you have a field annotated with@RequestBodyand the corresponding request parameter is null, the field will be set to null in the entity class.
You have several options to handle the situation when some parameters in an entity class with @RequestBody are null:
@DefaultValueannotation from thejavax.validationpackage.import java.util.Optional; public class MyEntity { @RequestBody private String name; private Optional description; // Other fields }
In this case, if thedescriptionparameter is null in the request, it will be set to "unknown" in the entity class.
Optionalwrapper class from thejava.utilpackage.In this case, if thedescriptionparameter is null in the request, thedescriptionfield in the entity class will be set toOptional.empty().
BadRequestExceptionjavax.validation패키지의@DefaultValue주석을 사용하여 null 필드의 기본값을 사용하세요.rrreee이 경우description요청에서 매개변수가 null이면 엔터티 클래스에서 "알 수 없음"으로 설정됩니다.
java.util패키지의Optional래퍼 클래스를 사용하는 엔터티 클래스입니다.rrreee이 경우description매개변수가 null인 경우 요청 시 엔터티 클래스의description필드는Optional.empty()로 설정됩니다.
BadRequestException이 발생할 수 있습니다.위 내용은 Spring에서 @RequestBody 주석을 사용하여 수신된 엔터티 클래스의 일부 매개변수가 null입니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!