@PathVariable
은 GET 방식으로 URL에 주소를 추가시켜 서버에 HTTP Request를 보낼 때 사용@RequestParam
은 GET 방식으로 URL에 Query String을 추가시켜 서버에 HTTP Request를 보낼 때 사용Clint(브라우저)에서 서버로 HTTP 요청을 보낼 때 데이터를 보내는 방식이 여러 가지가 존재하기 때문에 서버는 모든 방식에 대한 처리 방법을 학습해야 한다.
@PathVariable
: 데이터를 URL 경로에 추가하는 방법@RequestParam
: 데이터를 URL 경로 마지막에 ?
와 &
를 사용하여 추가하는 방법→ HTTP Body에 name=Robbie&age=95
형태로 담겨져서 서버로 전달된다.(개발자도구 - Payload에서 확인 가능)
<form method="POST" action="/hello/request/form/model">
<div>
이름: <input name="name" type="text">
</div>
<div>
나이: <input name="age" type="text">
</div>
<button>전송</button>
</form>
서버에 보내려는 데이터를 URL 경로에 추가하는 방법
/star/{name}/age/{age}
이처럼 URL 경로에서 데이터를 받고자 하는 위치의 경로에 {data}
중괄호를 사용{name}
중괄호에 선언한 변수명과 변수타입을 선언하면 해당 경로의 데이터를 받아올 수 있다.(@PathVariable String name, @PathVariable int age)
// GET http://localhost:8080/hello/request/star/Robbie/age/95
// 기존 경로에 '/star/Robbie/age/95' 추가
//{ } 안에 들어있는 이름과 @PathVariable를 사용한 변수명이 일치해야 한다
@GetMapping("/star/{name}/age/{age}")
@ResponseBody
public String helloRequestPath(@PathVariable String name, @PathVariable int age)
{
return String.format("Hello, @PathVariable.<br> name = %s, age = %d", name, age);
}
서버에 보내려는 데이터를 URL 경로 마지막에 ?
와 &
를 사용하여 추가하는 방법
?name=Robbie&age=95
에서 key 부분에 선언한 name과 age를 사용하여 value에 선언된 Robbie, 95 데이터를 받아 올 수 있다.(@RequestParam String name, @RequestParam int age)
// GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
// 기존 경로에 '?name=Robbie&age=95' 추가
@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam String name, @RequestParam int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
@RequestParam
은 생략이 가능@PathVariable
은 상황에 따라 생략 가능@RequestParam(required = false)
: required 옵션을 false로 설정하면 Client에서 전달받은 값들에서 해당 값이 포함되어있지 않아도 오류가 발생하지 않는다.@PathVariable(required = false)
도 해당 기능이 존재// GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam(required = false) String name, int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
package com.sparta.springmvc.request;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/hello/request")
public class RequestController {
// templates에 존재하는 HTML 파일을 반환
@GetMapping("/form/html")
public String helloForm() {
return "hello-request-form";
}
// [Request sample]
// GET http://localhost:8080/hello/request/star/Robbie/age/95
@GetMapping("/star/{name}/age/{age}")
@ResponseBody
public String helloRequestPath(@PathVariable String name, @PathVariable int age)
{
return String.format("Hello, @PathVariable.<br> name = %s, age = %d", name, age);
}
// [Request sample]
// GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam(required = false) String name, int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
// [Request sample]
// POST http://localhost:8080/hello/request/form/param
// Header
// Content type: application/x-www-form-urlencoded
// Body
// name=Robbie&age=95
@PostMapping("/form/param")
@ResponseBody
public String helloPostRequestParam(@RequestParam String name, @RequestParam int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
}
hello-request-form.html
<!DOCTYPE html>
<html>
<head>
<title>Hello Request</title>
</head>
<body>
<h2>GET /star/{name}/age/{age}</h2>
<form id="helloPathForm">
<div>
이름: <input name="name" type="text">
</div>
<div>
나이: <input name="age" type="text">
</div>
</form>
<div>
<button id="helloPathFormSend">전송</button>
</div>
<br>
<h2>GET /hello/request/form/param</h2>
<form method="GET" action="/hello/request/form/param">
<div>
이름: <input name="name" type="text">
</div>
<div>
나이: <input name="age" type="text">
</div>
<button>전송</button>
</form>
<br>
<h2>POST /hello/request/form/param</h2>
<form method="POST" action="/hello/request/form/param">
<div>
이름: <input name="name" type="text">
</div>
<div>
나이: <input name="age" type="text">
</div>
<button>전송</button>
</form>
<br>
<h2>POST /hello/request/form/model</h2>
<form method="POST" action="/hello/request/form/model">
<div>
이름: <input name="name" type="text">
</div>
<div>
나이: <input name="age" type="text">
</div>
<button>전송</button>
</form>
<br>
<h2>GET /hello/request/form/param/model </h2>
<form method="GET" action="/hello/request/form/param/model">
<div>
이름: <input name="name" type="text">
</div>
<div>
나이: <input name="age" type="text">
</div>
<button>전송</button>
</form>
<br>
<h2>POST /hello/request/form/json</h2>
<form id="helloJsonForm">
<div>
이름: <input name="name" type="text">
</div>
<div>
나이: <input name="age" type="text">
</div>
</form>
<div>
<button id="helloJsonSend">전송</button>
</div>
<div>
<div id="helloJsonResult"></div>
</div>
</body>
<script>
// GET /star/{name}/age/{age}
const helloPathForm = document.querySelector("#helloPathFormSend")
helloPathForm.onclick = (e) => {
const form = document.querySelector("#helloPathForm");
const name = form.querySelector('input[name="name"]').value;
const age = form.querySelector('input[name="age"]').value;
const relativeUrl = `/hello/request/star/${name}/age/${age}`;
window.location.href = relativeUrl;
}
// POST /hello/request/form/json
const helloJson = document.querySelector("#helloJsonSend")
helloJson.onclick = async (e) => {
const form = document.querySelector("#helloJsonForm");
const data = {
name: form.querySelector('input[name="name"]').value,
age: form.querySelector('input[name="age"]').value
}
const response = await fetch('/hello/request/form/json', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
const text = await response.text(); // read response body as text
document.querySelector("#helloJsonResult").innerHTML = text;
};
</script>
</html>