MVC와 템플릿 엔진
2024. 4. 20. 00:13ㆍ- 서버/springboot
스프링 웹개발은 크게 3가지로 나눌수 있습니다.
- 정적컨텐츠
- MVC와 템플릿 엔진
- API
이번시간에는 MVC와 템플릿 엔진에 대해 알아보겠습니다.
MVC는 Model, View, Controller를 말합니다.
과거에는 controller와 view가 따로 분리 되어 있지 않았습니다.
jsp를 가지고 view에서 모든 작업이 이뤄졌었는데요 소위 model1 방식이라고 하는데요
하지만 이런 방식은 관심사가 분리가 되지 않다 보니 한쪽으로만 코드가 커지는 문제가 있습니다.
아래서 MVC로 이뤄진 코드를 확인해보겠습니다.
HelloController
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
// 어노테이션 Controller를 사용해준다
@Controller
public class HelloController {
.....
// hello-mvc로 매핑이 되어 있기 때문에 /hello-mvc로 접속하면 아래 메소드가 실행
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name2") String name, Model model) {
model.addAttribute("name2", name); // key name2, String name
return "hello-template"; // hello-template.html을 호출
}
}
hello-template.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name2}">hello! empty</p> // key값 name2
</body>
</html>
이와같이 코드 작성후 main 코드를 run 해보면 에러 화면이 뜹니다.
화면의 에러 로그를 확인하거나 인텔리제이 로그캣을 확인하면 name2에 파라미터가 주어지지 않았다고 알려줍니다.
get방식으로 데이터를 넘겨주기 위해 url 뒤에 ? 다음에 데이터를 넣고 들어가줍니다.
그러면 아래와 같은 화면을 확인 할수 있습니다.
아래는 그림으로 설명한 모습입니다.
참고자료
'- 서버 > springboot' 카테고리의 다른 글
회원관리예제 (0) | 2024.06.08 |
---|---|
API (0) | 2024.04.22 |
정적 컨텐츠 (0) | 2024.04.18 |
Welcome Page 만들기 (0) | 2024.04.17 |
스트링부트에서 JPA로 데이터베이스 다루기(1) (0) | 2024.01.02 |