2024.07.10.수.TIL 내일배움캠프 60일차 <정적 페이지 & 동적 페이지>

김기남·2024년 7월 10일
0
post-thumbnail

안녕하세요, 오늘은 입문주차 강의자료를 바탕으로 정적페이지와 동적페이지에 대해 다시 정리해보았습니다.

정적 페이지 처리하기

  1. static 폴더
    http://localhost:8080/hello.html
    /resources/static/hello.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello Spring</title>
</head>
<body>
Hello, Spring 정적 웹 페이지!! (static)
</body>
</html>

  • SpringBoot 서버에 html 파일을 바로 요청하면 해당 html 파일을 static 폴더에서 찾아서 반환해 줍니다.
  • 그렇다면 Controller를 거쳐서 html을 반환할 수도 있을까요?
    • 물론 가능합니다. 하지만 이미 완성된 정적인 html 파일을 Controller를 통해서 반환할 필요는 없겠죠?
    • Controller를 통해서 반환하는 것을 테스트 하려면
    • implementation 'org.springframework.boot:spring-boot-starter-thymeleaf’ 해당 dependency를 주석 처리해야 테스트가 가능합니다.
      • thymeleaf 는 동적 페이지 처리를 위한 템플릿 엔진입니다. 추가하면 자동으로 Controller에서 html 파일 찾는 경로를/resources/templates 로 설정합니다.
      • 주석 처리한 후 "hello.html" 이렇게 문자열로 반환하면 static 폴더의 해당 html 파일을 찾아 반환 해줍니다.
@GetMapping("/static-hello")
public String hello() {
    return "hello.html";
}
  1. Redirect
    http://localhost:8080/html/redirect
@GetMapping("/html/redirect")
public String htmlStatic() {
    return "redirect:/hello.html";
}
  • 템플릿 엔진을 적용한 상태에서 static 폴더의 html 파일을 Controller를 통해서 처리하고 싶다면 이렇게 "redirect:/hello.html" redirect 요청을 문자열로 반환하면 http://localhost:8080/hello.html 요청이 재 수행되면서 static 폴더의 파일을 반환할 수 있습니다.

  1. Template engine 에 View 전달
    http://localhost:8080/html/templates
@GetMapping("/html/templates")
public String htmlTemplates() {
    return "hello";
}

타임리프 default 설정

  • prefix: classpath:/templates/
  • suffix: .html

/resources/templates/hello.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello Spring</title>
</head>
<body>
Hello, Spring 정적 웹 페이지!! (templates)
</body>
</html>

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

동적 페이지 처리하기

http://localhost:8080/html/dynamic

<!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>
private static long visitCount = 0;

...

@GetMapping("/html/dynamic")
public String htmlDynamic(Model model) {
    visitCount++;
    model.addAttribute("visits", visitCount);
    return "hello-visit";
}
  • 동적 페이지 처리 과정
    1. Client 의 요청을 Controller에서 Model 로 처리합니다.
      1. DB 조회가 필요하다면 DB 작업 후 처리한 데이터를 Model에 저장합니다.
    2. Template engine(Thymeleaf) 에게 View, Model 전달합니다.
      1. View: 동적 HTML 파일
      2. Model: View 에 적용할 정보들
    3. Template engine
      1. ViewModel을 적용 → 동적 웹페이지 생성
        1. 예) 로그인 성공 시, "로그인된 사용자의 Nickname"을 페이지에 추가
        2. Template engine 종류: 타임리프(Thymeleaf), Groovy, FreeMarker, Jade, JSP 등
    4. Client(브라우저)에게 View(동적 웹 페이지, HTML)를 전달 해줍니다.
  • Thymeleaf
    • View 정보
      • "hello-visit" → resources/templates/hello-visit.html
    • Model 정보
      • visits: 방문 횟수 (visitCount)
      • 예) 방문 횟수: 1,000,000
<div>
  (방문자 수: <span th:text="${visits}"></span>)
</div>
<div>
  (방문자 수: <span>1000000</span>)
</div>
package com.sparta.springmvc.html;

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

@Controller
public class HtmlController {

    private static long visitCount = 0;

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

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

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

    @GetMapping("/html/dynamic")
    public String htmlDynamic(Model model) {
        visitCount++;
        model.addAttribute("visits", visitCount);
        return "hello-visit";
    }
}
profile
새로운 시작~!

0개의 댓글