Coding 공부/IntelliJ

[IntelliJ_Springboot] Springboot 자원 자동 서빙, 리다이렉트 vs 뷰 반환 방식

CBJH 2024. 5. 29. 18:23
728x90
반응형

1. Springboot 자원 불러오기

Spring Boot는 src/main/resources/static 디렉토리에 있는 정적 파일을 자동으로 서빙합니다.

src/
└── main/
    └── resources/
        ├── static/
        │   └── css/
        │       └── sign-in.css
        └── templates/
            └── board/
                └── index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Index Page</title>
    <link rel="stylesheet" href="/css/sign-in.css">
</head>
<body>
    <h1>Welcome to the Board Index Page!</h1>
</body>
</html>

 

  • 정적 파일 위치: 정적 파일은 src/main/resources/static 디렉토리에 배치합니다.
  • 템플릿 파일 링크: HTML 템플릿 파일에서 <link rel="stylesheet" href="/css/sign-in.css"> 태그를 사용하여 CSS 파일을 링크합니다.
  • 폴더 구조: 정적 파일과 템플릿 파일의 폴더 구조를 올바르게 설정합니다.

 

2. Springboot Controller 리다이렉트 vs 뷰 반환 방식

 

 2.1 리다이렉트 방식

아래는 / 경로로 요청이 들어오면 index.html로 리다이렉트하는 예제 코드입니다.

@Controller
public class MainController {

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

 

리다이렉트 설명

  • @GetMapping("/"): 루트 경로로 들어오는 GET 요청을 처리합니다.
  • return "redirect:/index.html": index.html로 리다이렉트합니다.

추가 설명

  • index.html 파일은 보통 src/main/resources/static 폴더에 위치해야 합니다.
  • Spring Boot는 기본적으로 src/main/resources/static 폴더 내의 정적 파일을 자동으로 서빙합니다.
src/
└── main/
    └── resources/
        └── static/
            └── index.html

이렇게 설정하면, 사용자가 브라우저에서 http://localhost:8080/에 접속할 때 index.html 페이지로 리다이렉트됩니다.

 

 2.2 뷰 반환형식

아래는 / 경로로 들어오는 요청을 board/index.html 파일로 매핑하는 예제입니다.

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

@Controller
public class MainController {

    @GetMapping("/")
    public String indexGet() {
        return "board/index";
    }
}

뷰 템플릿 설정

  • return "board/index";는 src/main/resources/templates/board/index.html 파일을 의미합니다.
  • Spring Boot는 src/main/resources/templates 디렉토리를 기본 템플릿 위치로 사용합니다.

폴더 구조

프로젝트의 폴더 구조는 다음과 같아야 합니다.

src/
└── main/
    └── resources/
        └── templates/
            └── board/
                └── index.html

요약

  • 컨트롤러 수정: MainController 클래스의 indexGet 메서드에서 "board/index"를 반환하도록 합니다.
  • 템플릿 파일 위치: src/main/resources/templates/board/index.html 위치에 HTML 파일을 둡니다.
  • Thymeleaf 사용: Spring Boot는 기본적으로 Thymeleaf를 사용하여 templates 디렉토리의 HTML 파일을 렌더링합니다.

이렇게 설정하면 사용자가 브라우저에서 http://localhost:8080/에 접속할 때 src/main/resources/templates/board/index.html 파일이 렌더링됩니다.