728x90
반응형
ResponseEntity
요즘 RESTFul API 가 많이 사용되고있는데, Restful API에서 return Type으로 사용되고있는 ResponseEntity 에 대하여 알아보자.
설명 | 예시 |
HTTP 상태코드 제어 | ResponseEntity.status(HttpStatus.OK).body(testVO) |
결과 데이터를 body에 담아 return | ResponseEntity.status(HttpStatus.OK).body(testVO) |
ResponseEntity는 @ResponseBody 어노테이션과 같은 의미로, ResponseEntity를 return Type으로 지정하면 JSON (default) 또는 Xml Format으로 결과를 내려준다.
200 OK
1) return ResponseEntity.status(HttpStatus.OK).body(testVO);
@GetMapping("")
public ResponseEntity<?> test(HttpServletRequest request) {
TestVO testVO = new TestVO();
testVO.setIdx(1);
testVO.setUserName("kimseohae");
return ResponseEntity.status(HttpStatus.OK).body(testVO);
}
400 BadRequestException
1) return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(testVO);
@GetMapping("")
public ResponseEntity<?> test(HttpServletRequest request) {
TestVO testVO = new TestVO();
testVO.setIdx(1);
testVO.setUserName("kimseohae");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(testVO);
}
500 InternalServerError
1) return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(testVO);
@GetMapping("")
public ResponseEntity<?> test(HttpServletRequest request) {
TestVO testVO = new TestVO();
testVO.setIdx(1);
testVO.setUserName("kimseohae");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(testVO);
}
결론
결과적으로, ResponseEntity를 사용하여 반환되는 Response의 Header의 HTTP Status Code를 직접 제어할 수 있었다. 또한 .body()에 담겨질 객체는 Json 또는 Xml Format으로 Return 됨을 확인하였다.
반응형
'Spring' 카테고리의 다른 글
SpringBoot + ElasticSearch 연동 및 간단 API 호출해보기 (0) | 2021.02.09 |
---|---|
SpringBoot 2.4 + Oralce DB 연동하기 (2) | 2021.02.04 |
SpringBoot + Redis 연동하기 (0) | 2020.01.19 |
스프링부트 공통 Exception 처리하기 (1) | 2020.01.12 |
Reactive Spring / Reactive Programming (1) | 2020.01.11 |