プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

SpringBoot入門 vol.3:画面から値を渡そう

①「hello.html」に下記を記述

【格納先】:src\main\resources\templates配下
 

<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>Hello World</h1>
    <!-- ポイント1 -->
    <form action="/resultCtrl" method="post">
        <input type="text" name="val">
        <input type="submit" value="送信">
    </form>
</body>
</html>

 

【ポイント】

1.action属性に「SampleController」で受ける為のパスを設定
POSTメソッドで送信
 
 

②「SampleController.java」に下記を記述

package com.example.web;

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 SampleCotroller {
    @GetMapping("/")
    String getHello() {
        return "hello";
    }

    //ポイント1
    @PostMapping("resultCtrl")
    //ポイント2
    String postResult(@RequestParam("val") String responseVal, Model model) {
        //ポイント3
        model.addAttribute("responseVal", responseVal);
        return "result";
    }
}

 

【ポイント】

1.「@PostMapping」を付与すると画面からPOSTメソッドで送られてきた場合の処理ができる
引数には「hello.html」のフォームで設定したaction属性のパスを設定する
 
2-1.メソッドの引数に「@RequestParam」を付与すると画面で入力した値が受け取れる
引数にはformのname属性を指定する
 
2-2.直後に記述した変数で値を受け取る
「String responseVal」
 
2-3.画面に値を渡す為に引数に「Model model」を設定
 
3.model.addAttributeメソッドで画面に渡したいデータをModelオブジェクトに追加
【構文】 model.addAttribute("属性名", 渡したいデータ);
 
「return」で遷移先のパスを指定
遷移先は「src/main/resources/templates」より後のパスで、拡張子は省く
 
 

③遷移先の「result.html」を作成し、下記を記述する

【格納先】:src\main\resources\templates配下
 

 
 
【result.html】

<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>Result</h1>
    <!-- ポイント1 -->
    <p th:text="${responseVal}"></p>
</body>
</html>

 

【ポイント】

1.「th:text」でコントローラークラスからの値を受け取る
【構文】 th:text="${Modelオブジェクトに追加した属性名}"
 
 


前へ次へ
 
目次へ戻る