클라이언트(브라우저)에서 서버로 HTTP 요청을 보낼 때 데이터를 함께 보낼 수 있다.
서버에서는 이 데이터를 받아서 사용해야하는데 데이터를 보내는 방식이 한 가지가 아니라 여러 가지가 있기 때문에 모든 방식에 대한 처리 방법을 배워보자.
https://www.google.com/search?q=velog&sourceid=chrome&ie=UTF-8
// 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 리턴값;
}
서버에 보내려는 데이터를 URL 경로 마지막에 ? 와 & 를 사용하여 추가할 수 있다.
[GET]
// 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 리턴값;
}
[form 태그 POST]
// 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 리턴값;
}
해당 데이터를 Java의 객체 형태로 받는 방법은 @ModelAttribute 애너테이션을 사용한 후 Body 데이터를 Star star 받아올 객체를 선언한다.
[form 태그 POST]
// 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 리턴값;
}
[Query String 방식]
// 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 리턴값;
}
HTTP Body에 JSON 데이터를 담아 서버에 전달할 때 해당 Body 데이터를 Java의 객체로 전달 받을 수 있다.
// 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 리턴값;
}
이론을 정리하는 것은 그닥 기억에 남지 않는 것 같다. postman으로 직접 값을 넣어서 확인해야 직관적으로 개념들이 잘 들어오는거 같다.
postman으로 나중에 내용을 더 추가해보자.
참고자료