[TIL] 스프링 입문 - 요청 데이터 처리
Spring에서 Path Variable과 Request Param으로 요청 데이터를 전달받는 방법을 정리한 TIL입니다.
For the English version of this post, see here.
[TIL] 스프링 입문 - 요청 데이터 처리
오늘 할 일
공부한 내용
Path Variable과 Request Param
- Client(브라우저)에서 서버로 HTTP 요청을 보낼 때 데이터를 함께 보낼 수 있음
- Path Variable 방식
- 서버에 보내려는 데이터를 URL 경로에 추가할 수 있음 🌐 GET http://localhost:8080/hello/request/star/Robbie/age/95
1 2 3 4 5 6 7 8 // [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); }
- Request Param 방식
- 서버에 보내려는 데이터를 URL 경로 마지막에
?와&를 사용하여 추가할 수 있음 🌐 GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
1 2 3 4 5 6 7 // [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); }form 태그 POST
- HTML의 form 태그를 사용하여 POST 방식으로 HTTP 요청을 보낼 수 있음 🌐 POST http://localhost:8080/hello/request/form/param
- 이때 해당 데이터는 HTTP Body에
name=Robbie&age=95형태로 담겨져 서버로 전달됨 ``` html
1
2
3
4
5
6
7
8
9
10
11
12
``` java
// [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에서 전달받은 값들에서 해당 값이 포함되어있지 않아도 오류가 발생하지 않음
- Client로 부터 값을 전달 받지 못한 해당 변수는 null로 초기화됨 (
required = false설정이 안되어있다면, 오류 발생)
HTTP 데이터를 객체로 처리하는 방법
@ModelAttribute
- form 태그 POST 🌐 POST http://localhost:8080/hello/request/form/model
1 2 3 4 5 6 7 8 9 10 11 // [Request sample] // POST http://localhost:8080/hello/request/form/model // Header // Content type: application/x-www-form-urlencoded // Body // name=Robbie&age=95 @PostMapping("/form/model") @ResponseBody public String helloRequestBodyForm(@ModelAttribute Star star) { return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age); }
- HTML의 form 태그를 사용하여 POST 방식으로 HTTP 요청을 보낼 수 있음 -> 이때 해당 데이터는 HTTP Body에
name=Robbie&age=95형태로 담겨져서 서버로 전달됨@ModelAttribute어노테이션을 사용한 후 Body 데이터를Star star받아올 객체로 선언함- Query String 방식 🌐 GET http://localhost:8080/hello/request/form/param/model?name=Robbie&age=95
1 2 3 4 5 6 7 // [Request sample] // GET http://localhost:8080/hello/request/form/param/model?name=Robbie&age=95 @GetMapping("/form/param/model") @ResponseBody public String helloRequestParam(@ModelAttribute Star star) { return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age); }
?name=Robbie&age=95처럼 데이터가 두 개만 있다면 괜찮지만, 여러 개 있다면@RequestParam어노테이션으로 하나씩 받아오기 힘들 수 있음 -> 이때@ModelAttribute를 사용하면 Java의 객체로 데이터를 받아올 수 있음 - 파라미터에 선언한Star객체가 생성되고, 오버로딩된 생성자 혹은 Setter 메서드를 통해 요청된name & age의 값이 담겨짐
@ModelAttribute는 생략 가능하다.@ModelAttribute와@RequestParam이 모두 생략 가능한데 Spring에서 어떻게 구별할까- Spring은 해당 파라미터(매개변수)가 SimpleType이라면
@RequestParam으로 간주하고, 아니라면@ModelAttribute가 생략되어있다고 판단한다.
- Spring은 해당 파라미터(매개변수)가 SimpleType이라면
@RequestBody
- HTTP Body에 JSON 데이터를 담아 서버에 전달할 때 해당 Body 데이터를 Java의 객체로 전달 받을 수 있음
- Body JSON 데이터 🌐 POST http://localhost:8080/hello/request/form/json
1 2 3 4 5 6 7 8 9 10 11 // [Request sample] // POST http://localhost:8080/hello/request/form/json // Header // Content type: application/json // Body // {"name":"Robbie","age":"95"} @PostMapping("/form/json") @ResponseBody public String helloPostRequestJson(@RequestBody Star star) { return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age); }- HTTP Body에
{"name":"Robbie","age";"95"}JSON형태로 데이터가 서버에 전달되었을 때@RequestBody어노테이션을 사용해 데이터를 객체 형태로 받을 수 있음
- 데이터를 객체로 받아올 때 주의할 점
- 해당 객체의 필드에 데이터를 넣어주기 위해 set or get 메서드 또는 오버로딩된 생성자가 필요함
####