브라우저에서 서버로 http 요청 + 데이터를 함께 보낼 때 사용하는 방식
특징
🌐 GET http://localhost:8080/hello/request/star/Robbie/age/95
코드
@GetMapping
@PathVariable
// [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);
}
특징
🌐 GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
? 와 & 를 사용하여 추가할 수 있습니다.코드
@GetMapping
@RequestParam
// [Request sample]
// GET http://localhost:8080/hello/request/form/param?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);
}
특징
🌐 POST http://localhost:8080/hello/request/form/param
코드
@PostMapping
@RequestParam
// [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);
}
- @RequestParam은 생략이 가능합니다.
@RequestParam(required = false)
- 이렇게 required 옵션을 false로 설정하면 Client에서 전달받은 값들에서 해당 값이 포함되어있지 않아도 오류가 발생하지 않습니다.
@PathVariable(required = false)도 해당 옵션이 존재합니다.- Client로 부터 값을 전달 받지 못한 해당 변수는 null로 초기화됩니다.