네로개발일기

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

1. ResponseEntity

- Spring 프레임워크에는 HTTP Request 혹은 Response을 나타내기 위해 HttpEntity 클래스가 존재한다.

- HttpEntity 클래스는 HttpHeader, HttpBody가 있다.

- HttpEntity를 상속하여 추가적으로 HttpStatus 속성이 있는 클래스가 RequestEntity, ResponseEntity 클래스가 있다.

 

[사용법]

1) static method를 사용하여 ResponseEntity 반환

@GetMapping("/v1")
public ResponseEntity<String> getV1() {
    return ResponseEntity.ok("hello world!");
}
// response

HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 12
Data: Wed, 29 Mar 2023 16:17:22 GMT
Keep-Alive: timeout=60
Connection: keep-alive

hello world!

- ResponseEntity에는 자주 쓰이는 HttpStatus로 쉽게 인스턴스를 생성할 수 있는 static 메서드를 제공한다.

- OK(200), CREATED(201), NO_CONTENT(204), NOT_FOUND(404) 등

 

2) 생성자를 이용한 ResponseEntity 반환

@GetMapping("/v2")
public ResponseEntity<String> getV2() {
    return new ResponseEntity("hello world!", HttpStatus.OK);
}
// response

HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 12
Data: Wed, 29 Mar 2023 16:17:22 GMT
Keep-Alive: timeout=60
Connection: keep-alive

hello world!

- ResponseEntity는 여러 생성자를 지원하여 HttpBody, HttpHeader, HttpStatus 케이스를 유연하게 오버로딩 되어있다.

 

3) HttpHeader 추가하기

@GetMapping("/v3")
public ResponseEntity<String> getV3() {
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("test", "header-value");
    
    return new ResponseEntity("hello world!", headers, HttpStatus.OK);
}
// response

HTTP/1.1 200
test: header-value
Content-Type: text/plain;charset=UTF-8
Content-Length: 12
Data: Wed, 29 Mar 2023 16:17:22 GMT
Keep-Alive: timeout=60
Connection: keep-alive

hello world!

- MultiValueMap 타입을 가지는 Header를 정의할 수 있다.

 

2. @ResponseStatus

- HttpStatus를 다른 방식으로 표현한 어노테이션이다.

- 컨트롤러단에서 반환하는 Body를 감싸 @ResponseStatus에 정의된 HttpStatus를 추가할 수 있지만 주로 예외처리에서 쓰인다.

 

[사용법]

1) Controller 에서 사용

@GetMapping("/v4")
@ResponseStatus(value = HttpStatus.OK)
public String getV4() {
    return "hello world!";
}
// response

HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 12
Data: Wed, 29 Mar 2023 16:17:22 GMT
Keep-Alive: timeout=60
Connection: keep-alive

hello world!

- ModelAndView로 반환하는 @Controller가 아닌 텍스트 Body를 반환하는 @RestController 기준으로 작성되었다.

- @ResponseStatus에 정의된 HttpStatus로 반환된다.

- ResponseEntity 클래스처럼 유연하지 않다. 커스텀 header 정의도 불가능하며 반환값에 추가적인 작업도 불가능하다.

- default 값은 HttpStatus.INTENAL_SERVER_ERROR(500) 이다.

 

2) Exception 으로 활용

@ReponseStatus(value = HttpStatus.NOT_FOUND)
@Slf4j
public class MyResponseCustomException extends RuntimeException {
    
    public MyResponseCustomException(String message) {
        super(message);
        log.error(message);
    }
}

- 기본적인 Spring Web MVC는 로직상 Exception이 발생하면 HttpStatus.INTERNAL_SERVER_ERROR를 반환한다.

- Exception에 @ResponseStatus를 정의하면 해당 HttpStatus로 반환할 수 있다.

 

3) @ControllerAdvice로 활용

@RestControllerAdvice
public class MyResponseGlobalExceptionHandler {

    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    @ExceptionHandler(MyResponseCustomException.class)
    public String myResponseGlobalExceptionHandler(MyResponseCustomException ex) {
        return ex.getMessage();
    }
}

- @ControllerAdvice 혹은 @ExceptionHandler에서도 활용할 수 있다.

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !