プログラマーの調べ物

プログラマーが調べ物をするときに役に立つサイトを作ります。

Spring Bootでフォームを送って結果を返す

とりあえずって感じですが、formタグで囲まれた情報をJava側に送りつけて、その結果をHTMLで返すサンプルです。

まずは、HTTP GETで情報を送信するHTMLです。

account.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>SAMPLE</title>
</head>
<body>
<form action="/result">
  <fieldset>
    <input type="text" name="name" />
    <input type="submit" value="Subscribe me!" />
  </fieldset>
</form>
</body>
</html>

これを受け取るJavaを書きます。

package com.example;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class RestaurantController {
    
    @RequestMapping("/account")
    public String account(Model model) {
        return "account";
    }
    
    @RequestMapping(value = "/result", method = RequestMethod.GET)
    public String form(Model model,@RequestParam String name) {
        model.addAttribute("name", name);
        return "result";
    }
    
}

結果を表示するHTMLです。

result.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>結果</title>
</head>
<body>
結果:
<span th:text="${name}"></span>
</body>
</html>

「結果: test」とブラウザに表示されます。