Spring

[Spring] 스프링 View 환경설정

lumana 2024. 4. 28. 18:41

View 환경설정


Welcome Page 만들기

  • resources/static/index.html에 다음 파일 생성
<!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>
  • 스프링 부트가 제공하는 Welcome Page 기능
    • static/index.html 을 올려두면 Welcome page 기능을 제공한다.

thymeleaf 템플릿 엔진

Controller 만들기

  • hello.hellospring 패키지 안에 controller 패키지를 만들고 controller 클래스를 생성
@Controller
public class HelloController {
    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "hello!!");
        return "hello";
    }
}

thymeleaf 템플릿 엔진을 사용하는 html 파일 만들기

  • resources/templates/hello.html 생성
<!DOCTYPE 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>
</body>
</html>

작동 원리

  • @Getmapping : HTTP Get
    • http url을 입력하는 것을 Get 방식이라고 함
    • http://localhost:8080/hello  에서 /hello를 던지면 Spring Boot의 Tomcat 서버에서 슬롯이 Hello임을 확인하고 Spring에게 질의
    • Spring의 Hello Controller에 Getmapping("Hello")가 있으므로 url에 매칭되어 메서드가 실행된다.
    • Spring이 만들어 전달한 model에 "data"(key), "hello!!!"(value) attribute를 Add
    • 컨트롤러에서 리턴 값으로 문자를 반환하면 뷰 리졸버( viewResolver )가 화면을 찾아서 처리한다.
      • 스프링 부트 템플릿엔진 기본 viewName 매핑
      • resources:templates/ +{ViewName}+ .html
    • Thymeleaf 템플릿 엔진이 key값에 해당하는 Value를 꺼내서 출력해줌
    • 참고: spring-boot-devtools 라이브러리를 추가하면, html 파일을 컴파일만 해주면 서버 재시작 없이 View 파일 변경이 가능하다.

빌드하고 실행하기

콘솔로 이동

1. ./gradlew build
2. cd build/libs
3. java -jar hello-spring-0.0.1-SNAPSHOT.jar

4. 실행확인

 

참조) 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 강좌 (인프런 김영한)