【Spring Boot】1つのformで複数のPOST送信を行う方法
この記事は、1つのフォーム要素に複数のボタンがあってそれぞれ別のPOST送信をしたい場合のコードを解説します。
HTML要素のformaction属性を使うことで複数ボタンでPOSTを振り分けることが出来ます。
form.html
<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>form</title>
<script type="text/javascript"></script>
</head>
<body>
<form method="post">
    <label>
        メッセージ:<input type="text" name="msg1"><br>
    </label>
    <button style="background-color: yellowgreen;" formaction="/result">送信</button>
    <button style="background-color: pink;" formaction="/result2">送信2</button>
</form>
</body>
</html>
コントローラ側は以下のように記述します。
BaseController.java
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class BaseController{
    @GetMapping("/")
    public String home() {
      return "form";
    }
    @PostMapping("/result")
    public String result(@RequestParam String msg1,Model model){
        model.addAttribute("message1","result1です。");
        return "result";
    }
    @PostMapping("/result2")
    public String result2(@RequestParam String msg1,Model model){
        model.addAttribute("message1","result2です。");
        return "result2";
    }
}
POST先が/resultの場合は以下のページに遷移します。
result.html
<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>result</title>
<script type="text/javascript"></script>
</head>
<body>
    <h2>resultページ</h2>
    <p>メッセージ1:<span th:text="${message1}"></span></p>
</body>
</html>
POST先が/result2の場合は以下のページに遷移します。
result2.html
<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>result2</title>
<script type="text/javascript"></script>
</head>
<body>
    <h2>result2ページ</h2>
    <p>メッセージ1:<span th:text="${message1}"></span></p>
</body>
</html>
上記のソースを実行すると以下の画面が表示されます。
「送信」ボタンを押すと以下のようにresultページに遷移するのでresult.htmlに遷移しているとわかります。
「送信2」ボタンを押すと以下のようにresult2ページに遷移するのでresult2.htmlに遷移しているとわかります。
以上です。お疲れ様でした。
以上で記事の解説はお終い!
もっとJavaやSpringを勉強したい方にはUdemyがオススメ!同僚に差をつけよう!