[Spring] MVC와 템플릿 엔진

Haeun Noh·2023년 8월 1일
1

TweeksStudy:1 (Spring)

목록 보기
5/13
post-thumbnail

0801


☘️1. MVC

MVC란? Model, View, Controller


👉1.1. 역할 분배를 왜 하나요?

  • View는 화면을 그리는 데에 모든 역량을 집중
  • Controller 나 Model은 비즈니스 로직과 관련이 있거나 내부적인 것을 처리하는 것에 집중

👉1.2. Controller를 만들어보자!

  1. src > main > java > ... > controller > HelloController 에서 아래의 코드를 작성한다.
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model) {
        model.addAttribute("name", name);
        return "hello-template";
    }
  1. src > resources > templates 에서 hello-template.html파일을 생성하여 아래의 코드를 작성한다.
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Hello</title>
</head>
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
  • thymeleaf의 장점
    • 서버를 띄우지 않아도 파일 자체를 열어서 껍데기를 볼 수 있다!
  1. 스프링 서버를 실행한 후, localhost:8080/hello-mvc로 서버에 접속한다.

  2. 에러가 난다. ???


👉1.3. 왜 에러가 날까?

Required request parameter 'name' for method parameter type String is not present
(name의 값이 없다)

  • localhost:8080/hello-mvc?name=출력값 으로 name에 값을 넣어주어야 한다.

    • ex) localhost:8080/hello-mvc?name=hello spring!!!!!!!

      • http Get 방식에서 사용하는 방법

👉1.4. 작동 원리

  1. 웹브라우저가 localhost:8080/hello-mvc 를 넘기면

  2. 내장 톰켓 서버를 거치고, 내장 톰켓 서버는 스프링에게 해당 서버를 넘긴다.

  3. helloController에 매핑된 url을 확인하고 매핑이 되어있다면 리턴값과 키, 값을 viewResolver로 넘긴다.

  4. viewResolver는 리턴된 url 이름과 똑같은 파일을 찾아 Thymeleaf로 넘긴다.

  5. Rendering을 해서 변환을 한 파일을 웹 브라우저에 띄운다.

    • 정적으로 처리할 때는 변환을 하지 않았지만 템플릿 엔진을 사용하였기 때문에 변환을 한 것

profile
Tistory로 옮기게 되었습니다. @haeunnohh

0개의 댓글