resources/static/index.html
을 만들면 index.html
이 시작 화면이 됨.
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Document</title>
</head>
<body>
Hello
<a href="/hello">hello</a>
</body>
</html>
작성한 뒤 spring을 실행하면 위에 작성한 html파일이 뜨고
hello를 클릭하면 아까와 같은 에러 페이지가 뜬다.
static/index.html
을 올려두면 Welcome page 기능을 제공하지만 index.html 파일을 이용하여 웹서버에 올리는 것은 프로그래밍이 아니라 그저 파일을 옮긴 것에 불과하다!
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";
}
}
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hello</title>
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}">안녕하세요. 손님</p>
</body>
</html>
위의 코드를 입력한 뒤 실행
-> hello를 클릭했을 때, 에러 메시지가 아닌 "안녕하세요. hello!" 가 출력된 페이지가 뜨게 된다.
웹 브라우저에서 localhost:8080/hello
를 던진다.
스프링 부트가 내장하고 있는 톰캣 웹서버가 스프링에게 물어본다. @GetMapping()
안의 url
과 내가 던진 링크가 맞니? (GET 방식)
맞다면 @GetMapping()
안에 있는 url
과 매칭이 된 것이다.
스프링이 실행이 된다.
스프링이 실행이 되었을 때 Model
을 만들어서 hello
메서드의 인자로 넣어준다.
model.addAttribute("data", "hello!!");
로 model
에다가 데이터는 hello!! 라고 넣어둔다.
return "hello";
로 스프링이 resources > templates 폴더 밑에 있는 hello.html
을 찾는다.viewName
을 매핑resources:templates/
+(ViewName)+.html
참고 :
spring-boot-devtools
라이브러리를 추가하면,html
파일을 컴파일만 해주면 서버 재시작 없이View
파일 변경이 가능함.
window 기준입니다.
cd build : build 폴더로 이동
cd libs : libs 폴더로 이동
java -jar hello-spring-0.0.1-SNAPSHOT.jar : 서버 실행