[JPA] 7. 웹 계층 개발 - 홈 화면과 레이아웃

2025. 5. 20. 15:03·BE/SpringBoot
728x90

스프링부트 타임리프 기본 설정

spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html

스프링 부트 타임리프 viewName 매핑

  • `resources:templates/` +{ViewName}+ `.html`
  • `resources:templates/home.html`

반환한 문자(home)와 스프링부트 설정 `prefix` , `suffix` 정보를 사용해서 렌더링할 뷰(html)를 찾는다.

HomeController.java

@Controller
@Slf4j //Logger log = LoggerFactory.getLogger(getClass());
public class HomeController {

    @RequestMapping("/")
    public String home(){
        log.info("home controller");
        return "home";
    }
}

@Slf4j는 롬복(Lombok)에서 제공하는 어노테이션으로 아래와 같은 코드를 자동으로 생성해준다.

private static final Logger log = LoggerFactory.getLogger(현재클래스이름.class);

 

Home.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/header :: header}">
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div class="container">
    <div th:replace="~{fragments/bodyHeader :: bodyHeader}" />
    <div class="jumbotron">
        <h1>HELLO SHOP</h1>
        <p class="lead">회원 기능</p>
        <p>
            <a class="btn btn-lg btn-secondary" href="/members/new">회원 가입</a>
            <a class="btn btn-lg btn-secondary" href="/members">회원 목록</a>
        </p>
        <p class="lead">상품 기능</p>
        <p>
            <a class="btn btn-lg btn-dark" href="/items/new">상품 등록</a>
            <a class="btn btn-lg btn-dark" href="/items">상품 목록</a>
        </p>
        <p class="lead">주문 기능</p>
        <p>
            <a class="btn btn-lg btn-info" href="/order">상품 주문</a>
            <a class="btn btn-lg btn-info" href="/orders">주문 내역</a>
        </p>
    </div>
    <div th:replace="~{fragments/footer :: footer}" />
</div> <!-- /container -->
</body>
</html>

Home.html을 잘 보면 아래와 같은 코드들이 있다.

<head th:replace="~{fragments/header :: header}">

<div th:replace="~{fragments/bodyHeader :: bodyHeader}" />

<div th:replace="~{fragments/footer :: footer}" />

이 코드들은 타임리프에서 반복적으로 쓰이는 HTML 코드를 분리해 재사용하는 방식이다. 

 

맨 처음에 있는 head~의 의미는 fragments/header.html 파일 안에 정의된 <head> 영역의

th:fragment="header"라는 조각을 이 자리에 포함하라는 의미

fragments/header.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="header">
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1,shrink-to-fit=no">
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="/css/bootstrap.min.css" integrity="sha384-
        ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
        crossorigin="anonymous">
  <!-- Custom styles for this template -->
  <link href="/css/jumbotron-narrow.css" rel="stylesheet">
  <title>Hello, world!</title>
</head>

즉, fragments/header.html 파일 내의 <head> 영역의 th:fragment="header" 를 include 해준 것!

 

Thymeleaf Page Layouts - Thymeleaf

Summary In this article, we described many ways of achieving the same: layouts. You can build layouts using Thymeleaf Standard Layout System that is based on include-style approach. You also have powerful Layout Dialect, that uses decorator pattern for wor

www.thymeleaf.org

위의 코드에서는 header와 footer같은 템플릿 파일을 반복해서 include 해야한다.

링크 내의 Hierarchical-style layouts 참고하면 중복 제거도 가능하다.

 

좌) 부트스트랩 적용 전 / 우)부트스트랩 적용 후

/* Space out content a bit */
body {
    padding-top: 20px;
    padding-bottom: 20px;
}
/* Everything but the jumbotron gets side spacing for mobile first views */
.header,
.marketing,
.footer {
    padding-left: 15px;
    padding-right: 15px;
}
/* Custom page header */
.header {
    border-bottom: 1px solid #e5e5e5;
}
/* Make the masthead heading the same height as the navigation */
.header h3 {
    margin-top: 0;
    margin-bottom: 0;
    line-height: 40px;
    padding-bottom: 19px;
}
/* Custom page footer */
.footer {
    padding-top: 19px;
    color: #777;
    border-top: 1px solid #e5e5e5;
}
/* Customize container */
@media (min-width: 768px) {
    .container {
        max-width: 730px;
    }
}
.container-narrow > hr {
    margin: 30px 0;
}
/* Main marketing message and sign up button */
.jumbotron {
    text-align: center;
    border-bottom: 1px solid #e5e5e5;
}
.jumbotron .btn {
    font-size: 21px;
    padding: 14px 24px;
}
/* Supporting marketing content */
.marketing {
    margin: 40px 0;
}
.marketing p + h4 {
    margin-top: 28px;
}
/* Responsive: Portrait tablets and up */
@media screen and (min-width: 768px) {
    /* Remove the padding we set earlier */
    .header,
    .marketing,
    .footer {
        padding-left: 0;
        padding-right: 0;
    }
    /* Space out the masthead */
    .header {
        margin-bottom: 30px;
    }
    /* Remove the bottom border on the jumbotron for visual effect */
    .jumbotron {
        border-bottom: 0;
    }
}

CSS 적용시켜주면 아래와 같은 화면이 나타난다.

728x90

'BE > SpringBoot' 카테고리의 다른 글

[JPA] 6. 주문 도메인 개발 - 주문 검색 기능 개발  (0) 2025.05.20
[JPA] 6. 주문 도메인 개발 - 리포지토리/서비스/테스트  (0) 2025.05.17
[JPA] 6. 주문 도메인 개발 - 주문, 주문상품 엔티티 개발  (1) 2025.05.14
[JPA] 5. 상품 도메인 개발  (0) 2025.05.14
[JPA] 4. 회원 도메인 개발  (0) 2025.05.13
'BE/SpringBoot' 카테고리의 다른 글
  • [JPA] 6. 주문 도메인 개발 - 주문 검색 기능 개발
  • [JPA] 6. 주문 도메인 개발 - 리포지토리/서비스/테스트
  • [JPA] 6. 주문 도메인 개발 - 주문, 주문상품 엔티티 개발
  • [JPA] 5. 상품 도메인 개발
DROPDEW
DROPDEW
💻 Developer | 기록하지 않으면 존재하지 않는다
  • DROPDEW
    제 2장 1막
    DROPDEW
  • 전체
    오늘
    어제
    • Dev (444)
      • App·Android (1)
      • AI (10)
      • BE (50)
        • HTTP 웹 기본 지식 (8)
        • SpringBoot (23)
        • 스프링부트와 JPA 활용 (0)
        • JAVA (1)
        • PHP (11)
      • FE·Client (23)
        • HTML (1)
        • React (19)
        • Unity (1)
      • Data (28)
        • Bigdata (6)
        • Database (1)
        • Python (0)
        • 빅데이터분석기사 (13)
      • Infra (1)
      • Activity (7)
        • Intern (0)
        • SK AI Dream Camp (0)
        • 구름톤 유니브 4기 (1)
        • 리모트 인턴십 6기 (3)
        • 봉사활동 (0)
        • 부스트캠프 AI Tech 8기 (3)
      • CS (8)
      • 취준 (12)
        • 자격증 (4)
        • 인적성·NCS (6)
        • 코테·필기·면접 후기 (2)
      • 코테 (270)
        • Algorithm (222)
        • SQL (35)
        • 정리 (13)
      • 인사이트 (27)
        • 금융경제뉴스 (7)
        • 금융용어·지식 (2)
        • 북마크 (7)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자료구조
    오블완
    브루트포스 알고리즘
    백준
    구현
    매개변수탐색
    시뮬레이션
    정렬
    투포인터
    그리디알고리즘
    누적합
    너비우선탐색
    그래프이론
    다이나믹프로그래밍
    수학
    그래프탐색
    티스토리챌린지
    최단경로
    이분탐색
    문자열
  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
DROPDEW
[JPA] 7. 웹 계층 개발 - 홈 화면과 레이아웃
상단으로

티스토리툴바