前提
後悔しないためのSpring Boot 入門書という参考書を見ながらSpring Bootの学習をしています。
formタグから送信したキーワードをデータベース検索するという章を学んだ時に、
java
1`<form method="POST" action="hello/db"> 2<!-- th:valueでinputのvalueに値を代入--> 3 従業員ID:<input type="text" name="text2" th:value="${text2_value}"> 4 <input type="submit" value="クリック"> 5 </form>">
というタグが出てきました。
しかしその前には、
java
1 <form method="POST"> 2 入力:<input type="text" name="text1"> 3 <input type="submit" value="送信"> 4 </form>
というth:value=""を使わず値を送信する方法(こちらはデータベース検索ではありません)をやりました。
また、そもそもth:value="${text2_value}"のtext2_valueをhtmlにもjavaのクラスにもどこにも定義していないはずなのですが、"${text2_value}には何が入っているのでしょうか?
似たようなコードを書いている人を見ましたが、この方はth:value="${text2_value}"なしで動くようです。あってもなくてもかまわないとは思いませんが、どういうことか分かりません。
どなたかご教授頂けると幸いです。
適当にinputタグに入力してもvalueには何も入っていません。
※エラーはなく、ちゃんとアプリケーションは動いています。
該当のソースコード
html
1<html xmlns:th="http://www.thymeleaf.org"> 2<head> 3<meta charset="UTF-8"> 4<title>EclipseでSpring Bootの開発環境を構築!!</title> 5</head> 6<body> 7 <h1>Hello, Spring Boot!!</h1> 8 <form method="POST"> 9 入力:<input type="text" name="text1"> 10 <input type="submit" value="送信"> 11 </form> 12 <br/> 13 14 <form method="POST" action="hello/db"> 15<!-- th:valueでinputのvalueに値を代入--> 16 従業員ID:<input type="text" name="text2" th:value="${text2_value}"> 17 <input type="submit" value="クリック"> 18 </form> 19 20</body> 21</html>
HelloController.java
java
1package com.example.hello; 2 3import org.springframework.beans.factory.annotation.Autowired; 4import org.springframework.stereotype.Controller; 5import org.springframework.ui.Model; 6import org.springframework.web.bind.annotation.PostMapping; 7import org.springframework.web.bind.annotation.RequestMapping; 8import org.springframework.web.bind.annotation.RequestParam; 9 10@Controller // アノテーションを使って、Controllerクラスであることを宣言 11public class HelloController { 12 13 14 @Autowired 15 private HelloService service; 16 17 18 19 @RequestMapping(value="/hello") // 「/index」にリクエストが来たときに呼び出されるメソッドを作成 20 public String getHello() { 21 22 23// hello.htmlに画面遷移 24 return "hello"; 25 } 26 27 @PostMapping("/hello") 28 public String postRequest(@RequestParam(name="text1") String str,Model m) { 29 30 m.addAttribute("sample",str); 31 System.out.println("受け取ったよ"); 32 return "hello/response"; 33 } 34 35 36 37 @PostMapping("/hello/db") 38 public String postDbRequest(@RequestParam(name="text2") String id,Model m) { 39 40// 1件検索 41 Employee employee=service.getEmployee(id); 42// 43// 検索結果をModelに登録 44 m.addAttribute("employee",employee); 45 46// db.htmlに画面遷移 47 return "hello/db"; 48 } 49 50} 51
試したこと追記
https://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q10260885730
th:valueはhtmlを上書するとのことですが、実際上書きされていないので解決できませんでした。

回答1件
あなたの回答
tips
プレビュー