本文討論Spring中如何保證@RequestBody註解的實體類別中所有參數不為空。它解釋了@RequestBody對於空參數的預設行為,並提供了幾種處理空參數的選項
以確保中的所有參數使用@RequestBody註解的實體類別是非空的,您可以使用javax.validation
套件中的@NotNull
註解。@NotNull
annotation from thejavax.validation
package.
import javax.validation.constraints.NotNull; public class MyEntity { @NotNull private String name; // Other fields }
When the@NotNull
annotation is applied to a field, Spring Validation will automatically check if the field is non-null. If it is null, aConstraintViolationException
will 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@RequestBody
and 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:
@DefaultValue
annotation from thejavax.validation
package.import javax.validation.constraints.DefaultValue; public class MyEntity { @RequestBody private String name; @DefaultValue("unknown") private String description; // Other fields }
In this case, if thedescription
parameter is null in the request, it will be set to "unknown" in the entity class.
Optional
wrapper class from thejava.util
package.import java.util.Optional; public class MyEntity { @RequestBody private String name; private Optional description; // Other fields }
In this case, if thedescription
parameter is null in the request, thedescription
field in the entity class will be set toOptional.empty()
.
BadRequestException
rrreee@NotNull
註解應用於字段,Spring Validation 會自動檢查該字段是否為非空。如果為null,則會拋出
ConstraintViolationException
。
@RequestBody
註解,並且對應的請求參數為null,則實體類別中該欄位將被設定為null。 如何處理請求中部分參數為空的情況帶有@RequestBody的實體類別? 當帶有@RequestBody的實體類別中的某些參數為空時,您有多種選擇來處理這種情況:
javax.validation
套件中的@DefaultValue
註解為null 欄位設定預設值。 rrreee在這種情況下,如果description
請求中的參數為 null,在實體類別中會被設定為「未知」。
java.util
套件中的Optional
包裝類別的實體類別。 rrreee在這種情況下,如果description
參數為null請求時,實體類別中的description
欄位將被設定為Optional.empty()
。
BadRequestException
。以上是Spring中使用@RequestBody註解接收的實體類別中的某些參數為null的詳細內容。更多資訊請關注PHP中文網其他相關文章!