Spring
ResponseEntity에 대해 알아보기
LearnerKSH
2020. 11. 6. 01:29
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 됨을 확인하였다.
반응형