static/index.html
을 올려두면 Welcome page 기능 제공index.html
파일을 static
에서 먼저 찾고 만약 찾지 못한다면 index 템플릿에서 찾도록 동작<!DOCTYPE HTML>
<html>
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>
src>main>java>resources>static
경로에 index.html
파일 생성
1. HelloController.java
hellospring
> package controller
> HelloController.java
생성
package hello.hellospring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "hello!");
return "hello";
}
}
@Controller
어노테이션을 적어야 함model
은 MVC에서의 model을 뜻함/hello
라고 들어오면 hello 메소드를 호출하는 방식2. hello.html
resources
> templates
> hello.html
생성
<!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="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
</body>
</html>
<html xmlns:th="http://www.thymeleaf.org">
를 넣어주면 타임리프 문법 사용 가능th
는 thymeleafdata
부분이 hello!
로 치환됨model.addAttribute
에서 name: data
, value: hello!
) localhost:8080/hello
실행
1. 웹 브라우저에서 localhost:8080/hello
라고 던짐
2. 스프링 부트는 내장된 Tomcat
웹 서버에서 받아서 스프링한테 전달
3. 스프링은 helloController
의 GetMapping("hello")
에 매칭하면서 메소드 실행
4. 스프링이 모델을 만들어서 넣어주고 모델에 key=data, value=hello!
인 속성 추가
5. 메소드에서 hello
를 리턴하는데 여기서 hello는 templates/hello.html
(hello.html 화면 실행)
viewResolver
가 화면을 찾아서 처리함viewName
에 매핑resources:templates/ + {ViewName} + .html
의 ViewName
이 hello
로 바뀌면서 hello.html
이 열리게 됨