Spring Boot 프로젝트에서 ResponseEntity 는 HTTP 응답을 효과적으로 제어하고 다양한 측면에서 사용자에게 정확한 응답을 제공하는 데 사용됩니다.
ResponseEntity
ResponseEntity 는 HTTP 응답을 나타내는 Spring Framework 의 클래스입니다.
이 클래스는 요청에 대한 응답의 HTTP Header , Status Code 를 포함하여 클라이언트에게 전달할 수 있는 다양한 기능을 제공합니다.
사용하는 이유
ResponseEntity 를 사용하면 응답에 대한 HTTP 상태 코드를 명시적으로 지정할 수 있습니다.
이는 클라이언트에게 정확한 상태 정보를 제공하는 데 도움이 됩니다.
또한 응답 본문과 헤더를 세밀하게 제어할 수 있습니다.
ResponseEntity 에서 자주 사용되는 HTTP 상태 코드
상태 코드는 100 ~ 500 까지 매우 다양하게 있습니다.
ResponseEntity 는 아래와 같은 코드들을 지원해 줍니다.
HttpStatus.OK - 200 OK
HttpStatus.CREATED - 201 Created
HttpStatus.NO_CONTENT - 204 No Content
HttpStatus.BAD_REQUEST - 400 Bad Request
HttpStatus.UNAUTHORIZED - 401 Unauthorized
HttpStatus.NOT_FOUND - 404 Not Found
HttpStatus.INTERNAL_SERVER_ERROR - 500 Internal Server Error
사용방법
ok
HTTP 200 Status code 와 함께 Response 를 생성합니다.
이는 가장 일반적으로 사용되는 메서드 중 하나입니다.
ResponseEntity.ok(넘겨줄데이터);
ResponseEntity.status(HttpStatus.OK).body(넘겨줄 데이터);
...
status
특정 HTTP Status code 를 직접 설정할 수 있습니다. 이는 더 유연한 Response 처리가 필요할 때 유용합니다.
@PostMapping("/create")
public ResponseEntity<String> createProduct(@RequestBody Product product) {
boolean isCreated = productService.create(product);
return ResponseEntity.status(isCreated ? HttpStatus.CREATED : HttpStatus.BAD_REQUEST)
.body(isCreated ? "Product created successfully" : "Error creating product");
}
notFound
HTTP 404 Status code 를 설정할 때 사용합니다.
자원을 찾을 수 없을 때 클라이언트에게 명확하게 알려줄 수 있습니다.
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable String id) {
User user = userService.findById(id);
if (user == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(user);
}
badRequest
HTTP 400 Status code 와 함께 Response 를 생성할 때 사용합니다.
입력 데이터에 오류가 있을 때 유용하게 사용할 수 있습니다.
@PostMapping("/update")
public ResponseEntity<String> updateUser(@RequestBody User user) {
if (user.getId() == null) {
return ResponseEntity.badRequest().body("USer ID is required");
}
userService.update(user);
return ResponseEntity.ok("User updated successfully");
}
created
HTTP 201 Status code 와 함께 Response 를 생성할 때 사용됩니다.
새로운 Resource 가 성공적으로 생성되었을 때 이 메서드를 사용하실 수 있습니다.
@PostMapping("/users")
public ResponseEntity<User> addUser(@RequestBody User user) {
User createdUser = userService.addUser(user);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(createdUser.getId())
.toUri();
return ResponseEntity.created(location).body(createdUser);
}
noContent
HTTP 204 Status code 와 함께 Response 를 생성할 때 사용됩니다.
주로 삭제요청이나 업데이트 후 body 가 필요 없는 경우 사용됩니다.
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable String id) {
userService.delete(id);
return ResponseEntity.noContent().build();
}
accepted
HTTP 202 Status code 와 함께 Response 를 생성할 대 사용됩니다.
처리가 아직 완료되지 않았지만 시작되었음을 클라이언트에 알릴 때 사용할 수 있습니다.
@PostMapping("/process")
public ResponseEntity<Void> processRequest(@RequestBody RequestData data) {
processService.startProcess(data);
return ResponseEntity.accepted().build();
}
'Spring' 카테고리의 다른 글
@Scheduled (0) | 2025.01.24 |
---|---|
@Controller 와 @RestController (2) | 2025.01.22 |
JSON 형태로 객체 반환하기 (1) | 2025.01.15 |
빈 생명주기 콜백 (1) | 2025.01.09 |
스프링에서 조회 대상 빈이 2개 이상일 때 해결 방법 (0) | 2025.01.08 |