본문 바로가기
Spring

[Spring] 정적 페이지와 동적 페이지

by worldcenter 2024. 9. 26.

정적 페이지 처리하기

Static 폴더

static 폴더 아래 hello.html 을 생성하고 Controller를 통해 접근하는 모습을 보여드리겠습니다.

Client(요청) -> Controller -> hello.html

@Controller
public class HtmlController {

    @GetMapping("/static-hello")
    public String hello() {
        return "hello.html";
    }
}

org.thymeleaf.exceptions.TemplateInputException: Error resolving template [hello.html], template might not exist or might not be accessible by any of the configured Template Resolvers

 

사용자가 Controller를 통해 정적 페이지에 접근하면 다음과 같이 에러 페이지 보입니다. 왜 그럴까요?

그 이유는 thymeleaf 때문입니다. thymeleaf는 동적 페이지 처리를 위한 템플릿 엔진입니다. thymeleaf 엔진을 사용하게 되면 자동으로 Controller에서 html 파일 찾는 경로를 /resources/templates 로 설정합니다.

 

만약 static 폴더 하위에 있는 정적 페이지(.html)로 접근하고 싶다면 다음의 방법이 있습니다.

1) 정적 페이지 바로 접근

이미 완성된 정적 페이지를 Controller를 통해 반환할 필요는 없기 때문에 Controller를 통하지 않고 정적 페이지로 바로 접근하는 방법 입니다.

 

2) thymeleaf 미사용

굳이 Controller를 통해 정적 페이지에 접근할 필요는 없지만 Controller를 통해서 반환하는 것을 테스트 할 수는 있습니다.

thymeleaf 엔진을 사용함으로써 Controller가 html을 찾을 때 기본 경로를 /resources/templates로 잡기 때문에 템플릿 엔진을 미사용하여 정적 페이지로 접근할 수 있습니다.

// build.gradle
dependencies {
//    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

3) Redirect

템플릿 엔진을 적용한 상태에서 static 폴더의 html 파일을 Controller를 통해서 처리하고 싶다면 redirect를 통해 정적 페이지를 반환할 수 있습니다.

@Controller
public class HtmlController {

    @GetMapping("/html/redirect")
    public String htmlRedirect() {
        return "redirect:/hello.html";
    }
}

 

개발자 도구를 통해 확인해보면 /html/redirect로 요청하니 hello.html 페이지로 redirect 되는 것을 확인할 수 있습니다.

 

 

4) template 폴더

현재 thymeleaf 템플릿 엔진을 사용하고 있으며 thymeleaf을 사용한다고 해서 templates 폴더에 무조건 동적 페이지만 위치시킬 필요는 없습니다. 정적페이지를 배치하여 Controller를 통해 접근이 가능합니다.

 

static 폴더에 있는 html 파일을 바로 호출하는 방법이 가장 간단하지만 외부 즉, 브라우저에서 바로 접근하지 못하게 하고 싶거나 특정 상황에 Controller를 통해서 제어하고 싶다면 이렇게 templates 폴더에 해당 정적 html 파일을 추가하고 해당 html 파일명인 "hello" 문자열을 반환하여 처리할 수 있습니다.(.html 은 생략 가능!)

@Controller
public class HtmlController {

    @GetMapping("/html/templates")
    public String htmlTemplates() {
        return "hello";
    }
}

 

 

 

동적 페이지 처리하기

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

@Controller
public class HtmlController {

    private static int visitCount = 0;

    @GetMapping("/html/dynamic")
    public String htmlDynamic(Model model) {
        visitCount++;
        model.addAttribute("visits", visitCount);
        return "hello-visit";

    }
}
<!-- /templates/hello-visit.html -->
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Hello Spring</title></head>
<body>
<div>
    Hello, Spring 동적 웹 페이지!!
</div>
<div>
    (방문자 수: <span th:text="${visits}"></span>)
</div>
</body>
</html>

 

1. Client 의 요청을 Controller에서 Model로 처리합니다.

    a. DB 조회가 필요하다면 DB 작업 후 처리한 데이터를 Model 에 저장

 

2. Template Engine(Thymeleaf)에게 View, Model을 전달합니다.

     a. View : 동적 HTML 파일

     b. View에 적용할 정보들

 

3. Template Engine

    a. View에 Model을 적용 -> 동적 웹 페이지를 생성

ex) 로그인 성공 시, "로그인된 사용자의 Nickname"을 페이지에 추가

※ Template Engine 종류 : Thymeleaf, JSP, Groovy, FreeMarker, Jade 등

 

4. Client(브라우저)에게 View(동적 웹페이지, HTML)를 전달