MVC와 템플릿 엔진

하히호호·2024년 3월 9일
0

MVC구조

코드

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<p th:text="'hello ' +${name}"> hello! empty<!--타임리프 장점:서버없이 열수 있음--></p>
</body>
</html>
package hello.hellospring.controller;

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

@Controller
public class Hellocontroller {
    
    /*웹 브라우저 주소 전달값 (http://localhost:8080/hello-mvc)*/
    @GetMapping("hello-mvc")
    public String helloMVC(@RequestParam("name") String name, Model model){
        model.addAttribute("name",name);
        return "hello-template";
        /*return 값인 html 파일을 찾아간다.*/
    }
}

RequestParam

이번에는 RequestParam 어노테이션을 사용했다.
@RequestParam을 사용하게 되면 url에서 "?"이후에 key=value 형식으로 값을 줄 수있다.

코드를 보면 name이라는 key에 spring이라는 값을 넣어 요청하는 것이다.

전체 진행과정

과정

  1. 웹 브라우저에서 localhost:8080/hello-mvc 주소를 톰켓에게 넘긴다.
  2. 내장 톰켓 서버는 스프링 컨테이너에서 helloController에 맵핑이 되어있는 것을 찾는다.
    3.이때 return값을 hello-template으로 돌려주고 model에 데이터를 저장해서 넣어준다. (name:spring)
    4.화면과 관련된 viewResolver(veiw를 찾아주고 연결)가 templates/hello-template.html을 찾아서 Thymeleaf 템플릿 엔진에 처리하게 넘긴다.
    5.동적인 작업, 즉 변환을 시킨 HTML 파일을 웹 브라우저에 넘긴다.
profile
읽히는 코드를 짜고싶습니다.

0개의 댓글