Step-by-Step

[Spring] ResponseEntity<T> 로 응답 구성하기 본문

IT 기술

[Spring] ResponseEntity<T> 로 응답 구성하기

희주(KHJ) 2023. 2. 20. 16:38

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

 

ResponseEntity (Spring Framework 6.0.5 API)

Create a ResponseEntity with a body, headers, and a raw status code.

docs.spring.io

 

ResponseEntity

  • Header + Body 구성인 HttpEntity에서 HttpStatusCode를 추가하여 기능을 확장한 클래스
  • ResponseEntity<T> 에서 T는 Body로 넣은 타입으로 생각하면 됨

 

 

 

ResponseDTO

 

@Getter
@Setter
@AllArgsConstructor
public class ResponseDTO {
	public String message;
}
  • Response Body 정보를 담을 JAVA class 작성
  • ResponseEntity 클래스에서 자동으로 Key-Value로 변환해서 넘겨줌

 

 

Controller

 

@RestController
@RequestMapping("/test")
public class TestController {
	
	@PostMapping("/entity")
	public ResponseEntity<ResponseDTO> register(UserDTO userDTO) {
		System.out.println("entity");
		
		if(!userDTO.isNotNull())
			return new ResponseEntity<>(new ResponseDTO("잘못된 요청"), HttpStatus.BAD_REQUEST);
		
		return new ResponseEntity<>(new ResponseDTO("올바른 요청"), HttpStatus.OK);
	}
	
}

 

 

 

 

결과

 

사용자 정보를 모두 채워서 보낸 경우 → 올바른 요청, 200 OK

 

request Body 없이 요청한 경우 → 잘못된 요청, 400 Bad Request

 

 

 

Comments