Spring

[Spring] Welcome Page 만들기

퉁그리 2021. 9. 28. 00:06

Spring에서 제공하는 Welcome Page 기능

static/index.html을 올려두면 Welcome page 기능을 제공한다.

Spring Boot Reference Documentation 해당사이트를 가면 welcom page를 비롯한 여러가지 기능들에 대해 찾아볼 수 있다.

 

Thymeleaf 템플릿 엔진

Spring Boot Reference Documentation

 

템플릿 엔진은 주로 4개가 있으며 우리는 그 중 하나인 Thymeleaf를 쓸 것이다.

 

 

페이지 맵핑해보기

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 클래스를 만들 때는 위에 @Controller을 써야한다.

 

@GetMapping("hello")를 씀으로써 웹 어플리케이션에서 /hello가 들어오면 아래 함수를 실행하게 된다. (hello라는 url에 매칭)

 

프로그램 실행도

 

함수가 실행되면서 스프링에서 파라미터로 model을 들고 온다.

model에 addAttribute함수를 써 데이터를 넣어준다.

앞 인자는 키 값이며, 뒷 인자는 실제 값이다.

페이지에서 키값인 data를 호출한다면 실제 값인 hello!! 가 적용된다.

 

컨트롤러에서 리턴을 문자로 하면 viewResolver 클래스가 매핑을 해준다.

    - resources:templates/ + "리턴값" + .html

 

 

빌드하고 실행하기

cmd를 키고 프로젝트 최상단 폴더에 접근한 후

 

.\grandlew.bat buld 

 

를 눌러 빌드를 한다.

 

 

build 폴더의 lib폴더에 들어가 dir을 실행해 파일목록을 확인한 후

 

java -jar hello-spring-0.0.1-SNAPSHOT.jar

 

를 하여 프로그램을 실행시켜본다.

 

ctrl + c 를 누르면 실행되던 서버를 끌 수 있다.

 

출처 : 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 - 인프런 | 학습 페이지 (inflearn.com)