REST API의 경우, HTML을 전달하지 않고 HTTP Message Body에 직접 Data를 JSON 형식으로 담아 전달한다.
정적 HTML, View Template 또한 HTTP Message Body에 담겨서 전달된다.
text 타입의 데이터 전달
1. HttpServletResponse
@Controller
public class ResponseBodyController {
@GetMapping("/v1/response-body")
public void responseBodyV1(HttpServletResponse response
) throws IOException {
response.getWriter().write("data");
}
}
2. ResponseEntity<>
문자열과 상태 코드 함께 전달
@GetMapping("/v2/response-body")
public ResponseEntity<String> responseBodyV2() {
return new ResponseEntity<>("data", HttpStatus.OK);
}
3. @ResponseBody
@Data
@NoArgsConstructor // 기본 생성자
@AllArgsConstructor // 전체 필드를 인자로 가진 생성자
public class Tutor {
private String name;
private int age;
}
// TEXT 데이터 통신
@ResponseBody
@GetMapping("/v3/response-body-text")
public String responseBodyText() {
return "data"; // HTTP Message Body에 "data"
}
JSON 타입의 데이터 전달
1. @ResponseBody
@Data
@NoArgsConstructor // 기본 생성자
@AllArgsConstructor // 전체 필드를 인자로 가진 생성자
public class Tutor {
private String name;
private int age;
}
@ResponseBody
@GetMapping("/v3/response-body-json")
public Tutor responseBodyJson() {
Tutor tutor = new Tutor("wonuk", 100);
return tutor; // HTTP Message Body에 Tutor Object -> JSON
}
2. ResponseEntity<Object>
데이터 객체와 상태 코드를 하나의 Tutor 객체로 묶어서 전달
@ResponseBody
@GetMapping("/v5/response-body")
public ResponseEntity<Tutor> responseBody() {
Tutor tutor = new Tutor("wonuk", 100);
if (조건) {
return new ResponseEntity<>(tutor, HttpStatus.OK);
} else {
return new ResponseEntity<>(tutor, HttpStatus.BAD_REQUEST);
}
}
Server(Spring)에서 HTTP 응답을 Client에 전달하는 세가지 방법
1. 정적 리소스
정적인 HTML, CSS, JS, Image 등을 변경없이 그대로 반환
2. View Template
SSR(Server Side Rendering)을 사용할 때 View 반환
@Controller
3. HTTP Message Body
응답 데이터를 직접 Message Body에 담아 반환
@ResponseBody, ResponseEntity<Object>
'언어, 프레임워크 > Spring' 카테고리의 다른 글
[부트캠프 5주차] 새로 알게된 개념, 메서드 정리 (0) | 2025.03.23 |
---|---|
Spring Boot의 예외처리 (유효성 검사) (0) | 2025.03.20 |
요청(Request) 데이터 전달 방식 (0) | 2025.03.20 |
Spring Annotation (+Request Mapping) (0) | 2025.03.19 |
Spring MVC (0) | 2025.03.19 |