오답노트

[Spring Boot] POST 본문

Java/Spring

[Spring Boot] POST

권멋져 2023. 7. 12. 15:51

JSON

Post 방식은 Body를 통해 데이터를 주고 받는다. 이때 가장 잘 사용하는 포맷이 JSON이다.

JSON은 대괄호로 depth를 나누고 key 와 value로 이루어져 있다.

 

  • string : value
  • number : value
  • boolean : value {}
  • object : value
  • array : value
{
"phon_number : "010-0000-0000",
"age" : 10,
"isAgree" : false,
"account" : {
"email" : "asd@gmail.com",
"password":1234
}
"array" [
{
"account" : "asdf",
"password" : 1234
},
{
"account" : "asdf",
"password" : 1234
}
]
}

POST 구현

@RestController
@RequestMapping("/api")
public class PostApiController {

    @PostMapping("/post")
    public void post(@RequestBody PostRequestDto requestData){
        System.out.println(requestData.toString());
    }

}

 

JsonProperty를 통해 body에서 변수명과 동일하지 않는 key여도 지정하여 읽어들일 수 있다.

import com.fasterxml.jackson.annotation.JsonProperty;

public class PostRequestDto {
    private String account;
    private String email;
    private String address;
    private String password;
    @JsonProperty("phone_number")
    private String phoneNumber; //phone_number
    @JsonProperty("OTP")
    private String OTP;

    public String getOTP() {
        return OTP;
    }

    public void setOTP(String OTP) {
        this.OTP = OTP;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phone_number) {
        this.phoneNumber = phone_number;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "PostRequestDto{" +
                "account='" + account + '\'' +
                ", email='" + email + '\'' +
                ", address='" + address + '\'' +
                ", password='" + password + '\'' +
                ", phoneNumber='" + phoneNumber + '\'' +
                ", OTP='" + OTP + '\'' +
                '}';
    }
}

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

[Spring Boot] Response  (0) 2023.07.13
[Spring Boot] PUT  (0) 2023.07.12
[Spring Boot] GET  (0) 2023.07.12
[Spring Boot] 스프링 부트란  (0) 2023.07.12
[Web] HTTP Protocal  (0) 2023.07.12