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?

@DeleteMappingでなく@PostMappingを使用する理由

Posted at

簡単なCRUD機能を持つアプリを開発しているとき、レコードの削除のためにContorllerのメソッドに@DeleteMappingアノテーションを使用していましたが、削除が実行されませんでした。その代わりに@PostMappingアノテーションを使用して削除を実行することにしました。
その理由として以下のような点が挙げられます。
HTML のform では method="delete" を直接指定できません。そのため、POST を使いながら DELETE に変換する仕組みを利用します。

解決策:@PostMapping + _method="delete"

<form th:action="@{/delete/{id}(id=${book.id})}" method="post">
    <input type="hidden" name="_method" value="delete"/>
    <button type="submit">削除</button>
</form>

  • method="post" を指定(delete は HTML で直接使えない)。
  • input type="hidden" name="_method" value="delete" を追加することで DELETE に変換。

どっちを使うべき?

  • REST API なら @DeleteMapping が適切。
  • Thymeleaf などのフォームを使う場合 は、@PostMapping を使って _method="delete" で DELETE に変換する
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?