[Spring] Path Variable, Request Param

kang·2024년 8월 13일

SPRING

목록 보기
8/22

브라우저에서 서버로 http 요청 + 데이터를 함께 보낼 때 사용하는 방식

1. Path Variable 방식

특징

🌐 GET http://localhost:8080/hello/request/star/Robbie/age/95
  • 서버에 보내려는 데이터를 URL 경로에 추가할 수 있습니다.
  • /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);
}
  • { }는 data, (받는 내용에 따라 달라짐)

2. Request Param

특징

🌐 GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
  • 서버에 보내려는 데이터를 URL 경로 마지막에 ?& 를 사용하여 추가할 수 있습니다.
  • ?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);
}

3. Html의 form태그를 활용하여 POST방식으로 요청보내기

특징

🌐 POST http://localhost:8080/hello/request/form/param
  • HTML의 form 태그를 사용하여 POST 방식으로 HTTP 요청을 보낼 수 있습니다.
  • 이때 해당 데이터는 HTTP Body에 name=Robbie&age=95 형태로 담겨져서 서버로 전달됩니다.

코드

@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로 초기화됩니다.
profile
뉴비 개발 공부중

0개의 댓글