Response 내려주는 방법

2263 단어 SpringSpring

Text

    @GetMapping("/text")
    public String text(@RequestParam String account){
        return account;
    }

Talend API Tester로 실행

account에 넘긴 값이 그대로 잘 넘어왔다.

Json

@PostMapping("/json")
    public User json(@RequestBody User user){
        return user;
    }

request는 아래와 같은 과정으로 처리가 된다.

json(request) -> object mapper -> object
-> method
-> object -> object mapper -> json(response)

object mapper가 json(text) <-> object 변환을 처리하여, json통신을 쉽게 할 수 있다.

아래와 같은 json으로 post 요청을 보내보자.

응답은 잘 왔지만, phoneNumber가 null이다.

그 이유는 서버 코드는 핸드폰 번호를 담는 변수를 phoneNumber로 선언하고, request는 phone_number로 보냈기 때문이다.

즉, Camel case와 Snake case의 차이에서 발생하는 문제이다.
2가지 방법으로 처리할 수 있다.

dto 클래스 멤버 변수위에 @JsonProperty("처리할 변수명")를
추가하여 처리할 수도 있고,

@JsonProperty("phone_number")
private String phoneNumber;

dto 클래스에 @JsonNaming을 추가하여 처리할 수도 있다. 이 방법을 사용하면, 처리할 방법이 모든 멤버 변수에 적용된다.

@JsonNaming(value = PropertyNamingStrategy.SnakeCaseStrategy.class)

서버 재실행 후 다시 request를 보내면, 이제 phone_number를 잘 읽는다.

ResponseEntity

ResponseEntity<>를 이용하여 header와 body, 상태 코드등을 추가하여 리턴할 수 있다.

@PutMapping("/put")
public ResponseEntity<User> put(@RequestBody User user){
        return ResponseEntity.status(HttpStatus.CREATED).body(user);
}

같은 request를 보내면 아래와 같은 응답을 받을 수 있다.

좋은 웹페이지 즐겨찾기