[Spring Boot] 2. View 설정 및 빌드

Noh_level0·2024년 1월 21일
0

Spring Boot

목록 보기
2/5
post-thumbnail

1. Welcome Page

Spring Boot는 resources/static 또는 resources/templates 폴더에 index.html을 만들면 이 페이지를 Welcome 페이지로 만들어준다.

이와 같이 resources/static 폴더에 index.html을 생성 후
<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Hello</title>
</head>
<body>
정적 컨텐츠
<a href="/hello">hello</a>
</body>
</html>

index.html을 이처럼 작성하면

http://localhost:8080/에 접속 시 이러한 화면이 보인다.
문자열만 작성하는 것은 정적 페이지라는 것으로 그대로 웹 브라우저에 넘어가게 된다.(프로그래밍 x)

2. thymeleaf 템플릿 엔진 사용해보기

템플릿 엔진을 쓰게 된다면 html에서 원하는 부분의 모양을 바꿀 수 있다. 즉, 동적 페이지를 만들 수 있게 된다.

controller 패키지를 만들고 그 안에 HelloController.java를 생성하고, templates 폴더 안에는 hello.html 파일을 생성한다.
@Controller
public class HelloController {

    @GetMapping("hello") 
    public String hello(Model model){
        model.addAttribute("data", "hello!!");
        return "hello";
    }
}

HelloController.java에는 위와 같이 작성한다.

  • @GetMapping("hello")
    웹 애플리케이션에서 첫번째 진입점은 컨트롤러이며, @GetMapping("hello")라면 웹 어플리케이션에서 http://localhost:8080/hello로 접속 시 해당 메서드를 호출해준다.
  • Model
    Spring에서는 model을 만들어 넣어주는데 여기에서는 key는 "data", value는 "hello!!"가 되어 들어간다.
  • return
    return "hello"의 의미는 resources/templates에 있는 hello.html로 가서 렌더링해라(화면을 실행시켜라)의 의미가 된다. 이는 기본적으로 Spring Boot에서 세팅된 것으로, 컨트롤러에서 return 값으로 문자를 반환하면 뷰 리졸버('viewResolver')가 화면을 찾아서 처리한다.
    Spring Boot 템플릿엔진은 기본적으로 viewName 매핑이 된다.
    즉, 'resources:templates/' + {ViewName} + '.html'
<!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.html에는 위와 같이 작성한다.

th: thymeleaf의 th를 의미
여기에서 {data}는 HelloController.java에서 model.addAttribute에서 key로 넣었던 "data"를 의미하며, 이 코드에서 Value는 "hello!!"이다. 따라서 ${data} 이 부분이 hello!!로 바뀌어 웹 브라우저에 띄워진다.

프로젝트 실행 후 http://localhost:8080/hello로 접속하게 되면 이와 같은 화면이 출력된다.

3. 빌드 후 실행 파일 만들기

IntelliJ IDE가 실행하는 것이 아닌 빌드 파일을 만들어 실행해본다.

1. IntelliJ에서 서버를 중지시킨다.
2. cmd를 프로젝트 폴더 경로 위치에서 실행한 후 gradlew.bat build를 실행한다. (맥의 경우 ./gradlew build 입력)

3. build/libs 폴더로 이동 후 hello-spring-0.0.1-SNAPSHOT.jar 파일을 실행한다.

4. http://localhost:8080/ 접속 확인

페이지가 정상적으로 띄워지는 것을 볼 수 있다.

따라서 서버 배포 시 hello-spring-0.0.1-SNAPSHOT.jar 파일만 서버에 넣어준 후 실행하면 된다.

4. 빌드가 잘 안 되었을 때

gradlew clean build를 입력해 빌드를 다시 시작한다.

!! gradlew clean 입력 시 bulid 폴더 자체가 삭제된다.


본 포스팅은 inflearn 김영한 강사님의 "스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술" 강의에 기반하여 작성되었습니다.
강의 링크

썸네일 생성: Thumbnail Maker

0개의 댓글