Spring에서 @RequestBody 주석을 사용하여 수신된 엔터티 클래스의 일부 매개변수가 null입니다.

DDD
풀어 주다: 2024-08-13 16:14:20
원래의
1147명이 탐색했습니다.

이 기사에서는 Spring에서 @RequestBody 주석이 달린 엔터티 클래스의 모든 매개 변수가 null이 아닌지 확인하는 방법에 대해 설명합니다. null 매개변수에 대한 @RequestBody의 기본 동작을 설명하고 null 매개변수를 처리하기 위한 여러 옵션을 제공합니다. @RequestBody 주석이 달린 엔터티 클래스가 null이 아닌 경우 javax.validation 패키지의 @NotNull 주석을 사용할 수 있습니다.

<code class="java">import javax.validation.constraints.NotNull;

public class MyEntity {
    @NotNull
    private String name;
    // Other fields
}</code>
로그인 후 복사
@NotNull 주석이 필드에 적용되면 Spring Validation은 필드가 null이 아닌지 자동으로 확인합니다. null인 경우 ConstraintViolationException이 발생합니다.

Spring에서 @RequestBody 주석을 사용하여 수신된 엔터티 클래스의 일부 매개변수가 null입니다.@RequestBody는 Null 매개변수를 어떻게 처리합니까?

기본적으로 @RequestBody는 null 값을 엔터티 클래스의 기본이 아닌 필드에 바인딩합니다. . 예를 들어 @RequestBody 주석이 달린 필드가 있고 해당 요청 매개변수가 null인 경우 해당 필드는 엔터티 클래스에서 null로 설정됩니다.

일부에서 Null 매개변수를 처리하는 방법 @RequestBody가 포함된 엔터티 클래스?@NotNull annotation from the javax.validation package.

<code class="java">import javax.validation.constraints.DefaultValue;

public class MyEntity {
    @RequestBody
    private String name;
    @DefaultValue("unknown")
    private String description;
    // Other fields
}</code>
로그인 후 복사

When the @NotNull annotation is applied to a field, Spring Validation will automatically check if the field is non-null. If it is null, a ConstraintViolationException will be thrown.

How Does @RequestBody Handle Null Parameters?

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 @RequestBody and the corresponding request parameter is null, the field will be set to null in the entity class.

How to Handle Null Parameters in Part of an Entity Class with @RequestBody?

You have several options to handle the situation when some parameters in an entity class with @RequestBody are null:

  1. Use default values: You can provide default values for null fields by using the @DefaultValue annotation from the javax.validation package.
<code class="java">import java.util.Optional;

public class MyEntity {
    @RequestBody
    private String name;
    private Optional<String> description;
    // Other fields
}</code>
로그인 후 복사

In this case, if the description parameter is null in the request, it will be set to "unknown" in the entity class.

  1. Use optional fields: You can declare optional fields in the entity class using the Optional wrapper class from the java.util package.
rrreee

In this case, if the description parameter is null in the request, the description field in the entity class will be set to Optional.empty().

  1. Custom handling: You can also write custom code in the controller method to handle null parameters. For example, you could throw a BadRequestException
  2. @RequestBody가 포함된 엔터티 클래스의 일부 매개변수가 null인 경우 상황을 처리할 수 있는 여러 가지 옵션이 있습니다.
  1. 기본값 사용: 제공할 수 있습니다. javax.validation 패키지의 @DefaultValue 주석을 사용하여 null 필드의 기본값을 사용하세요.🎜🎜rrreee🎜이 경우 description 요청에서 매개변수가 null이면 엔터티 클래스에서 "알 수 없음"으로 설정됩니다.🎜
    1. 선택 필드 사용: java.util 패키지의 Optional 래퍼 클래스를 사용하는 엔터티 클래스입니다.🎜🎜rrreee🎜이 경우 description 매개변수가 null인 경우 요청 시 엔터티 클래스의 description 필드는 Optional.empty()로 설정됩니다.🎜
      1. Custom 처리: 컨트롤러 메서드에 사용자 정의 코드를 작성하여 null 매개변수를 처리할 수도 있습니다. 예를 들어 필수 매개변수 중 하나라도 null인 경우 BadRequestException이 발생할 수 있습니다.🎜🎜

위 내용은 Spring에서 @RequestBody 주석을 사용하여 수신된 엔터티 클래스의 일부 매개변수가 null입니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!