Step-by-Step
[Spring] ResponseEntity<T> 로 응답 구성하기 본문
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
'IT 기술' 카테고리의 다른 글
[MySQL] MyBatis에서 Auto_Increment 값 조정하기 (0) | 2023.02.22 |
---|---|
[MySQL] 최신 PK 값 가져오기 - last_insert_id() (0) | 2023.02.22 |
HTTP 상태 코드 (Http Status Code) (0) | 2023.02.18 |
[Kafka] 아파치 카프카에 대한 이해 (0) | 2022.05.21 |
REST API에 대한 이해 (0) | 2022.04.29 |
Comments