본문 바로가기
카테고리 없음

스프링 MVC

by 소년수 2022. 8. 5.

MVC가 무엇일까?

MVC = (Model - View - Controller)디자인 패턴이다.

 

Server에서 HTML을 내려주는 경우

1. 정적 (static) 웹 페이지

Controller

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

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

   

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

 

 

2.동적 웹페이지 (dynamic)

  1. Client 의 요청을 Model 로 받아 처리
  2. Template engine 에게 View, Model 전달
    1. View: 동적 HTML 파일
    2. Model: View 에 적용할 정보들
  3. Template engine
    1. ViewModel 을 적용 → 동적 웹페이지 생성
      1. 예) 로그인 성공 시, "로그인된 사용자의 id" 를 페이지에 추가
      2. Template engine 종류: 타임리프 (Thymeleaf), Groovy, FreeMarker, Jade 등 (스프링에서 JSP 이용은 추천하지 않고 있음)
  4. Client 에게 View (동적 웹 페이지, HTML) 를 내려줌

이제 MVC관련 프로젝트를 만들어보겠다.

 

처음설정할때 Lombok,Spring Web, Thymeleaf 라이브러리를 선택한다

정적웹페이지인 static/hello.html을 만들어준다

<!DOCTYPE html>
<html>
<head>
		<meta charset="UTF-8">
    <title>Hello Spring</title>
</head>
<body>
Hello, Spring 정적 웹 페이지!!
</body>
</html>

동적웹페이지인 temlplates/hello-visit.html 을 만들어준다

<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Hello Spring</title></head>
<body>
  <div>
    Hello, Spring 동적 웹 페이지!!
  </div>
  <div>
    (방문자 수: <span th:text="${visits}"></span>)
  </div>
</body>
</html>

이제는 이 정적/동적 웹페이지가 작동할 수 있게 Controller도 만들어주어야 한다.

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/hello/response")
public class HelloResponseController {
    // [Response header]
    //   Location: http://localhost:8080/hello.html
    @GetMapping("/html/redirect")
    public String htmlFile() {
        return "redirect:/hello.html";
    }

    // [Response header]
    //   Content-Type: text/html
    // [Response body]
    // * resources/templates/hello.html 의 text 내용
    //   <!DOCTYPE html>
    //   <html>
    //     <head><meta charset="UTF-8"><title>By Templates engine</title></head>
    //      <body>Hello, Spring 정적 웹 페이지!!</body>
    //   </html>
    @GetMapping("/html/templates")
    public String htmlTemplates() {
        return "hello";
    }

    // [Response header]
    //   Content-Type: text/html
    // [Response body]
    //   <!DOCTYPE html>
    //   <html>
    //     <head><meta charset="UTF-8"><title>By @ResponseBody</title></head>
    //      <body>Hello, Spring 정적 웹 페이지!!</body>
    //   </html>
    @GetMapping("/body/html")
    @ResponseBody
    public String helloStringHTML() {
        return "<!DOCTYPE html>" +
               "<html>" +
                   "<head><meta charset=\"UTF-8\"><title>By @ResponseBody</title></head>" +
                   "<body> Hello, 정적 웹 페이지!!</body>" +
               "</html>";
    }

    // [Response header]
    //   Content-Type: text/html
    // [Response body]
    // * resources/templates/hello-visit.html 의 text 내용
    @GetMapping("/html/dynamic")
    public String helloHtmlFile(Model model) {
        visitCount++;
        model.addAttribute("visits", visitCount);
        // resources/templates/hello-visit.html
        return "hello-visit";
    }

    private static long visitCount = 0;

    // [Response header]
    //   Content-Type: text/html
    // [Response body]
    //   {"name":"BTS","age":28}
    @GetMapping("/json/string")
    @ResponseBody
    public String helloStringJson() {
        return "{\"name\":\"BTS\",\"age\":28}";
    }

    // [Response header]
    //   Content-Type: application/json
    // [Response body]
    //   {"name":"BTS","age":28}
    @GetMapping("/json/class")
    @ResponseBody
    public Star helloJson() {
        return new Star("BTS", 28);
    }
}

만들고 나면 맨밑에 Star에 오류표시가 날텐데, 게터세터를 설정안해주어서그렇다. Star.java 클래스도 추가적으로 만든다.

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@AllArgsConstructor
@Getter
@Setter
public class Star {
    String name;
    int age;
}

프로젝트 세팅은 끝났다. 하지만 Spring MVC동작원리를 깨우치기전에 HTTP메세지에 이해를 먼저하고 넘어가야 한다.

  • Client 와 Server 간 Request, Response 는 HTTP 메시지 규약을 따름
  • HTTP 메시지는 웹 서비스 개발자(백엔드, 프론트 개발자)에게 매우 중요한 내용!!
  • 스프링 MVC 이해를 위한 필수 내용만 학습

  1. 시작줄 (start line) Response 에선 '상태줄 (status line)' 이라고 부름
  2. 헤더 (headers)
  3. 본문 (body)

 

댓글