Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags more
Archives
Today
Total
관리 메뉴

요리사에서 IT개발자로

스파르타 부트캠프 Spring Master 1강 Path Variable과 Request Param 본문

Spring

스파르타 부트캠프 Spring Master 1강 Path Variable과 Request Param

H.S-Backend 2024. 5. 17. 19:53

출처 : 스파르타 코딩클럽

  // [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);
}

@PathVariable

데이터를 받기위해서 /star/{name}/age/{age} 

이처럼 URL경로에서 데이터를 받고자하는 위치의 경로에 {} 중괄호를 사용한다.

(@PathVariable String name, @PathVariable int age)
해당 요청 메서드 파라미터에 @PathVarialbe 에너테이션과 함께 {name} 중괄호에 선언한 변수명과 변수타입을 선언하면 해당 경로의 데이터를 받아올 수 있다.

@RequestParam 

서버에 보내려는 데이터를 URL 마지막에 ? 와 &을 사용하여 추가할 수 있다.

// [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);
}
(@RequestParam String name, @RequestParam int age)
//해당 요청 메서드 파라미터에 @RequestParam 에너테이션과함께 Key부분에 선언한 변수명과 변수타입을 선언하여 데이터를 받아올 수 있다.

@RequestParam은 생략이 가능하다

@RequestParam (required = false)

옵션을 false로 설정하면

Client에서 전달받은 값들에서 해당 값이 포함되어 있지 않아도

오류가 발생하지 않는다.

 

대신 해당 변수는 null로 초기화가 된다.

반응형