3
0

Java の Spring Boot を使用して、画面からコントローラ(Controller)に値を渡す方法はいくつかあります。以下に、主な方法を整理しました。

1. リクエストパラメータを使用する(@RequestParam

クエリパラメータとして値を渡し、コントローラで@RequestParamアノテーションを使って取得する方法です。

例:
URL: /users?name=John

UserController
@Controller
public class UserController {

    @GetMapping(value = "/users")
    public String getUsersByName(@RequestParam("name") String name) {
    	System.out.print("name:"+name);// Expected output: name:John
        return "index";
    }
}

2. URL パス変数を使用する(@PathVariable

URL の一部として値を渡し、コントローラで@PathVariableアノテーションを使って取得する方法です。

例:
URL: /users/100

UserController
@Controller
public class UserController {

	@GetMapping(value = "/users/{userId}")
    public String getUserById(@PathVariable("userId") int userId) {
    	System.out.print("userId:"+userId);// Expected output: userId:100
        return "index";
        }
    }

3. フォームデータをオブジェクトで受け取る(@ModelAttribute

フォームデータをオブジェクトにマッピングして受け取る方法です。

例:
URL: /users
HTML フォーム:textbox:John

index.html
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>index</title>
  </head>
  <body>
	  <form action="/users/post" method="post">
		  <input type="text" name="name" />
		  <button type="submit">Submit</button>
	  </form> 
	</body>
</html>
sample.html
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>page</title>
  </head>
  <body>

<h1>Hello World sample!!</h1>    

    </body>
</html>
UserController
@Controller
public class UserController {
	
	@GetMapping(value = "/users")
	public String showIndex() {
		return "index";
	}
	
	@PostMapping(value = "/users/post")
    public String getUserByUser(@ModelAttribute User user) {
    	System.out.print("name:"+user.getName());// Expected output: name:John
        return "sample";
    }
}

まとめ

  • URL パス変数(@ PathVariable): URL の一部として値を渡す場合に使用
  • リクエストパラメータ(@ RequestParam): クエリパラメータとして値を渡す場合に使用
  • フォームデータ(@ ModelAttribute): フォームデータをオブジェクトにマッピングして受け取る場合に使用
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0