0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring Bootでの@RequestBodyと@Validによるバリデーションまとめ

Last updated at Posted at 2025-04-10

※学習中のため、内容に誤りがあるかもしれません。
今回は@RequestBody@Validの役割に関して簡単にまとめていきます。

@RequestBodyとは?

@RequestBodyは簡単に言うと、受け取ったリクエストのbody部分(JSONなど)を読み取り、
Javaオブジェクトへ変換することができるアノテーションです。

Entityやdtoなどに変換し使用します。

{
    "name": "taro",
    "email": "test@test.com"
}
@Data
public class ContactDto {
    @NotNull
    @Size(min=1, max=40)
    private String name;

    @NotNull
    @Email
    private String email;
}

@Validとは?

@Validはメソッドを実行した際に、バリデーションをかけてくれる処理です
引数として設定しているDTOやEntityのバリデーションアノテーションを有効化してくれる
例(@Email@NotNullなど)

実際のコード例

✖バリデーションが無効になる例

@PostMapping("/")
public void save(@RequestBody ContactDto contact) {
    service.save(contact);
}

〇バリデーションが有効になる例

@PostMapping("/")
public void save(@Valid @RequestBody ContactDto contact) {
    service.save(contact);
}

おわりに

Spring Bootでバリデーションを有効にするためには、@Validを忘れずに付与することが大事です!
つまずいている方の参考になれば幸いです

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?