[SPRING] 서버에서 데이터 처리 방법

야부엉·2023년 11월 2일
0

SPRING

목록 보기
8/45

1. Jackson 라이브러리

  • Jackson은 JSON 데이터 구조를 처리해주는 라이브러리
  • Object를 Json으로 변환, Json을 Object로 변환이 가능하다.
  • SpringBoot에 default로 제공

1. Object -> Json

  • objectMapper의 writeValueAsString 메서드를 사용하여 변환
  • Object -> Json 하기 위해서는 get Method가 필요
    // Object to Json : Serialization(직렬화)
    @Test
    @DisplayName("Object To JSON : get Method 필요")
    void test1() throws JsonProcessingException {
        Star star = new Star("Robbie", 95);

        ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 ObjectMapper
        // objectMapper 객체를 읽은 다음에 String 타입의 json 형태로 변환
        // objectMapper도 Getter가 필요(직렬화 떄문)
        String json = objectMapper.writeValueAsString(star);

        System.out.println("json = " + json);
    }

2. Json -> Obeject

  • JSON 타입의 String을 Object로 변환하기 위해서는 해당 Object에 기본 생성자와 get 혹은 set 메서드가 필요
  • objectMapper의 readValue 메서드 사용 - readValue(json, 클래스 이름)
    // Json to Object : DeSerialization(역직렬화)
    @Test
    @DisplayName("JSON To Object : 기본 생성자 & (get OR set) Method 필요")
    void test2() throws JsonProcessingException {
        // 클래스 필드의 Key 값을 잘 맞춰줘야한다.
        String json = "{\"name\":\"Robbie\",\"age\":95}"; // JSON 타입의 String

        ObjectMapper objectMapper = new ObjectMapper(); // Jackson 라이브러리의 ObjectMapper
        // readValue(String , 어떠한 객체로 만들거냐? )
        Star star = objectMapper.readValue(json, Star.class);
        System.out.println("star.getName() = " + star.getName());
        System.out.println("star.getAge() = " + star.getAge());
    }
}

2. 서버에서 데이터 처리 방법

  • 브라우저(client)에서 서버애게 HTTP 요청을 할 때, 데이터를 여러 방식으로 보낼 수 있는데, 서버에서 여러 방식에 대한 데이터 처리 방법들이 있다.

1. Path Variable

  • 보내고자 하는 데이터를 경로에 보내는 방식
  • Url 경로에 받고자 하는 데이터 부분에 중괄호를 한다.
  • @PathVariable과 함께 중괄호에 선언한 변수명과 변수 타입을 선언하면 데이터를 받아올 수 있다.
    // [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);
    }

2. Request Param

  1. Request Param 방식
  • 서버에 보내려는 데이터를 URL 경로 마지막에 ? 와 & 를 사용하여 추가할 수 있다.
  • 해당 요청 메서드 파라미터에 @RequestParam 애너테이션과 함께 key 부분에 선언한 변수명과 변수타입을 선언하면 데이터를 받을 수 있다.
 	// [Request sample]
    // GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95 (Query String 방식)
    // ? key=value & key=value -> ?name=Robbie & age=95
    // RequestParam 생략이 가능하다.
    // 데이터를 안 보낼경우 오류가 난다. -> required = false로 해결한다. : 클라이언트의 전달받는 값들 중에서 해당 값이 포함이 안되도 오류 X, 물론 pathVariable에도 있다.
    // 대신 빈 값에 NULL이 들어간다.
    @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);
    }
  1. Form 태그 Post
  • Post방식도 위와 같다 하지만, Post는 HTTP Body 부분name=Robbie&age=95형태로 서버로 전달한다.
  • 브라우저 개발자도구 Network -> payload 탭에 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);
    }

3. 객체로 처리하는 방법

1. @ModelAttribute

  • form 태그 Post방식 (Query String)
    - Body에 있는 QueryString 방식을 객체로 받을 수 있다.
    • @ModelAttribute 애너테이션을 사용한 후 Body 데이터를 Star star 받아올 객체를 선언
    // [Request sample]
    // POST http://localhost:8080/hello/request/form/model
    // Header
    //  Content type: application/x-www-form-urlencoded
    // Body
    //  name=Robbie&age=95
    // ModelAttribute - > Body에 있는 QueryString 방식을 객체로 받을 수 있다.
    @PostMapping("/form/model")
    @ResponseBody
    public String helloRequestBodyForm(@ModelAttribute Star star) {
        return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
    }
  • Get 방식 (query String)
    - 요청할 때 제공해 주는 데이터 타입이 여러개 일때 사용한다. -> 객체로 만들어주면서 매개 변수를 여러개 선언할 필요가 없어진다.
    • 파라미터에 선언된 객체가 생성되고, 오버로딩된 생성자 혹은 Setter 메서드를 통해 요청된 데이터 값이 담긴다.
// [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);
}

Spring에서는 @ModelAttribute뿐만 아니라 @RequestParam도 생략이 가능한데 그럼 어떻게 구분할까?

  • 파라미터(매개변수)가 SimpleValueType : @RequestParam
  • 파라미터가 객체 : @ModelAttribute

2. @RequestBody (Json)

  • 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"}
    // @RequestBody : 이거 데이터 받아와주세요.
    @PostMapping("/form/json")
    @ResponseBody
    public String helloPostRequestJson(@RequestBody Star star) {
        return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
    }

주의할 점!!!
객체의 필드에 데이터를 넣어주기 위해 set or get 메서드 또는 오버로딩된 생성자가 필요


출처

스프링 Master 강의

profile
밤낮없는개발자

0개의 댓글