[Spring]MVC와 템플릿 엔진

DEV.Kang·2022년 5월 11일
1

spring

목록 보기
5/6

MVC

MVC는 Model, View, Controller 이 세가지를 MVC라고 부르는 것이다.

Controller

@GetMapping("hello-mvc") //메서드에 따라 어떤 page를 보여줄지 결정하는 역할
    public String helloMvc(@RequestParam("name") String name, Model model){ //반환값이 string이므로 string으로 지정한다.
        model.addAttribute("name",name); //key:name, value:name
        return "hello-template"; //hello-template에 model을 return한다.
    }

@RequestParam()

앞에서 보던 내용들과는 다르게 @RequestParam이 추가되어 있다.
@RequestParam: HttpServletRequest와 동등한 역할을 수행한다.
사용방법은 다음과 같다.
@RequestParam("가져올 데이터 이름")[데이터 타입][가져온 데이터를 담는 변수]
위의 Controller를 보게 되면 name이라는 데이터를 가져오는데 name이라는 변수에 저장을 하는 것을 알 수 있다.

View
resources/templates/hello-template.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello-template</title>
</head>
<body>
<p th:text="'hello'+${name}">hello! empty</p>
</body>
</html>

템플릿 엔진을 사용하게 되면 D:\spring\spring 공부\hello-spring\hello-spring\src\main\resources\templates\hello-template.html위와 같은 경로로 들어가게 되면 Controller에서 아무런 값을 받지 않아 Hello! empty라는 화면이 출력되게 된다.

하지만 Controller에서 값을 받는 경우에는 hello[가져온 데이터 값]이 출력되게 된다.
실행
localhost:8080/hello-mvc?name=spring
name 뒤의 값을 다르게 지정하면 다른 값이 출력된다.

동작 방식

  1. 웹 브라우저에서 localhost:8080/hello-mvc를 요청하게 됩니다.
  2. 스프링 부트 내부에 있는 내부 톰켓 서버가 이것을 받아 스프링 컨테이너에 넘기게 됩니다.
  3. 스프링 컨터이너 내부에 있는 helloController에서 return:hello-template, model(name:spring)viewResolver에 넘겨주게 됩니다.
  4. viewResolver에서 HTML 변환 후 웹 브라우저에 보내지게 됩니다.
profile
back-end에 대해 집중적으로 공부 내용을 업로드 예정입니다.

0개의 댓글