[Spring] View 환경 설정 및 빌드 해보기

Haeun Noh·2023년 8월 1일
1

TweeksStudy:1 (Spring)

목록 보기
3/13
post-thumbnail

0731


☘️1. 정적인 Welcome Page 만들기

resources/static/index.html
을 만들면 index.html이 시작 화면이 됨.

<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Document</title>
</head>
<body>
    Hello
    <a href="/hello">hello</a>
</body>
</html>

작성한 뒤 spring을 실행하면 위에 작성한 html파일이 뜨고
hello를 클릭하면 아까와 같은 에러 페이지가 뜬다.

하지만 index.html 파일을 이용하여 웹서버에 올리는 것은 프로그래밍이 아니라 그저 파일을 옮긴 것에 불과하다!

  • 내가 원하는대로 Welcome 페이지의 모양을 바꿀 수 있는 것이 바로 템플릿 엔진이다.


☘️2. Thymeleaf 템플릿 엔진

👉2.1. 탬플릿 엔진을 사용하여 welcome 화면 만들기

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";
    }
}
<!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를 클릭했을 때, 에러 메시지가 아닌 "안녕하세요. hello!" 가 출력된 페이지가 뜨게 된다.

👉2.2. 동작 원리

  1. 웹 브라우저에서 localhost:8080/hello를 던진다.

  2. 스프링 부트가 내장하고 있는 톰캣 웹서버가 스프링에게 물어본다. @GetMapping()안의 url과 내가 던진 링크가 맞니? (GET 방식)

  3. 맞다면 @GetMapping()안에 있는 url과 매칭이 된 것이다.

  4. 스프링이 실행이 된다.

  5. 스프링이 실행이 되었을 때 Model을 만들어서 hello메서드의 인자로 넣어준다.

  6. model.addAttribute("data", "hello!!");model에다가 데이터는 hello!! 라고 넣어둔다.

  • "data" : 키
  • "hello!!" : 값 (바뀔 수 있음)
  1. return "hello";로 스프링이 resources > templates 폴더 밑에 있는 hello.html을 찾는다.
  • 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버 (viewResolver) 가 화면을 찾아서 처리한다.
    • 스프링 부트 템플릿 엔진 기본 viewName을 매핑
    • resources:templates/+(ViewName)+.html

참고 : spring-boot-devtools 라이브러리를 추가하면, html파일을 컴파일만 해주면 서버 재시작 없이 View 파일 변경이 가능함.


☘️3. 빌드하고 실행하기

window 기준입니다.

  1. gradlew.bat build : 빌드하기
  • 확인 : BUILD SUCCESSFUL in 12s
  1. cd build : build 폴더로 이동

  2. cd libs : libs 폴더로 이동

  3. java -jar hello-spring-0.0.1-SNAPSHOT.jar : 서버 실행

  • (!주의!) 다른 서버가 실행되고 있으면 안 됨
  • 해당 에러 : Web server failed to start. Port 8080 was already in use.
  1. 실행 확인


profile
Tistory로 옮기게 되었습니다. @haeunnohh

0개의 댓글