[Spring] 스프링 입문 환경설정(3)

View 환경설정

Welcome Page 만들기

src>main>java>mess>hellospring 의 경로에 HelloSpringApplication.java를 생성해준다.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloSpringApplication {

	public static void main(String[] args) {
		SpringApplication.run(HelloSpringApplication.class, args);
	}

}

resource/static/index.html 생성하여 만든다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
    Hello
    <a herf="/hello">hello</a>
</body>
</html>

spring06

실행해보면 이렇게 출력될 것이다.

다음은 먼저 따라하자면 다음은 Controller를 다룰 차례이다.

위치는 아래의 사진과 같다.

spring07

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("hello") //웹 어플리케이션에서 /hello라고 들어오면 이 메서드를 호출해줌
    public String hello(Model model){
        model.addAttribute("data", "hello!!");
        return "hello";
    }
}

다음은 resources > templates 위치에 hello.html을 생성한다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"> //이것을 선언하면 타임리프 문법 사용가능

<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>

<body>
<p th:text="'안녕하세요. ' + ${data}">안녕하세요. 손님</p>
</body>
</html>

여기에 <p th:text="'안녕하세요. ' + ${data}">안녕하세요. 손님</p>가 있다.

${data}은 HelloController에서 작성한 model.addAttribute(“data”, “hello!!”); 의 data의 value 값의hello!!로 치환되게 됨

spring08

결국 안녕하세요. 다음의 $data는 hello!!로 치환되어 나온 결과를 볼 수 있다.

spring09

김영한님의 강의 자료에서 가져온 그림이다.

먼저 웹 브라우저에서 localhost:8080/hello를 보내주면 hello를 톰캣 서버를 거쳐서 helloController에게 전달한다.

그 hello를 보고 helloController의 GetMapping(”hello”)로 매서드를 실행한다.

Spring에서 model이란걸 만들어서 넣어준다. 모델의 키는 data 값은 hello!!가 된다. 그리고 리턴 값은 hello를 리턴한다.

그렇다면 hello를 리턴하는 것이 뭘까? 한다면 hello는 templates에 있는 hello.html을 의미한다.

(Spring의 구조상 return값을 templates에서 똑같은 이름을 찾는다.)

그렇다면 마지막 templates/hello.html 을 출력해주면 끝이난다.

Leave a comment