인프런/스프링 입문 (김영한)
[II. 스프링 웹 개발 기초] 6. MVC와 템플릿 엔진
upcake_
2021. 12. 23. 21:58
반응형
https://github.com/upcake/hello-spring
오늘의 단축키
- 라인 삭제 : Ctrl + y
- 매직 숏컷 : 쉬프트 쉬프트
- 옵션, 파라미터 정보 보기 : Ctrl + p
1. MVC : Model, View, Controller
- 과거에는 컨트롤러와 뷰가 분리되어 있지 않았다. (과거의 JSP, Model 1 방식)
- View는 화면을 그리는데 모든 역량을 집중해야 한다.
- Controller, Model은 비즈니스 로직 등 내부적인 일에 집중해야함.
package com.upcake.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")
public String hello(Model model) {
model.addAttribute("data", "hello!!");
return "hello";
}
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
- /resources/templates/hello-template.html
- 타임리프 엔진을 거치지 않고 html 파일을 열어 보면 hello! empty가 보인다
- 타임리프의 장점으로 그냥 열어보더라도 무언가의 껍데기를 볼 수 있다
- 그냥 접속하면 에러가 난다.
- name parameter가 없어서 에러가 떠있는 것을 확인가능하다.
@GetMapping("hello-mvc")
public String helloMvc(@RequestParam(value = "name", required = false) String name, Model model) {
model.addAttribute("name", name);
return "hello-template";
}
- @RequestParam에 required = false옵션을 넣어주면 필수값이 아니게 된다.
- 파라미터에 들어간 `spring!!`이 들어가 있다.
반응형