ThymeleafでJavascriptのonclickでフォームの送信をする方法

ThymeleafでJavascriptのonclickでフォームの送信をする方法

ThymeleafでJavaScriptのonclickイベントを使ってフォームを送信する方法について説明します。
以下は、そのための基本的なサンプルコードです。

HTMLファイル (Thymeleafテンプレート)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>フォーム送信</title>
  <script type="text/javascript">
    function submitForm() {
      document.getElementById("myForm").submit();
    }
  </script>
</head>
<body>
  <form id="myForm" th:action="@{/submit}" method="post">
    <input type="text" name="inputField" />
    <button type="button" onclick="submitForm()">送信</button>
  </form>
</body>
</html>

コントローラー (SpringBoot)

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MyController {

  @GetMapping("/form")
  public String showForm() {
    return "form";
  }

  @PostMapping("/submit")
  public ModelAndView submitForm(@RequestParam("inputField") String inputField) {
    // フォームデータを処理するコード
    ModelAndView modelAndView = new ModelAndView("result");
    modelAndView.addObject("inputField", inputField);
    return modelAndView;
  }
}

説明

1. HTMLファイル

  • form要素にはid="myForm"を設定し、th:action="@{/submit}"で送信先を指定します。
  • buttonのtype="button"を指定して、デフォルトの送信動作を防ぎます。

代わりに、onclickイベントでsubmitForm()関数を呼び出します。

  • submitForm()関数は、JavaScriptでdocument.getElementById("myForm").submit()を使ってフォームを送信します。

2. コントローラー

  • showFormメソッドで、フォームを表示するためのThymeleafテンプレートを返します。
  • submitFormメソッドで、フォームから送信されたデータを処理し、結果を表示するための別のビューを返します。

このコードを使えば、ボタンをクリックすることでJavaScriptを介してフォームを送信することができます。