Spring - ResponseEntity,RequestEntity

유재학·2022년 11월 16일
0

지난 포스트에 @RestController는 객체 데이터를 JSON 또는 XML형태로 HTTP응답에 담아 전달하며 주로 ResponseEntity에 감싸서 반환한다는 내용이 있었습니다. 이번 포스트에서는 ResponseEntity가 무엇인지, RequestEntity까지 함께 정리해보도록 하겠습니다.

ResponseEntity

ResponseEntity는 스프링 프레임워크에서 제공하는 클래스인 HttpEntity클래스를 상속받으며 응답 자체의 독립된 값이나 표현을 사용자 요청에 대한 응답 데이터와 함께 포함하는 클래스로, 해당 클래스를 이용하여 HTTP 메시지를 상세하게 보낼 때 주로 사용합니다.

ResponseEntity에는 HttpHeaders, HttpBody, HttpStatus가 포함되며 각 요소가 나타내는 것은 다음과 같습니다.

  • HttpHeaders : 메시지 헤더(조건이나 요구사항)
    • Location : 서버의 응답이 다른 곳에 있으니 사용자의 위치를 리다이렉트 하기 위한 URI지정
    • Server : 서버 종류
    • Referrer Policy : 서버 Referrer 정책을 알려주는 값
    • WWW-Authenticate : 사용자 인증이 필요한 자원을 요구할 시 서버가 제공하는 인증 방식
    • Proxy-Authenticate : 요청한 서버가 프록시 서버인 경우 유저 인증을 위한 값
  • HttpBody - 메시지 본문
  • HttpStatus - 상태코드

예시코드

@PostMapping("/signup")
public ResponseEntity<MemberVO> doSignup(@ModelAttribute MemberDTO memberDTO,
                       BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
        bindingResult.getAllErrors().forEach(error -> System.out.println(error));
        return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
    }

    boolean res = memberService.signup(memberDTO.getuId(), memberDTO.getuPwStr(), memberDTO.getuEmail());
    System.out.println(res);
    return new ResponseEntity<>(memberService.getByUserId(memberDTO.getuId()).toVO(), HttpStatus.OK);
}

RequestEntity

RequestEntity는 스프링 프레임워크에서 제공하는 클래스인 HttpEntity클래스를 상속받으며 요청 자체의 독립된 값이나 표현을 사용자 요청 데이터와 함께 포함하는 클래스입니다.

RequestEntity는 HttpHeaders, HttpBody, HttpMethod, URI, MediaType을 생성자 파라미터로 넘길 수 있습니다.

예시코드

// header 생성
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");

// url 생성
URI url = URI.create("localhost:8080/");

// requestEntity 생성 (방법1)
//header, method, url 을 파라미터로 하여 생성자 호출
RequestEntity<String> req1 = new RequestEntity<>(headers, HttpMethod.GET, url);

//body 생성
String body = "test"

// requestEntity 생성 (방법2)
RequestEntity<String> req2 = RequestEntity.post(new URI("https://https://mchch.tistory.com/"))
                                          .accept(MediaType.APPLICATION_JSON)
                                          .body(body);
                                          
profile
github : https://github.com/kiaeh2323 , email : kiaeh9269@gmail.com

0개의 댓글