Spring Boot 할 일 목록 만들기

시작 화면 만들기

· 2 views

이어서 시작 화면용 컨트롤러와 HTML, 스타일, 오류 화면을 추가합니다. 아래 네 파일을 차례로 새로 만들고 내용을 모두 입력합니다. HomeController는 이 장에서만 쓰는 임시 클래스이고 다음 장에서 지웁니다.

[5] HomeController.java 시작 화면 컨트롤러
작업 5. src/main/java/com/example/todo/controller/HomeController.java 파일을 새로 만들고 아래 내용을 모두 입력합니다.

▼ Code

Path: src/main/java/com/example/todo/controller/HomeController.java

package com.example.todo.controller;

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

@Controller
public class HomeController {

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

▼ Explain

@Controller
웹 요청을 받아 화면 이름을 돌려주는 컨트롤러 클래스라는 표시입니다.

    @GetMapping("/")
브라우저에서 GET / 주소로 들어오면 아래 메서드를 실행합니다.

        return "index";
templates/index.html을 화면으로 보여 줍니다. 확장자 .html은 적지 않습니다.

개념 정리: @Controller와 요청 매핑

@Controller를 붙인 클래스는 브라우저 요청을 받는 창구가 됩니다. @GetMapping("/")은 GET 방식으로 / 주소에 온 요청을 바로 아래 메서드에 연결합니다. 메서드가 돌려주는 문자열 "index"는 화면 이름이고 Thymeleaf가 templates/index.html을 찾아 그립니다. 주소 하나에는 메서드 하나만 연결할 수 있으므로 같은 주소를 두 클래스에 적으면 실행이 실패합니다.

[6] index.html 시작 화면
작업 6. src/main/resources/templates/index.html 파일을 새로 만들고 아래 내용을 모두 입력합니다.

▼ Code

Path: src/main/resources/templates/index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>할 일 목록 앱</title>
    <link rel="stylesheet" th:href="@{/css/main.css}">
</head>
<body>
<div class="container">
    <h1>할 일 목록 앱을 시작합니다</h1>
    <p>개발 환경 설치와 첫 실행이 끝났습니다.</p>
</div>
</body>
</html>

▼ Explain

<html xmlns:th="http://www.thymeleaf.org">
th:로 시작하는 Thymeleaf 속성을 쓰겠다는 선언입니다. 모든 템플릿의 첫머리가 같습니다.

    <link rel="stylesheet" th:href="@{/css/main.css}">
static/css/main.css를 불러옵니다. @{ }는 앱 주소를 기준으로 경로를 만듭니다.

<div class="container">
화면 가운데 흰 상자입니다. 모든 화면이 이 상자 안에 내용을 담습니다.

[7] main.css 스타일
작업 7. src/main/resources/static/css/main.css 파일을 새로 만들고 아래 내용을 모두 입력합니다.
스타일시트는 이후 장의 목록과 폼에도 그대로 씁니다.

▼ Code

Path: src/main/resources/static/css/main.css

* {
    box-sizing: border-box;
}

body {
    margin: 0;
    font-family: "Malgun Gothic", "Apple SD Gothic Neo", sans-serif;
    background: #f5f5f5;
    color: #222;
}

.container {
    max-width: 720px;
    margin: 32px auto;
    padding: 24px;
    background: #fff;
    border: 1px solid #ddd;
}

h1 {
    margin-top: 0;
    font-size: 24px;
}

.toolbar {
    display: flex;
    gap: 8px;
    align-items: center;
    margin-bottom: 16px;
}

input[type="text"] {
    width: 100%;
    padding: 8px;
    font-size: 14px;
}

button, .button {
    display: inline-block;
    padding: 8px 14px;
    border: 1px solid #333;
    background: #333;
    color: #fff;
    text-decoration: none;
    font-size: 14px;
    cursor: pointer;
}

.button.secondary {
    background: #fff;
    color: #333;
}

.button.danger {
    background: #a33;
    border-color: #a33;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th, td {
    border-bottom: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

.done {
    color: #888;
    text-decoration: line-through;
}

.error {
    color: #a33;
    margin-bottom: 12px;
}

.meta {
    color: #666;
    font-size: 13px;
}

.empty {
    padding: 16px 0;
    color: #666;
}

.actions {
    margin-top: 16px;
    display: flex;
    gap: 8px;
}

▼ Explain

    box-sizing: border-box;
모든 요소의 너비에 안쪽 여백과 테두리를 포함해 상자가 넘치지 않게 합니다.

.container {
가운데 흰 상자의 모양입니다. 최대 너비 720px로 가운데에 놓습니다.

.toolbar {
검색칸과 등록 단추를 한 줄에 나란히 놓는 영역입니다.

button, .button {
button 태그와 button 클래스를 붙인 링크를 같은 단추 모양으로 맞춥니다.

.button.danger {
삭제 단추를 빨간색으로 구분합니다.

.done {
완료한 할 일의 제목을 회색으로 바꾸고 가운데 줄을 긋습니다.

.error {
입력 오류 문구를 빨간색으로 보여 줍니다.

.meta {
상세 화면의 등록일처럼 덧붙는 정보를 작은 회색 글씨로 보여 줍니다.

.empty {
할 일이 없을 때 나오는 안내 문구에 위아래 여백을 주고 회색으로 보여 줍니다.

.actions {
수정, 삭제, 목록 같은 단추를 가로로 나란히 놓습니다. 상세, 폼, 오류 화면에서 씁니다.


[8] error.html 오류 화면
작업 8. src/main/resources/templates/error.html 파일을 새로 만들고 아래 내용을 모두 입력합니다.

▼ Code

Path: src/main/resources/templates/error.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>오류</title>
    <link rel="stylesheet" th:href="@{/css/main.css}">
</head>
<body>
<div class="container">
    <h1>요청을 처리할 수 없습니다</h1>
    <p>주소를 다시 확인하거나 목록으로 돌아가 주세요.</p>
    <div class="actions">
        <a class="button secondary" th:href="@{/}">목록</a>
    </div>
</div>
</body>
</html>

▼ Explain

    <h1>요청을 처리할 수 없습니다</h1>
스프링 부트는 오류가 나면 templates/error.html을 찾아 보여 줍니다. 그래서 파일 이름이 error여야 합니다.

        <a class="button secondary" th:href="@{/}">목록</a>
오류 화면에서 목록으로 돌아가는 링크입니다.

여기까지 마치면 프로젝트 폴더는 아래와 같습니다.

▼ Code

Path: 폴더 구조

todo-app
├── build.gradle
├── settings.gradle
├── gradlew
├── gradlew.bat
├── gradle/wrapper/
├── sql/schema.sql
├── src/test/java/com/example/todo/TodoAppApplicationTests.java
└── src/main
    ├── java/com/example/todo
    │   ├── TodoAppApplication.java
    │   └── controller/HomeController.java
    └── resources
        ├── application.properties
        ├── static/css/main.css
        └── templates
            ├── index.html
            └── error.html

자주 하는 실수

  • 시작 클래스 밖에 컨트롤러를 둠
    • 증상 컨트롤러를 com.example.todo 바깥 패키지(예: com.example.web)에 두면 실행은 되지만 GET / 가 404 오류 화면으로 끝납니다.
    • 원인 @SpringBootApplication이 켜는 컴포넌트 스캔은 시작 클래스가 있는 com.example.todo 패키지와 그 하위만 찾습니다. 바깥 패키지의 컨트롤러는 빈으로 등록되지 않아 GET / 를 맡을 메서드가 없습니다.
    • 고치는 법 컨트롤러는 TodoAppApplication이 있는 com.example.todo 패키지나 그 아래(controller 등)에 둡니다.
  • 파일을 저장하지 않고 실행
    • 증상 고친 내용이 화면에 반영되지 않습니다.
    • 원인 Gradle은 디스크에 저장된 파일을 컴파일합니다. 편집기 화면에만 있는 내용은 빌드에 들어가지 않습니다.
    • 고치는 법 VS Code 탭 이름 옆의 점(저장 안 됨 표시)을 확인하고 저장(Ctrl+S)한 뒤 다시 실행합니다.

안 될 때

  • bootRun이 바로 끝나고 Communications link failure가 보임
    • 확인할 곳 MySQL 서버가 켜져 있는지
    • 고치는 방법 MySQL을 켠 뒤 다시 실행합니다.
  • Cannot find a Java installation ... languageVersion=25
    • 확인할 곳 JDK 25 설치 여부(.\gradlew.bat -q javaToolchains 목록에 25가 있는지)
    • 고치는 방법 JDK 25를 설치하고 터미널을 새로 엽니다.

댓글

아직 댓글이 없습니다.