JSON 형태로 반환하는것을 선호.
// [Response header]
// Content-Type: text/html
// [Response body]
// {"name":"Robbie","age":95}
@GetMapping("/response/json/string")
@ResponseBody
public String helloStringJson() {
return "{\"name\":\"Robbie\",\"age\":95}";
}
// [Response header]
// Content-Type: application/json
// [Response body]
// {"name":"Robbie","age":95}
@GetMapping("/response/json/class")
@ResponseBody
public Star helloClassJson() {
return new Star("Robbie", 95);
}
Java Class 를 return 할 경우 json 형태로 Spring이 자동변환 해준다.
@RestController = @Controller + @ResponseBody
@ResponseBody 어노테이션 효과를 부여.ObjectMapper를 사용할 수 있음.@Test
@DisplayName("Object To JSON : get Method 필요")
void test1() throws JsonProcessingException {
Star star = new Star("Robbie", 95);
ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 ObjectMapper
String json = objectMapper.writeValueAsString(star);
System.out.println("json = " + json);
}
=====================================================
json = {"name":"Robbie","age":95}
Getter 가 필요하다.@Test
@DisplayName("JSON To Object : 기본 생성자 & (get OR set) Method 필요")
void test2() throws JsonProcessingException {
String json = "{\"name\":\"Robbie\",\"age\":95}"; // JSON 타입의 String
ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 ObjectMapper
Star star = objectMapper.readValue(json, Star.class);
System.out.println("star.getName() = " + star.getName());
}
===============================================================
star.getName() = Robbie
star.getAge() = 95

클라이언트가 서버로 요청을 보낼때 데이터를 함께보낼수 있음.
서버에서는 데이터를 받아 사용할때 보내는방식이 여러가지기에 모든방식에 대한 처리가 필요.
http://localhost:8080/hello/request/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);
}
데이터를 받기 위해서는 /star/{name}/age/{age} 이처럼 URL 경로에서 데이터를 받고자 하는 위치의 경로에 {data} 중괄호를 사용
(@PathVariable String name, @PathVariable int age)
? 와 & 를 사용하여 추가.http://localhost:8080/hello/request/form/param?name=Robbie&age=95// [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);
}
데이터를 받는 ?name=Robbie&age=95 부분에서 key부분에 설정한 네이밍 부분과 매칭하여 데이터를 받아옴.
(@RequestParam String name, @RequestParam int age)
위에 패스밸류 방식과 동일.
POST http://localhost:8080/hello/request/form/param// [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);
}
name=Robbie&age=95 형태로 담겨져서 전달.// [Request sample]
// GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
@GetMapping("/form/param")
@ResponseBody
public String helloGetRequestParam(@RequestParam(required = false) String name, int age) {
return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
}
@RequestParam(required = false) required 옵션을 설정하면 Client로 부터 값이 포함되어있지 않아도 오류가 발생하지 않음@PathVariable(required = false) 도 가능하다.NULL 값으로 지정됌!
// [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);
}
// [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);
}
@RequestParam 의 경우 받는 데이터수가 적다면 문제가 없지만 여러개가 있을시 하나씩 받아오기가 힘듬.
@ModelAttribute 애너테이션을 사용하면 Java의 객체로 데이터를 받아올 수 있음.
생략이 가능하다. 그런데 @ModelAttribute뿐만 아니라 @RequestParam도 생략이 가능그렇다면 Spring은 이를 어떻게 구분??
HTTP Body 부분에 JSON 형태로 서버에 전달할때 받는 어노테이션
// [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);
}