응답 리턴시 응답값을 리턴하는 방식이다.
1. @ResponseStatus
- 컨트롤러 메소드 어노테이션이다. 항상 같은 코드를 반환할때 사용한다.
- 특정 예외가 발생했을 때 공통적으로 상태 코드를 지정하고 싶을 때 사용한다.
- value, reason을 통해 코드와 메세지를 리턴할 수 있다.
@GetMapping("/created")
@ResponseStatus(HttpStatus.CREATED) // 항상 201 반환
public String created() {
return "리소스가 생성되었습니다";
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "잘못된 요청입니다")
public class BadRequestException extends RuntimeException {}
2. ResponseEntity
- 어노테이션이 아니다. 싱글톤으로, 각기 다른 코드를 리턴할때 사용한다.
- 헤더, 본문 모두 제어가 가능하다.
- 컨트롤러 내 각 메소드에서 조건에 따라 다른 코드를 리턴할 수 있다.
- 이 방식을 가장 많이 사용되고 권장된다
@GetMapping("/user/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Not Found"));
return ResponseEntity
.ok(user); // 상태 200 + body(user)
}
//헤더 포함
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
User savedUser = userRepository.save(user);
return ResponseEntity
.status(HttpStatus.CREATED)
.header("Location", "/users/" + savedUser.getId())
.body(savedUser);
}
'Backend > SpringBoot' 카테고리의 다른 글
| 클라이언트의 파일을 받아 처리하기 (0) | 2025.09.15 |
|---|---|
| @RequestBody, @ResponseBody (0) | 2025.09.15 |
| @Controller exception 처리 (@ControllerAdvice, @RestControllerAdvice) (0) | 2025.09.15 |
| Controller 에서 각종 파라메터 받기 + Cookie (0) | 2025.09.12 |
| Main DB (Postgresql) + Cache (Redis) 사용하기 (0) | 2025.09.03 |