본문 바로가기
Java/Spring

23.06.24) Spring 강의 노트

by NH_club 2023. 6. 24.
자바에선 JSON 타입을 지원하지 않는다. 그러면 어떻게 JSON 데이터를 반환해야 할까?
더보기

1. JSON 형식의 html 파일을 반환해 준다.

2. @ResponseBody 어노테이션을 추가해서 JSON 형식의 문자열로 반환해 준다.

@GetMapping("/response/json/string")
@ResponseBody
public String helloStringJson() {
    return "{\"name\":\"Robbie\",\"age\":95}";
}

3. 객체 반환하기. Spring에서는 자동으로 Java 객체를 JSON으로 반환해 준다. 

@GetMapping("/json/class")
@ResponseBody
public Star helloClassJson() {
    return new Star("Robbie", 95);
}

※ 주의 사항: @ResponseBody 어노테이션이 없으면 templates 폴더에서 파일을 찾기 때문에 2, 3번처럼 반환할 때는 view(html)반환이 아니라 데이터 반환이다 라는 것을 알려주기 위해 @ResponseBody 사용 해야함

4. @Controller가 아닌 @RestController를 사용해서 반환.

@RestController
@RequestMapping("/response/rest")
public class ResponseRestController{
    @GetMapping("/json/string")
    public String helloStringJson(){
        return "{\"name\":\"Robbied\",\"age\":95}";
}

★ @RestController = @Controller + @ResponseBody. 모든 메소드에 @ResponseBody 부여한 것과 동일한 효과.

만약 View를 반환하는 메소드가 있다면 @Controller로 교체해야 함
@Controller로 변경 됐으면 데이터로 전달하는 메소드에는 @ResponseBody 사용.

Jackson 이란?
더보기

JSON 데이터 구조를 처리해 주는 라이브러리. Spring 3.0 버전 이후로 Jackson과 관련된 API를 제공해 준다.

Object를 JSON 타입의 String으로 변환해 주거나 JSON 타입의 String을 Object로 변환 해준다.
SpringBoot의 starter-web에서는 default로 Jackson 관련 라이브러리 제공. ObjectMapper를 사용해서 데이터 처리

@Test
@DisplayName("Object To JSON : getter 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);
}

@Test
@DisplayName("JSON To Object : 기본 생성자 & (getter OR setter) 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());
}

 

클라이언트가 서버로 데이터를 보낼 때 데이터 처리 방식은?
더보기

클라이언트가 서버로 요청을 보낼 때 데이터를 같이 보낼 수 있다. 데이터를 보내는 방법에는 여러 가지가 있다.
서버에선 이 데이터를 받아서 처리해야 하므로 데이터를 보내는 모든 방식에 대한 처리 방법을 알아야 한다.

1. Path Variable 방식. 서버에 보내려는 데이터를 URL 경로에 추가할 수 있다.

// [Request sample]
// GET http://localhost:8080/hello/request/star/Robbie/age/95
@GetMapping("/star/{name}/age/{age}") //데이터를 받고자 하는 곳에 중괄호
@ResponseBody
//@PathVariable 어노테이션과 같이 데이터의 변수명과 타입을 파라미터로 지정
public String helloRequestPath(@PathVariable String name, @PathVariable int age)
{
    return String.format("Hello, @PathVariable.<br> name = %s, age = %d", name, age);
}

2. Request Param(GET) 방식.  서버에 보내려는 데이터를 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);
}

3. Request Param(POST) 방식.  서버에 보내려는 데이터를 Body에 담아서 보낼 수 있다.

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

@PathValriable(required = false) or  RequestParam(required = false)로 설정하면 값을 생략할 수 있음.
해당 값은 null로 들어감. default 값은 true이기 때문에 값을 넣지 않으면 오류 남.

4. ModelAttribute(Post). Header와 Body로 구성된 Post 요청이 날라오면 객체로 처리해 줄 수 있다.

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

5. ModelAttribute(Get).

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

6. RequestBody. HTTP Body에 JSON 데이터를 담아 요청할 때 Body 데이터를 Java의 객체로 받을 수 있다.

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

데이터를 객체로 받아올 때 주의사항:
해당 필드에 데이터를 넣어주기 위해 생성자 또는 getter 또는 setter가 필요함. 객체로 데이터를 받아올 때 데이터가 
제대로 들어오지 않는다면 객체의 생성자, getter, setter 유무를 파악해야 함

●의문점: ModelAttribute 랑 RequestBody 둘 다 객체로 받는건데 무슨 차이?

ModelAttribute는 일반적으로 HTTP GET 요청의 쿼리 매개변수나 HTTP POST 요청의 폼 데이터를 처리하는데 사용 쿼리 매개변수나 폼 데이터는 일반적으로 "name=value" 형태의 키-값 쌍임.
ModelAttribute는 자동으로 View에 데이터를 추가하는 기능도 있음
RequestBody는 JSON 또는 XML처럼 복잡한 데이터 구조를 객체로 변환하는 데 쓰임. 그러므로 라이브러리(Jackson 등)가 필요함 

DTO란?
더보기

데이터 전송 및 이동을 위해 생성되는 객체를 의미한다.

ModelAttribute, RequestBody 애노테이션으로 데이터를 객체로 처리했는데, 이 객체를 DTO 객체로 사용한다.

JDBC란?
더보기

기존에 사용하던 데이터베이스를 다른 회사의 데이터베이스로 변경한다면 바꿀 회사에 맞게 수정해야한다.

이 것을 해결할 수 있도록 만든 것이 JDBC 이다.

DB 회사들은 자신들의 DB에 맞도록 JDBC 인터페이스를 구현한 후 라이브러리로 제공하는데 이를 JDBC 드라이버라 부른다. DB를 교체할 때 드라이버만 교체하면 손쉽게 DB 변경이 가능하다.

'Java > Spring' 카테고리의 다른 글

23.06.30) Spring 강의 노트  (0) 2023.06.30
23.06.29) Spring 강의 노트  (0) 2023.06.29
23.06.26)Spring  (0) 2023.06.26
23.06.25)Spring 강의 노트  (0) 2023.06.25
23.06.23) Spring 강의 노트  (0) 2023.06.23