LoginSignup
2
1

More than 5 years have passed since last update.

ThymeleafでPUTする時 hidden型を使っている

Last updated at Posted at 2019-02-11

ThymeleafでPUTする時は、単純にformメソッドのactionにPUTを指定しているわけではない。

調べた経緯

PUTできるように実装したのに、chromeのdeveloperコンソールでRequest Methodを見ていたところPOSTになっててあれ?ってなったため。。

image.png

From Dataのところをみるとputになっている。
image.png

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タグは、getpostメソッドしかサポートしていない。
そのため、formタグ上はmethod="post"を指定し、hidden型でvalue="put"を指定する方法を取っていると思われる。
結果としてRequest MethodはPOSTだが_methodで指定したメソッドで送信されるためPUTで送信される。調べてみると他のRailsなどのフレームワークでもこのような方法でputを実現しているみたい。

2
1
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
2
1