Burninghering's Blog
article thumbnail

MVC 패턴을 이해하기 위해, 클라이언트와 서버 간 규약인 HTTP - Response에 대해 설명하고 있습니다.
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

Server 에서 HTML 을 내려 줄 때

정적(static) 웹 페이지 내려주기

1. Controller가 Client 의 요청을 "Model"로 받아 처리

예시) 회원가입을 위한 개인 정보들 (id, password, name)

 

2. Client 에게 "View(정적 웹 페이지, HTML)"를 내려줌

 

 

동적(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)"를 내려줌

 

 


HTTP 메시지 이해

Client 와 Server 간

Request, Response 는 HTTP 메시지 규약을 따릅니다.

 

HTTP 메시지 구조

1. 시작줄 (start line) -> Response 에선 '상태줄 (status line)' 이라고 부름

2. 헤더 (headers)

3. 본문 (body)


HTTP - Request 메시지

시작줄: API 요청 내용

GET naver.com HTTP/1.1

 

헤더의 "Content type"

- 내용 없음

- HTML <form> 태그로 요청 시

Content type: application/x-www-form-urlencoded

- AJAX 요청

Content type: application/json

 

본문

- GET 요청 시: (보통) 없음

- POST 요청 시: (보통) 사용자가 입력한 폼 데이터

name=김혜린&age=20

HTTP - Response 메시지

상태줄: API 요청 결과 (상태 코드, 상태 텍스트)

HTTP/1.1 404 Not Found

 

헤더의 "Content type"

- 내용 없음

- Response 본문 내용이 HTML인 경우

Content type: text/html

- Response 내용이 JSON인 경우

Content type: application/json

 

헤더의 "Location"

Redirect 할 페이지 URL

Location: http://localhost:8080/hello.html

 

본문

- HTML

<!DOCTYPE html>
<html>
  <head><title>By @ResponseBody</title></head>
   <body>Hello, Spring 정적 웹 페이지!!</body>
</html>

- JSON

{ 
  "name":"홍길동",
  "age": 20
}

Controller의 요청 ->  HTTP Response 메시지

 

정적 웹페이지 - static 폴더

요청 : 

http://localhost:8080/hello.html

응답 :

resources/static/hello.html

 

정적 웹페이지 - Redirect

요청 :

http://localhost:8080/hello/response/html/redirect

응답 : 

@Controller
@RequestMapping("/hello/response")
public class HelloResponseController {

	@GetMapping("/html/redirect")
    public String htmlFile() {
        return "redirect:/hello.html";
    }
}

 

정적 웹페이지 - Template engine 에 View 전달

요청 : 

@GetMapping("/html/templates")
public String htmlTemplates() {
    return "hello";
}

 

응답 :

http://localhost:8080/hello/response/html/templates

 

타임리프 default 설정

  • prefix: classpath:/templates/
  • suffix: .html
resources/templates/hello.html

 

정적 웹페이지 - @ResponseBody

요청 :

http://localhost:8080/hello/response/html/templates

 

응답 :

@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 을 직접 입력


동적 웹페이지

http://localhost:8080/hello/response/html/dynamic
private static long visitCount = 0;

@GetMapping("/html/dynamic")
public String helloHtmlFile(Model model) {
    visitCount++;
    model.addAttribute("visits", visitCount);
    return "hello-visit";
}

View, Model 정보를 타임리프에게 전달

 

타임리프 처리방식 (뷰 템플릿 엔진)

View 정보

"hello-visit" 을 return → resources/templates/hello-visit.html 을 내려줌

<div>
  (방문자 수: <span th:text="${visits}"></span>)
</div>

 

Model 정보

visits: 방문 횟수 (visitCount)

예) 방문 횟수: 1,000,000

<div>
  (방문자 수: <span>1000000</span>)
</div>

JSON 데이터

1. 반환값: String

http://localhost:8080/hello/response/json/string
@GetMapping("/json/string")
@ResponseBody
public String helloStringJson() {
    return "{\"name\":\"BTS\",\"age\":28}";
}

 

2. 반환값: String 외 자바 클래스

http://localhost:8080/hello/response/json/class
@GetMapping("/json/class")
@ResponseBody
public Star helloJson() {
    return new Star("BTS", 28);
}

Response 내려주기의 종류

  • 정적 웹페이지
  • 동적 웹페이지
  • JSON 데이터


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

1. Client → DispatcherServlet

  • 가장 앞 단에서 요청을 받아 FrontController 라고도 불림

2. DispatcherServlet → Controller

  • API 를 처리해 줄 Controller 를 찾아 요청을 전달
  • Handler mapping 에는 API path 와 Controller 함수가 매칭되어 있음
  • Controller 에서 요청하는 Request 의 정보 ('Model') 전달
@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

profile

Burninghering's Blog

@개발자 김혜린

안녕하세요! 반갑습니다.