4. View 환경설정

View 환경설정

Welcome Page 만들기

Welcome Page란 domain으로 들어 왔을때의 첫 화면이다.

<!-- index.html : Spring boot에서 index.html을 Welcome Page로 정함 -->
<!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>

템플릿 엔진이란 내가 원하는 대로 모양을 바꿀 수 있다.

@Controller // Web application의 첫번째 진입점이다.
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model) { // 스프링이 model을 만들어서 넣어줌
    model.addAttribute("data", "hello!!"); // 여기서 "data"는 key고 "hello!!"는 value다.                                                
                                           //(value는 바뀔 수 있다.)

    return "hello"; // 기본적으로 스프링 부트는 resources의 templates의 folder 밑에 있는                             
                    // hello.html을 찾고 렌더링 한다. (이때 model의 data와 그 값도 날라간다.)
    }
}
<!-- resources/templates/hello.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> 
    <!-- data에 model의 value 값이 들어간다. -->
</body>
</html>

웹 어플리케이션에서 첫번째 진입점이 controller다.

GetMapping("hello") ← web application에서 '/hello' 라고 들어오게 되면 아래 메서드인 hello를 호출해 준다. (여기서 Get은 GET/POST 할때 GET 이다!, 우리가 임의로 주소창에 http~~ 엔터치는게 GET 방식임)

타임리프 템플릿 엔진이 xml 스키마로 선언되어있음 (템플릿 엔진으로 문법을 쓸 수 있음)

model attribute의 value인 hello!!가 ${data}에 치환되어 들어간다.

임의로 http://localshot:8080/hello를 URL에다가 치면 GET방식 이라고함.

* 동작 원리

여기서 return "hello"는 resources의 templates의 hello.html이름과 일치한다. 따라서 get 메서드의 리턴을 통해 hello.html로 가서 렌더링(화면을 실행) 하라는 의미다

스프링 부트가 어떻게 셋팅 되어있느냐? 기본적으로 return을 하게되면 resources의 templates 폴더 밑의 파일의 이름을 찾아서 렌더링을 한다!

여기서 ViewName은 지금은 hello인 거다.

 

출처 : 인프런의 김영한 선생님 강의를 정리한 글입니다.
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard

'Java > 스프링 입문' 카테고리의 다른 글

6. 정적 컨텐츠  (0) 2021.06.04
5. 빌드하고 실행하기  (0) 2021.06.04
3. 라이브러리 살펴보기  (0) 2021.06.04
2. 프로젝트 생성  (0) 2021.06.04
1. 시작  (0) 2021.06.04

댓글

Designed by JB FACTORY