[Spring] ResponseEntity

서현서현·2022년 7월 15일
0

Spring

목록 보기
9/31
post-thumbnail

ResponseEntity

: 일반적인 API는 반환하는 리소스의 종류가 상태코드, 응답메세지, Object 등 다양할것이다. 그럴때 쓴다. 즉 결과데이터와 HTTP 상태코드를 직접 제어할 수 있다.

Rest템플릿 및 @Controller 메소드에 사용한다. HttpEntity 클래스를 상속받는데, 이 클래스는 HTTP 요청(request)과 그에대한 응답(response)에 해당하는 HttpHeader와 HttpBody를 포함하는 클래스이다.

-> 결국 좀 더 세밀한 제어가 되는것이다!

구조

HttpStatus, HttpHeaders, HttpBody를 포함한다.

ResponseEntity 클래스를 사용하면 결과값,상태코드,헤더값을 모두 프론트에 넘겨줄 수 있고, 에러또한 섬세하게 설정해서 보내줄 수 있다는 장점이있다.

사용법

String 내부에 이미 ResponseEntity 객체가 구현되어있고, 우리는 그것을 보고 그대로 사용하면 된다.

public class ResponseEntity<T> extends HttpEntity<T> {

   private final Object status;

   /**
    * Create a {@code ResponseEntity} with a status code only.
    * @param status the status code
    */
   public ResponseEntity(HttpStatus status) {
      this(null, null, status);
   }

   /**
    * Create a {@code ResponseEntity} with a body and status code.
    * @param body the entity body
    * @param status the status code
    */
   public ResponseEntity(@Nullable T body, HttpStatus status) {
      this(body, null, status);
   }

   /**
    * Create a {@code ResponseEntity} with headers and a status code.
    * @param headers the entity headers
    * @param status the status code
    */
   public ResponseEntity(MultiValueMap<String, String> headers, HttpStatus status) {
      this(null, headers, status);
   }

   /**
    * Create a {@code ResponseEntity} with a body, headers, and a status code.
    * @param body the entity body
    * @param headers the entity headers
    * @param status the status code
    */
   public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status) {
      this(body, headers, (Object) status);
   }

   /**
    * Create a {@code ResponseEntity} with a body, headers, and a raw status code.
    * @param body the entity body
    * @param headers the entity headers
    * @param rawStatus the status code value
    * @since 5.3.2
    */
   public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, int rawStatus) {
      this(body, headers, (Object) rawStatus);
   }

   /**
    * Private constructor.
    */
   private ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, Object status) {
      super(body, headers);
      Assert.notNull(status, "HttpStatus must not be null");
      this.status = status;
   }
 }
 

생성자를 다양히 작성해 두어서, status값만 넣거나 body만 넣어도 ResponseEntity값이 null로 들어가는걸 알 수 있다.

예를들면 다음과같다.

@PostMapping("/post/like")
public ResponseEntity<SetLikeDto.Response> updateLike(@RequestBody SetLikeDto.Request postLikeDto, @AuthenticationPrincipal UserDetailsImpl userDetails){
    Post post = postService.setPostLike(postLikeDto,userDetails.getUser());

    SetLikeDto.Response response = modelMapper.map(post, SetLikeDto.Response.class);

    return new ResponseEntity<>(HttpStatus.OK);
    return new ResponseEntity<>(response, HttpStatus.ACCEPTED);
    //지금은 header에 빈 값이 들어간, 비어있는 객체 -> 필요하다면 내용을 채워서 이렇게 생성해줄 수 있다.
    return new ResponseEntity<>(response, new HttpHeaders(HttpHeaders.EMPTY), HttpStatus.ACCEPTED);
}

참고 : https://thalals.tistory.com/268

0개의 댓글