[#3] Spring 파헤치기 : View 환경설정
전에 메인메소드를 실행했을때 오류만 떴었다. 이번엔 WelcomePage를 작성해보도록하자.
src - main - resources - static 안에 index.html을 생성한 뒤
<!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>
를 입력하자.
그 다음 서버를 껐다 키면
이렇게 Welcome Page가 성공적으로 뜨게된다.
위에 Page는 정적인 기능이기때문에, 프로그래밍이라 보기어렵다. 동적으로 만들어보자.
1. Controller 생성
src - main - java - hello.hellospring 아래에 controller라는 package를 생성한 다음 그 안에 HelloController라는 class를 생성한다.
그 다음 안에 다음과 같이 작성한다.
@Controller
public class HelloController {
@GetMapping("hello")
public String hello(Model model) {
model.addAttribute("data", "hello");
return "hello";
}
}
class명 위에 @Controller의 이노테이션을 달아주고, 안에 @Getmapping으로 감싼 컨트롤러를 추가한다.
hello라는 컨트롤러는 주소창에 'http://localhost:8080/hello' 를 입력받으면, 데이터를 가지고 templates 폴더 아래에 있는 hello.html로 이동하게 해준다.
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>
그다음 주소창에 http://localhost:8080/hello를 입력하면
성공적으로 화면이 뜨는걸 볼 수 있다!
원리는 다음과 같다.
먼저 웹브라우저에서 주소를 받아 톰켓서버를 통해 스프링 컨테이너로 들어간다. 거기서 helloController안에 hello로 Mapping되어있는 Controller를 실행시킨다. 이걸 viewResolver가 ViewName을 매핑해 화면을 찾은다음 templates에서 찾아 실행시키고 템플릿 엔진처리를해 html로 변환시켜 웹 브라우저에 뿌려주는 방식이다.