[Spring Boot] ResponseEntity

노성빈·2024년 4월 30일

Spring Boot

목록 보기
5/6
post-thumbnail

📌 응답의 종류

  • String : 일반 Text Type 응답
  • Object : 자동으로 Json으로 반환되어 응답, 상태값은 항상 200 OK
  • ResponseEntity : Body의 내용을 Object로 설정, 상황에 따라서 HttpStatus 설정
  • @ResponseBody : RestController가 아닌 곳(Controller)에서 Json응답을 내릴 때

✏️ ResponseEntity

HTTP status를 설정할 때 사용할 수 있다.

예제

@GetMapping("")
    public ResponseEntity<UserRequest> user() {

        var user = new UserRequest();
        user.setUserName("홍길동");
        user.setUserAge(10);
        user.setEmail("hong@gmail.com");

        log.info("user : {}", user);

        var response = ResponseEntity
                .status(HttpStatus.CREATED)
                .header("x-custom", "hi")
                .body(user);

        return response;

.status() : 매개변수에 HttpStatus.xx 를 통해 HttpStatus를 지정할 수 있다.
.body() : 매개변수에 반환할 객체, 변수를 넣어 정할 수 있다.
.header() : 헤더 이름, 내용을 넣어 원하는 내용을 넣을 수 있다.

0개의 댓글