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

정재현·2024년 1월 22일
0

Spring Boot

목록 보기
14/19
post-thumbnail

SpringBoot를 이용해 정적 페이지 생성/반환 하기

  • static에 존재하는 정적인 페이지는 template에 존재하지 않기 때문에 localhost:8080/hello.html같이 페이지 이름을 직접 넣어서 접근
    • HTML코드는 이미 완성된 코드이기 때문에 굳이 Controller를 통해 거쳐서 반환할 필요가 없다.
    • dependencies에서 ..thymeleaf는 템플릿 엔진이라고해서 동적인 웹 페이지를 만들기 위한 라이브러리인데 이걸 추가하면 기본적으로 Spring에서 Controller에서 GET으로 파일을 찾을 때 template 폴더 내부에서 찾도록 내부적으로 설정이 되어 있다. 따라서 이 부분을 주석처리해면 직접 점근(localhost:8080/hello.html)이 아닌 localhost:8080/static-hello 방식인 Controller를 통해서 GET을 할 수 있다.

static 폴더에 있는 HTML파일에 접근하기 위한 방법

  1. URL 경로에서 직접 접근 (localhost:8080/hello.html)
  2. thymeleaf가 dependencies에 설정되어 있지 않은 상황에서 Controller를 거쳐서 GetMapping으로 접근 (localhost:8080/static-hello)
@GetMapping("/static-hello")
public String hello() {
    return "hello.html";
}
  1. thymeleaf가 dependencies에 설정되어 있는 상황에서 redirect:/직접접근 경로를 이용해 직접접근하는 경로로 다시 요청하는 방법
    (return "redirect:/직접접근 경로";)
@GetMapping("/html/redirect")
public String htmlStatic() {
    return "redirect:/hello.html";
}
  1. 정적인 파일(HTML파일)을 template에 넣어서 반환하는 방법
  • static폴더에 있는 html파일을 바로 호출하는 방법
  • 가장 간단하지만 브라우저에서 바로 접근하지 못하게 하고 싶거나 특정 상황에 Controller를 통해서 제어하고 싶다면 templates폴더에 해당 정적 html파일을 추가하고 해당 html파일명을 문자열로 반환하여 처리(.html은 생략가능)
@GetMapping("/html/templates")
public String htmlTemplates() {
    return "hello";
}

SpringBoot를 이용해 동적 페이지 생성/반환 하기

  1. Client 의 요청을 Controller에서 Model 로 처리
    • 데이터를 모델로 넣는 기능을 Spring에서 Model 클래스(org.springframework.ui)를 지원
    • DB 조회가 필요하다면 DB 작업 후 처리한 데이터를 Model에 저장
  2. Template engine(Thymeleaf) 에게 View, Model 전달합니다.
    • View: 동적 HTML 파일
    • Model: View 에 적용할 정보들
  3. Template engine
    • ViewModel을 적용 → 동적 웹페이지 생성
      • 예) 로그인 성공 시, "로그인된 사용자의 Nickname"을 페이지에 추가
      • Template engine 종류: 타임리프(Thymeleaf), Groovy, FreeMarker, Jade, JSP 등
  4. Client(브라우저)에게 View(동적 웹 페이지, HTML)를 전달 해줍니다.

profile
공부 기록 보관소

0개의 댓글