ThymeleafでPUTする時 hidden型を使っている
ThymeleafでPUTする時は、単純にformメソッドのactionにPUTを指定しているわけではない。
調べた経緯
PUTできるように実装したのに、chromeのdeveloperコンソールでRequest Methodを見ていたところPOST
になっててあれ?ってなったため。。
Thmeleafのソースがどのように展開されているかをみる
formタグのactionにはpost
を指定した上で、hidden型を使って、putを実現していることがソースを見るとわかる。
・hidden型とは
https://developer.mozilla.org/ja/docs/Web/HTML/Element/Input/hidden
もともとフォームに表示させずに値を送信したいときなどに使うもの。
- Thymeleafのコード
sample.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv='Content-type' content='text/html; charset=utf-8' />
<title>test</title>
</head>
<body>
<!-- ここに注目 -->
<form th:action="@{/user}" th:method="put">
<input class="btn btn-default btn-xs" type="submit" value="更新" />
</form>
<!-- ここに注目 -->
</body>
</html>
- 画面に表示されたソースのコード(thymeleaf展開後)
sample.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-type' content='text/html; charset=utf-8' />
<title>test</title>
</head>
<body>
<!-- ここに注目 -->
<form action="/user" method="post">
<input type="hidden" name="_method" value="put"/>
<input class="btn btn-default btn-xs" type="submit" value="更新" />
</form>
<!-- ここに注目 -->
</body>
</html>
理由
formタグは、get
とpost
メソッドしかサポートしていない。
そのため、formタグ上はmethod="post"
を指定し、hidden型でvalue="put"
を指定する方法を取っていると思われる。
結果としてRequest MethodはPOST
だが_method
で指定したメソッドで送信されるためPUT
で送信される。調べてみると他のRailsなどのフレームワークでもこのような方法でputを実現しているみたい。
Author And Source
この問題について(ThymeleafでPUTする時 hidden型を使っている), 我々は、より多くの情報をここで見つけました https://qiita.com/yukiyoshimura/items/a4a4b35a3abbb5caa9f4著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .