[Spring] Note0. ResponseEntity

2026. 2. 14. 16:28·🌱 Spring Framework
반응형

Note1. ResponseEntity 

ResponseEntity란 Spring Framework에서 Http 요청에 대한 응답을 제어하기 위해 제공하는 클래스이다. 

ReponseEntity에는 Http Protocol 표준에 따라 Reponse Body, Header, Status Code 등 다양한 응답 정보를 포함할 수 있다. 

public class ResponseEntity<T> extends HttpEntity<T> {}

 

 

Note2. ResponseEntity 동작 & @RestController

Spring MVC는 기본적으로 Controller의 Return Type을 처리할 때, ResponseEntity 객체가 반환되면 아래와 같이 동작한다.

1. ViewResolver 생략 - @Controller의 경우 리턴값으로 문자열이 들어오면 HTML 파일을 탐색하지만 ResponseEntity는 이 탐색 과정을 생략한다. 

2. HttpMessageConverter 사용 - ResponseEntity 안에 담긴 객체를 JSON 혹은 XML 형태로 반환하기 위한 컨버터를 호출한다.

ResponseEntity를 사용할 때 반드시 @RestController 어노테이션과 함께 사용해야 하는 것은 아니지만 주로 @RestController를 사용해 모든 메서드는 데이터를 반환한다는 것을 명시하는 것이 가독성 측면에서 효율적이다. 

 

Note3. ResponseEntity.status() 

.status() 메서드를 사용해 특정 HTTP Status Code를 직접 설정 가능하며 아래와 같은 상태 상수를 제공한다. 

HttpStatus.OK (200) - 성공 
HttpStatus.CREATED (201) - 생성 성공
HttpStatus.BAD_REQUEST (400) - 잘못된 요청 
HttpStatus.UNAUTHORIZED (401) - 인증 필요
HttpStatus.FORBIDDEN (403) - 권한 없음
HttpStatus.NOT_FOUND (404) - 리소스 없음 
HttpStatus.INTERNAL_SERVER_ERROR (500) - 서버 오류 

 

 

Note4. Login Example

로그인 로직에 따른 적절한 상태코드를 부여한뒤 에러를 핸들링한 로그인 예제이다. 

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController {

    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody LoginDTO loginRequest) {
        try {
            // 사용자 인증
            Optional<User> userOpt = authService.validateUser(
                    loginRequest.getUserId(),
                    loginRequest.getPassword());

            if (userOpt.isPresent()) {
                // 로그인 성공
                LoginResponseDTO response = authService.login(userOpt.get());
                return ResponseEntity.ok(response);
            }

            else {
                // 인증 실패 (비밀번호 오류 또는 사용자 없음)
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(Map.of("message", "Invalid user ID or password"));
            }
        }

        catch (UserNotApprovedException e) {
            // 승인되지 않은 계정
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(Map.of("message", e.getMessage()));
        }

        catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("message", "Login failed: " + e.getMessage()));
        }
    }
}

 

반응형
저작자표시 비영리 변경금지 (새창열림)

'🌱 Spring Framework' 카테고리의 다른 글

[Spring] Note2. @Configuration @Value  (0) 2026.02.19
[Spring] Note1. Flyway Setting  (0) 2026.02.15
'🌱 Spring Framework' 카테고리의 다른 글
  • [Spring] Note2. @Configuration @Value
  • [Spring] Note1. Flyway Setting
novs
novs
https://github.com/novvvv
    반응형
  • novs
    nov.Zip
    novs
  • 전체
    오늘
    어제
    • All (380)
      • Project (2)
        • Rag Blog (2)
      • 🌱 Spring Framework (27)
        • Java Fundamental (13)
        • SpringSecurity (1)
        • Multi Thread Programming (3)
        • Spring Framework (3)
        • JPA (4)
      • 🔓 Security (1)
      • Cloud (2)
        • Docker (1)
        • AWS (1)
      • Mobile Development (0)
      • dev (7)
        • Git (2)
        • React (2)
        • Android (1)
        • Computer Science (2)
      • Algorithm (29)
        • PS With C++ (8)
        • Algorithm (2)
        • BOJ (16)
        • AtCoder (3)
      • Archive (312)
        • 동아리 사이트 개발일지 (3)
        • 카페 주문 시스템 (3)
        • UIKit (2)
        • Swift Language (3)
        • PS With Swift (2)
        • Next.js (3)
        • React (2)
        • Git (1)
        • Linux (3)
        • Vue.js (2)
        • Flutter (11)
        • ...2022 (34)
        • ...2024 (2)
        • C# (14)
        • C&C++ (47)
        • GameDevelop (19)
        • WEB (32)
        • CS (7)
        • Algorithm (13)
        • ProblemSolving (105)
        • Daily (2)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    다이나믹프로그래밍
    C++
    STL
    javascript
    소스코드
    C언어
    js
    C++문법
    프로그래머스
    c#
    알고리즘
    BOJ
    자바스크립트
    유니티
    dp
    백준
    스택
    C
    그리디
    문제풀이
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
novs
[Spring] Note0. ResponseEntity
상단으로

티스토리툴바