응답
1. String : 일반 Text Type 응답
2. Object : 자동으로 Json 변환되어 응답 상태값은 항상 200 OK
3. ResponseEntity : Body의 내용을 Object로 설정 상황에 따라서 HttpStatus Code 설정
4. @ResponseBody : RestController가 아닌곳(Controller)에서 Json 응답을 내릴 때
Spring Boot에서 ResponseEntity는 HTTP 응답을 보다 세밀하게 제어할 수 있는 방법을 제공합니다. ResponseEntity를 사용하면 상태 코드, 본문(body), 헤더(headers)를 모두 설정할 수 있습니다.
ResponseEntity의 구성 요소
- Status Code: HTTP 상태 코드를 설정할 수 있습니다.
- Body: 응답 본문을 설정할 수 있습니다.
- Headers: 응답 헤더를 설정할 수 있습니다.
@RestController
@RequestMapping("/api/v1")
@Slf4j
public class ResponseController {
// http://localhost:8888/api/v1
@GetMapping("")
public ResponseEntity<UserRequest> user(){
var user = new UserRequest();
user.setUsername("홍길동");
user.setUserAge(10);
user.setEmail("hong@gmail.com");
log.info("user: {}", user);
var response = ResponseEntity
.status(HttpStatus.OK)
.body(user);
return response;
}
}
정적 팩토리 메서드 공통 응답 코드
- of: 객체를 생성하는 일반적인 메서드. 주로 여러 인자를 받아 객체를 생성할 때 사용됩니다.
- ok: 성공 상태의 객체를 생성할 때 사용됩니다.
- create: 객체를 생성할 때 사용됩니다.
- getInstance: 싱글톤 패턴에서 인스턴스를 반환할 때 사용됩니다.
- newInstance: 새로운 인스턴스를 생성할 때 사용됩니다.
- valueOf: 주로 문자열이나 다른 타입을 변환하여 객체를 생성할 때 사용됩니다.
- from: 다른 타입의 객체를 기반으로 새로운 객체를 생성할 때 사용됩니다.
- empty: 빈 객체를 생성할 때 사용됩니다.
- success: 성공 상태의 객체를 생성할 때 사용됩니다.
- failure: 실패 상태의 객체를 생성할 때 사용됩니다.
- error: 에러 상태의 객체를 생성할 때 사용됩니다.
- ofNullable: null을 허용하는 객체를 생성할 때 사용됩니다.
import lombok.Getter;
import org.springframework.http.HttpStatus;
@Getter
public class CustomResponse<T> {
private int code;
private HttpStatus status;
private String message;
private T data;
// Constructor without data
public CustomResponse(HttpStatus status, String message) {
this(status, message, null);
}
// Constructor with data
public CustomResponse(HttpStatus status, String message, T data) {
this.code = status.value();
this.status = status;
this.message = message;
this.data = data;
}
// Static factory method without data
public static <T> CustomResponse<T> of(HttpStatus status, String message) {
return new CustomResponse<>(status, message);
}
// Static factory method with data
public static <T> CustomResponse<T> of(HttpStatus status, String message, T data) {
return new CustomResponse<>(status, message, data);
}
// Convenience method for OK status with data
public static <T> CustomResponse<T> ok(String message, T data) {
return CustomResponse.of(HttpStatus.OK, message, data);
}
// Convenience method for creating a success response
public static <T> CustomResponse<T> success(String message, T data) {
return CustomResponse.of(HttpStatus.OK, message, data);
}
// Convenience method for creating a failure response
public static <T> CustomResponse<T> failure(String message) {
return CustomResponse.of(HttpStatus.BAD_REQUEST, message);
}
// Convenience method for creating an error response
public static <T> CustomResponse<T> error(String message) {
return CustomResponse.of(HttpStatus.INTERNAL_SERVER_ERROR, message);
}
// Convenience method for creating a response from an existing data object
public static <T> CustomResponse<T> from(T data) {
return CustomResponse.of(HttpStatus.OK, "Operation successful", data);
}
}
@RestController
@RequestMapping("/api/v1")
@Slf4j
public class ResponseController {
// http://localhost:8888/api/v1
@GetMapping("")
public CustomResponse<UserRequest> user(){
var user = new UserRequest();
user.setUsername("홍길동");
user.setUserAge(10);
user.setEmail("hong@gmail.com");
log.info("user: {}", user);
return CustomResponse.ok("user 객체 생성", user);
}
}
'스터디 > Victor' 카테고리의 다른 글
[Git ] 깃헙 프로젝트와 이슈 정리하기 (0) | 2024.05.26 |
---|---|
[Spring Boot] 인텔리제이 설정 및 플러그인 (0) | 2024.05.26 |
[Spring Boot] Springdoc-OpenApi ( Swagger ) (0) | 2024.05.26 |
DI 종류는 어떤것이 있고, 이들의 차이는 무엇인가요? (0) | 2024.04.18 |
시간 복잡도 (0) | 2024.04.08 |