본문 바로가기
Language/JAVA

[자바/스프링] MVC와 템플릿 엔진

by 아이엠제니 2023. 2. 13.

 

 

  • MVC: Model, View, Controller
    • model
    • view: 화면과 관련된 것만 함
    • controller: 비즈니스 로직과 서버 뒷단에 관련된 건 컨트롤러나 뒷단 비즈니스 로직에서 처리

 

 

💾 main > java > hello > hellospring > controller > HelloSpriongApplication

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 {

    @GetMapping("hello") // 웹 애플리케이션에서 /hello 라고 들어오면, 이 메서드를 호출함
    public String hello(Model model) {
        model.addAttribute("data", "hello!!"); // 데이터를 "hello!!" 라고 넘길 거임
        return "hello"; // resources > templates에 있는 hello를 찾아서 렌더링 해라
    }

// 이 부분 추가
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model) { // 외부에서 파라미터를 받을 때 @RequestParam을 적는다
        model.addAttribute("name", name);
        return "hello-template";
    }
}

 

💾 resources > temmplates > hello-template.html

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello '+${name}">hello! empty</p>
</body>
</html>

 

  • HelloController.java 에 `hello-mvc` 추가
  • hello-template.html 추가

 

그런데 이렇게 에러가 뜬다.

여기서도 확인할 수 있지만, 로그에서도 확인을 할 수 있다.

 

 

parameter name이 없다.

 

 

required라는 옵션이 있는데, default 가 'true'임.

그래서 무조건 뭔가를 입력을 한다.

 

 

http get 방식에서 이렇게 파라미터 값을 입력한다.

name= 바보 

다.

 

 

 

✔️ MVC, 템플릿 엔진 이미지

 

 

 

[스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술] 강의 기록
300x250