Spring 8. Path Variable과 Request Param

김창민·2024년 8월 12일

BE

목록 보기
28/50

Path Variable

서버에 보내려는 데이터를 URL 경로에 추가한다.

/star/Robbie/age/95 이러면 Robbie와 95라는 데이터를 서버로 보내는 것.
이를 받기 위해선 (GET방식이라고 치면)@GetMapping("/star/{name}/age/{age}")와 같이 사용한다. 즉, 데이터를 받고자 하는 위치에 {date}식으로 입력한다. 이후 이 값을 파라미터로 받아와서 메소드의 매개변수에 다음과 같이 입력한다.

public String helloRequestPath(@PathVariable String name, @PathVariable int age)
{
     return ~~
}

이러면 어노테이션에서 name, age를 동명의 매개변수로 사용한다.

Request Param

Request Param 방식

서버에 보내려는 데이터를 URL 끝에 매단다.

URL경로를 전부 입력하고 ?로 시작하며 &로 추가하면서 사용한다. 즉, http://localhost:8080/hello/request/form/param?name=Robbie&age=95
처럼 http://localhost:8080/hello/request/form/param에서 경로는 끝이 났지만, ?로 name=Robbie, age=95를 보낸다.
이렇게 보내진 데이터도 역시 다음과 같이 받는다.

public String helloGetRequestParam(@RequestParam String name, @RequestParam int age) {
    return ~;
}

이러면 key=value로 전달되는 데이터의 key명과 파라미터의 이름이 같으면 이용이 가능해진다.

form 태그 POST

HTML의 form 태그를 사용해서 POST 방식으로 HTTP 요청을 보낼 수 있다.

이때 데이터는 Request Param 방식으로 key1:value1&key2:value2 형태로 담겨진다.
즉,

<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>

이렇게 전달되면

@PostMapping("/form/param")
@ResponseBody
public String helloPostRequestParam(@RequestParam String name, @RequestParam int age) {
    return ~
}

이런식으로 받아진다는 것.

이때, 모든 @RequestParam은 생략이 가능하다.

profile
일일 회고 : https://rlackdals981010.github.io/

0개의 댓글