정적 동적 페이지

Jay·2023년 8월 27일

Spring

목록 보기
11/17

Untitled.png

  1. static폴더

Untitled (1).png

  • SpringBoot 서버에 html 파일을 바로 요청하면 해당 html 파일을 static 폴더에서 찾아서 반환
  • Controller를 통해서도 반환할수 있지만 이미 완성된 정적 html파일을 그렇게 할 필요는 없다
    • Controller를 통해서 반환하는 것을 테스트 하려면
    • implementation 'org.springframework.boot:spring-boot-starter-thymeleaf’ 해당 dependency를 주석 처리해야 테스트가 가능
      • thymeleaf 는 동적 페이지 처리를 위한 템플릿 엔진으로 추가하면 자동으로 Controller에서 html 파일 찾는 경로를/resources/templates 로 설정
  1. redirect
  • 템플릿 엔진을 적용한 상태에서 static 폴더의 html 파일을 Controller를 통해서 처리하고 싶다면 이렇게 "redirect:/hello.html" redirect 요청을 문자열로 반환하면 http://localhost:8080/hello.html ****요청이 재 수행되면서 static 폴더의 파일을 반환 Screen_Shot_2023-05-15_at_3.20.54_PM.png
  1. Template engine 에 View 전달

    🌐 http://localhost:8080**/html/templates**

    타임리프 default 설정

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

    /resources/templates/hello.html

    Untitled

    • 브라우저에서 바로 접근하지 못하게 하고 싶거나 특정 상황에 Controller를 통해서 제어하고 싶다면 이렇게 templates 폴더에 해당 정적 html 파일을 추가하고 해당 html 파일명인 `"hello"` 문자열을 반환하여 처리할 수 있다 (.html은 생략가능!)

동적 페이지 처리

  • 동적 페이지 처리 과정
    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

        <div>
          (방문자 수: <span th:text="${**visits**}"></span>)
        </div>
    • Model 정보
      - visits: 방문 횟수 (visitCount)
      - 예) 방문 횟수: 1,000,000

          ![스크린샷 2023-08-25 20.18.17.png](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/03d72aaa-15e1-49ab-8fdc-d687a0a4eec7/%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA_2023-08-25_20.18.17.png)
          
      // controller
      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"; // templates파일 안에 있어야만 호출할수있다
          }
      
          @GetMapping("/html/redirect")
          public String htmlStatic(){
              return "redirect:/hello.html"; // 직접접근하는 경로를 redirect다음에 작성
              // state code가 302가 나온다
              // location쪽은 hello.html을 직접 url에 작성했을때랑 같은게 나온다
              // redirect를 통해 한번더 직접 방문
          }
      
          @GetMapping("/html/templates")
          public String htmlTemplates(){
              return "hello"; // 확장자 생략이 가능
              // thymeleaf가 자동으로 확장자를 생략가능해도 찾을 수 있게한다
          }
      
          @GetMapping("html/dynamic")
          public String htmlDynamic(Model model){// springframe work에있는 Model
              visitCount ++;
              model.addAttribute("visits",visitCount);
              return "hello-visit";
          }
      }
      <!DOCTYPE html>
      <html>
      <head><meta charset="UTF-8"><title>Hello Spring</title></head>
      <body>
      <div>
          Hello, Spring 동적 웹 페이지!!
      </div>
      <div>
          (방문자 수: <span th:text="${visits}"></span>)
      <!--   model의 이름이 visits인 값을 가져옴  -->
      </div>
      </body>
      </html>
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
        <title>Hello Spring</title>
      </head>
      <body>
      Hello, Spring 정적 웹 페이지!! (templates)
      </body>
      </html>

0개의 댓글