Blog

[Spring]14_4 JSON형태로 반환하도록 API 작성하기 Path Variable과 Request Param

Author
Summary
Path Variable과 Request Param 보여줌
Category
Study
Tags
Spring
Favorite
Memory Date
2023/08/29
Cross Reference Study
Related Media
Related Thought
Related Lessons
tag
날짜
작성자
진행상황
진행 전
태그구분
6 more properties
Path Variable
기본적인 모습/star/Robbie/age/95
// [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); }
Java
복사
데이터를 받기 위해서는 /star/{name}/age/{age} 이처럼 URL 경로에서 데이터를 받고자 하는 위치의 경로에 {data} 중괄호를 사용
(@PathVariable String name, @PathVariable int age)
그리고 해당 요청 메서드 파라미터에 @PathVariable 애너테이션과 함께 {name} 중괄호에 선언한 변수명과 변수타입을 선언하면 해당 경로의 데이터를 받아올 수 있음
Request Param(쿼리스트링방식이라고도 함)
데이터를 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); }
Java
복사
데이터를 받기 위해서는 ?name=Robbie&age=95 에서 key 부분에 선언한 name과 age를 사용
(@RequestParam String name, @RequestParam int age)
해당 요청 메서드 파라미터에 @RequestParam 애너테이션과 함께 key 부분에 선언한 변수명과 변수타입을 선언하면 데이터를 받음
form태그의 POST 메서드로?
// [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); }
Java
복사
사실 위와 같아보이지만, Content type이 다르다. x-www-form-urlencoded 하지만 작동원리는 비슷. 결국 태그의 속성 중 name이 클래스 name과 같아야 한다.