
MVC 패턴을 이해하기 위해, 클라이언트와 서버 간 규약인 HTTP - Response에 대해 설명하고 있습니다.
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ
1. Server 에서 HTML 을 내려 줄 때
1.1. 정적(static) 웹 페이지 내려주기

1. Controller가 Client 의 요청을 "Model"로 받아 처리
예시) 회원가입을 위한 개인 정보들 (id, password, name)
2. Client 에게 "View(정적 웹 페이지, HTML)"를 내려줌
1.2. 동적(dynamic) 웹 페이지 내려주기

1. Controlle가 Client 의 요청을 "Model"로 받아 처리
2. Template engine 에게 "View, Model" 전달
- View: 동적 HTML 파일
- Model: View 에 적용할 정보들
3. Template engine은 "View" 에 "Model" 을 적용 → 동적 웹페이지 생성
예시) 로그인 성공 시, "로그인된 사용자의 id" 를 페이지에 추가
Template engine 종류: 타임리프 (Thymeleaf), Groovy, FreeMarker, Jade 등 (스프링에서 JSP 이용은 추천하지 않고 있음)
4. Client 에게 "View(동적 웹 페이지, HTML)"를 내려줌
2. HTTP 메시지 이해
Client 와 Server 간
Request, Response 는 HTTP 메시지 규약을 따릅니다.
2.1. HTTP 메시지 구조

1. 시작줄 (start line) -> Response 에선 '상태줄 (status line)' 이라고 부름
2. 헤더 (headers)
3. 본문 (body)
3. HTTP - Request 메시지
3.1. 시작줄: API 요청 내용
<bash />GET naver.com HTTP/1.1
3.2. 헤더의 "Content type"
- 내용 없음
- HTML <form> 태그로 요청 시
<bash />
Content type: application/x-www-form-urlencoded
- AJAX 요청
<bash />
Content type: application/json
3.3. 본문
- GET 요청 시: (보통) 없음
- POST 요청 시: (보통) 사용자가 입력한 폼 데이터
<bash />name=김혜린&age=20
4. HTTP - Response 메시지
4.1. 상태줄: API 요청 결과 (상태 코드, 상태 텍스트)
<bash />HTTP/1.1 404 Not Found
4.2. 헤더의 "Content type"
- 내용 없음
- Response 본문 내용이 HTML인 경우
<bash />
Content type: text/html
- Response 내용이 JSON인 경우
<bash />
Content type: application/json
4.3. 헤더의 "Location"
Redirect 할 페이지 URL
<bash />Location: http://localhost:8080/hello.html
4.4. 본문
- HTML
<bash /><!DOCTYPE html> <html> <head><title>By @ResponseBody</title></head> <body>Hello, Spring 정적 웹 페이지!!</body> </html>
- JSON
<bash />
{
"name":"홍길동",
"age": 20
}
5. Controller의 요청 -> HTTP Response 메시지

5.1. 정적 웹페이지 - static 폴더
요청 :
<bash />http://localhost:8080/hello.html
응답 :
<bash />resources/static/hello.html
5.2. 정적 웹페이지 - Redirect
요청 :
<bash />http://localhost:8080/hello/response/html/redirect
응답 :
<bash />
@Controller
@RequestMapping("/hello/response")
public class HelloResponseController {
@GetMapping("/html/redirect")
public String htmlFile() {
return "redirect:/hello.html";
}
}
5.3. 정적 웹페이지 - Template engine 에 View 전달
요청 :
<bash />
@GetMapping("/html/templates")
public String htmlTemplates() {
return "hello";
}
응답 :
<bash />http://localhost:8080/hello/response/html/templates
타임리프 default 설정
- prefix: classpath:/templates/
- suffix: .html
<bash />resources/templates/hello.html
5.4. 정적 웹페이지 - @ResponseBody
요청 :
<bash />http://localhost:8080/hello/response/html/templates
응답 :
<bash />
@GetMapping("/body/html")
@ResponseBody
public String helloStringHTML() {
return "<!DOCTYPE html>" +
"<html>" +
"<head><title>By @ResponseBody</title></head>" +
"<body> Hello, 정적 웹 페이지!!</body>" +
"</html>";
}
@ResponseBody : View 를 사용하지 않고, HTTP Body 에 들어갈 String 을 직접 입력
5.5. 동적 웹페이지
<bash />http://localhost:8080/hello/response/html/dynamic
<bash />
private static long visitCount = 0;
@GetMapping("/html/dynamic")
public String helloHtmlFile(Model model) {
visitCount++;
model.addAttribute("visits", visitCount);
return "hello-visit";
}
View, Model 정보를 타임리프에게 전달
5.5.1. 타임리프 처리방식 (뷰 템플릿 엔진)
View 정보
"hello-visit" 을 return → resources/templates/hello-visit.html 을 내려줌
<bash />
<div>
(방문자 수: <span th:text="${visits}"></span>)
</div>
Model 정보
visits: 방문 횟수 (visitCount)
예) 방문 횟수: 1,000,000 번
<bash /><div> (방문자 수: <span>1000000</span>) </div>
5.5.2. JSON 데이터
1. 반환값: String
<bash />http://localhost:8080/hello/response/json/string
<bash />
@GetMapping("/json/string")
@ResponseBody
public String helloStringJson() {
return "{\"name\":\"BTS\",\"age\":28}";
}
2. 반환값: String 외 자바 클래스
<bash />http://localhost:8080/hello/response/json/class
<bash />
@GetMapping("/json/class")
@ResponseBody
public Star helloJson() {
return new Star("BTS", 28);
}
6. Response 내려주기의 종류
- 정적 웹페이지
- 동적 웹페이지
- JSON 데이터

7. Response를 통한 스프링 MVC 동작 원리 이해하기

1. Client → DispatcherServlet
- 가장 앞 단에서 요청을 받아 FrontController 라고도 불림
2. DispatcherServlet → Controller
- API 를 처리해 줄 Controller 를 찾아 요청을 전달
- Handler mapping 에는 API path 와 Controller 함수가 매칭되어 있음
- Controller 에서 요청하는 Request 의 정보 ('Model') 전달
<bash />
@Controller
public class ItemSearchController {
@GetMapping("/api/search")
@ResponseBody
public List<ItemDto> getItems(@RequestParam String query) {
// ...
}
}
3. Controller → DispathcerServlet
- Controller 가 Client 으로 받은 API 요청을 처리
- 'Model' 정보와 'View' 정보를 DispatcherServlet 으로 전달
4. DispatcherServlet → Client
- ViewResolver 통해 View 에 Model 을 적용
- View 를 Client 에게 응답으로 전달
Client -> DispathcherServlet -> (Handler Mapping) Controller -> DispatcherServlet -> Client

'Spring' 카테고리의 다른 글
Spring - @Transactional (0) | 2023.02.14 |
---|---|
Spring - 생성자 생성 어노테이션 (0) | 2023.01.28 |
Repository를 선언할 때 final을 붙이는 이유 (0) | 2022.11.23 |
추상 클래스와 인터페이스의 차이, 모듈의 뜻 (0) | 2022.11.23 |
Domain이란? (0) | 2022.11.21 |