[spring] (2) Spring Web MVC

orca·2022년 11월 1일
0

Spring

목록 보기
2/13

MVC (Model-View-Controller)는 사용자 인터페이스, 데이터 및 제어 논리를 구현하는 데 일반적으로 사용되는 소프트웨어 설계의 패턴이다. 소프트웨어의 비즈니스 로직과 디스플레이 간의 분리를 강조한다. 이러한 관심사의 분리를 통해 더 나은 분업과 수월한 유지 보수가 가능하다.
mozilla

MVC 패턴

소프트웨어 설계시 세 가지 요소로 나누어 개발하는 방법론
비즈니스 로직과 디스플레이를 분리하여 서로 영향없이 개발할 수 있음

  • Model
    Manages data and business logic ex> CRUD, 데이터 처리 etc
  • View
    Handles layout and display
  • Controller
    Routes commands to the model and view parts

Spring Web MVC

스프링 웹 기술은 MVC 패턴을 근간으로 한다

스프링 MVC는 request를 처리하는데 DispatcherServlet이라는 프론트 컨트롤러를 사용합니다.
Spring MVC, as many other web frameworks, is designed around the front controller pattern where a central Dispatcher Servelet provides a shared algorithm for request processing, while actual work is performed by configurable delegate components. This model is flexible and supports diverse workflows.
Spring

Spring 웹 MVC 로직을 뜯어보기 위해 동적 웹 페이지를 만들어보자

build.gradle

implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

templates/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>

HelloController.java

@Controller
@RequestMapping("/visit")
public class HelloController {

   private static long visitCount = 0;

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

}

잠깐 🙋‍♀️ (Model model) 이 뭘까요?

Spring에서 컨트롤러의 메소드 작성시 Model이라는 객체를 매개 변수로 지정할 수 있음
Model 객체는 thymeleaf에 컨트롤러에서 생성된 데이터를 담아서 전달하는 역할을 함

thymeleaf
HTML 코드에 JAVA 코드를 넣어 동적 웹페이지를 생성하는 웹 애플리케이션 도구


아무튼 본론으로 들어와서 위 코드는 위와 같이 동작함

이 웹은 스프링 내부에서 어떤 로직으로 동작할까?

  1. Client to Dispatcher Servelet
    클라이언트는 http://localhost:8080/visit/dymanic 으로 Dispatcher Servelet에게 HttpServletRequest
  2. Dispatcher Servelet to HelloController
    Dispatcher Servelet은 API를 처리해줄 컨트롤러를 찾아 요청을 전달함
  3. HelloController To Dispatcher Servelet
    HelloController가 클라이언트로부터 받은 api 요청을 처리함
    이 때 Model 정보와 View 정보를 Dispatcher Servelet으로 전달함
  4. Dispatcher Servelet to Client
    Thymeleaf View Resolver를 통해 View에 Model을 적용함
    만들어진 View를 클라이언트에게 Response함

0개의 댓글

Powered by GraphCDN, the GraphQL CDN