Thymeleafと@Controllerでデータを送受信する方法 on Spring Boot

Spring BootでThymeleafと@Controllerのデータ送受信する方法をご紹介します。

Thymeleaf

まずThymeleafで送信処理を書きます。ここはHTMLと同じです。

<form type="post" name="sampleFormName" action="./sampleFormAction" id="sampleFormId">
  <input type="text" name="sampleData" value="Hello World!">
  <button type="submit" name="sampleFormSubmit"></button>
</form>

@Controller

続いて@Controllerを書きます。Thymeleafの送信処理を受け止めます。

@Controller
public class HelloController {

  @RequestMapping(value = "/sampleFormAction", method = RequestMethod.POST)
  public ModelAndView helloWorld(
      @RequestParam(name = "sampleData") String sample
      ModelAndView mav) {
  
    mav.addObject("message", sample);
    mav.setViewName("index");
  
    return mav;
  }
}

Thymeleafのテンプレートとデータを合成してHTMLを作成して返却します。

ModelAndViewがテンプレートとデータの合成先です。ModelAndViewに対してsetViewNameでテンプレートを設定、ModelAndViewに対してaddAttributeでデータを設定します。そうして合成されたModelAndViewをreturnで返却します。

Thymeleaf

再びThymeleafです。@Controllerで作成されたHTMLを表示します。

<p th:text="${message}"></p>

これで完了です。