Light Blue Pointer
본문 바로가기
Developing/TIL(Develop)

HTTP 데이터를 객체로 처리하는 방법

by Greedy 2023. 11. 7.

request→Star클래스 만듦

우클릭 → generate → Constructor ctrl로 전부 체크

public Star(String name, int age) {
        this.name = name;
        this.age = age;
    }

모든 필드 체크하면 이게 뜸

@ModelAttribute

Body 부분에 데이터가 들어왔을 때 객체로 처리하는 방법

Body 부분에 들어온 QueryString 방식의 데이터를 객체에 매핑해서 가지고 옴

RequestController에 이거 추가

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

http://localhost:8080/hello/request/form/html

여기 가서

POST /hello/request/form/model

에 데이터 전송해봄

Star 클래스에 가서

name 우클릭 refactor → rename → select all 하고 nam으로 바꾸면

관련된 데이터가 모두 nam으로 바뀜

// [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.nam**, star.age);
    }

 

근데 name = null이 됨

Star의 field의 이름을 클라이언트에서 보내주는 이름이랑 꼭 일치시켜야 한다고 함

객체로 변환하는 과정에서 인식을 못해서 못 넣어줬다고

 

 

RequestController에 이거 추가해줌

// [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으로 다 받기 부담스러워서 객체를 많이 쓴다고 함

유지보수도 힘들고

전송 누르면
잘 나온다

 

 

오버로딩된 생성자를 지워봄

public class Star {
    String name;
    int age;
}

 

 

name 생성자를 만들면  name은 출력됨

@ModelAttribute는 생략이 가능하다고 함

// [Request sample]
    // GET <http://localhost:8080/hello/request/form/param/model?name=Robbie&age=95>
    @GetMapping("/form/param/model")
    @ResponseBody
    public String helloRequestParam(Star star) {
        return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
    }

@RequestParam도 생략 가능한데 어떻게 구분하냐

Simple value : primitive type이면 param이라고 생각하고 Object가 들어오면 ModelAttribute라고 생각한다고 함

 

 

@RequestBody

JSON 형식으로 받아오기

RequestController에 이거 추가

// [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부분에 JSON 형식으로 데이터가 넘어왔을때

그 데이터를 처리하기 위해서는 그 데이터를 처리하기 위한 Class를 만들어서 parameter에 넣어주고(Star) 그 앞에 @RequestBody를 꼭 달아줘야 한다고 함

이것도 마찬가지로 Star 클래스의 name 필드를 refactor 하면 RequestBody로 넘어오는 이름이랑 달라져서 null됨

package com.sparta.springmvc.request;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/hello/request")
public class RequestController {
    @GetMapping("/form/html")
    public String helloForm() {
        return "hello-request-form";
    }

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

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

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

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

'Developing > TIL(Develop)' 카테고리의 다른 글

3 Layer Architecture 역할 분리  (1) 2023.11.09
Database&SQL&JDBC  (0) 2023.11.07
Path Variable과 Request Param  (0) 2023.11.06
Jackson이란 무엇일까  (0) 2023.11.06
데이터를 클라이언트에게 반환하는 방법  (0) 2023.11.06