Spring Boot 할 일 목록 만들기

코드 작성과 설명

· 1 views

[1] detail.html 수정 버튼
작업 1. src/main/resources/templates/detail.html 파일을 아래 내용과 같게 고칩니다.
색이 다르고 굵은 줄이 이번에 바뀐 줄입니다.
아래는 이 단계까지 고친 파일 전체입니다.

상세 화면에 수정 버튼을 추가합니다. 삭제 버튼은 다음 장에서 넣습니다.

▼ Code

Path: src/main/resources/templates/detail.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><strong>번호</strong> <span th:text="${todo.id}">1</span></p>
    <p><strong>제목</strong> <span th:text="${todo.title}" th:classappend="${todo.done} ? 'done'">제목</span></p>
    <p><strong>상태</strong> <span th:text="${todo.done} ? '완료' : '미완료'">미완료</span></p>
    <p class="meta"><strong>등록일</strong> <span th:text="${#temporals.format(todo.createdAt, 'yyyy-MM-dd HH:mm')}">2026-11-23 10:00</span></p>
    <div class="actions">
        <a class="button" th:href="@{/todos/{id}/edit(id=${todo.id})}">수정</a>
        <a class="button secondary" th:href="@{/}">목록</a>
    </div>
</div>
</body>
</html>

▼ Explain

        <a class="button" th:href="@{/todos/{id}/edit(id=${todo.id})}">수정</a>
새로 넣은 수정 버튼입니다. {id} 자리에 이 할 일의 번호가 들어가 /todos/3/edit 같은 주소로 이동합니다.

[2] edit.html 수정 폼
작업 2. src/main/resources/templates/edit.html 파일을 새로 만들고 아래 내용을 모두 입력합니다.

수정 폼입니다.
완료 체크박스는 value="true" 이고 체크되었을 때만 done 파라미터가 전송됩니다.

▼ Code

Path: src/main/resources/templates/edit.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 class="error" th:if="${errorMessage != null and !errorMessage.isEmpty()}" th:text="${errorMessage}">오류</p>
    <form th:action="@{/todos/{id}(id=${todo.id})}" method="post">
        <p>
            <label for="title">제목</label>
            <input id="title" type="text" name="title" th:value="${todo.title}" maxlength="200">
        </p>
        <p>
            <label>
                <input type="checkbox" name="done" value="true" th:checked="${todo.done}">
                완료
            </label>
        </p>
        <div class="actions">
            <button type="submit">저장</button>
            <a class="button secondary" th:href="@{/todos/{id}(id=${todo.id})}">취소</a>
        </div>
    </form>
</div>
</body>
</html>

▼ Explain

    <form th:action="@{/todos/{id}(id=${todo.id})}" method="post">
수정 폼은 POST /todos/번호로 보냅니다. 등록 폼과 달리 주소에 번호가 들어갑니다.

            <input id="title" type="text" name="title" th:value="${todo.title}" maxlength="200">
th:value로 지금 제목을 입력칸에 미리 채워 둡니다.

                <input type="checkbox" name="done" value="true" th:checked="${todo.done}">
th:checked로 저장된 완료 여부에 맞춰 체크 상태를 채웁니다.
체크하지 않으면 done 값은 요청에 담기지 않습니다.

개념 정리: 체크박스와 defaultValue

체크박스는 체크되었을 때만 name="done" 값이 요청에 담기고 체크하지 않으면 아예 보내지지 않습니다. 그래서 컨트롤러는 @RequestParam(defaultValue = "false") boolean done으로 받습니다. 값이 없으면 false가 들어가므로 완료 해제가 저장됩니다. th:checked="${todo.done}"는 수정 폼을 열 때 저장된 값에 맞춰 체크 상태를 채웁니다.

[3] TodoController.java 수정 폼 열기와 저장 메서드
작업 3. src/main/java/com/example/todo/controller/TodoController.java 파일을 아래 내용과 같게 고칩니다.
색이 다르고 굵은 줄이 이번에 바뀐 줄입니다.
아래는 이 단계까지 고친 파일 전체입니다.

▼ Code

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

package com.example.todo.controller;

import com.example.todo.domain.Todo;
import com.example.todo.repository.TodoRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequiredArgsConstructor
public class TodoController {

    private final TodoRepository todoRepository;

    @GetMapping("/")
    public String list(Model model) {
        List<Todo> todos = todoRepository.findAllByOrderByIdDesc();
        model.addAttribute("todos", todos);
        return "list";
    }

    @GetMapping("/todos/new")
    public String createForm(Model model) {
        model.addAttribute("title", "");
        model.addAttribute("errorMessage", "");
        return "form";
    }

    @PostMapping("/todos")
    public String create(@RequestParam String title, Model model) {
        String trimmed = title == null ? "" : title.trim();
        String errorMessage = validateTitle(trimmed);
        if (errorMessage != null) {
            model.addAttribute("title", title == null ? "" : title);
            model.addAttribute("errorMessage", errorMessage);
            return "form";
        }
        Todo todo = new Todo(trimmed);
        todoRepository.save(todo);
        return "redirect:/";
    }

    @GetMapping("/todos/{id}")
    public String detail(@PathVariable Long id, Model model) {
        Todo todo = todoRepository.findById(id)
                .orElseThrow(() -> new TodoNotFoundException(id));
        model.addAttribute("todo", todo);
        return "detail";
    }

    @GetMapping("/todos/{id}/edit")
    public String editForm(@PathVariable Long id, Model model) {
        Todo todo = todoRepository.findById(id)
                .orElseThrow(() -> new TodoNotFoundException(id));
        model.addAttribute("todo", todo);
        model.addAttribute("errorMessage", "");
        return "edit";
    }

    @PostMapping("/todos/{id}")
    public String update(@PathVariable Long id,
                         @RequestParam String title,
                         @RequestParam(defaultValue = "false") boolean done,
                         Model model) {
        Todo todo = todoRepository.findById(id)
                .orElseThrow(() -> new TodoNotFoundException(id));
        String trimmed = title == null ? "" : title.trim();
        String errorMessage = validateTitle(trimmed);
        if (errorMessage != null) {
            todo.setTitle(title == null ? "" : title);
            todo.setDone(done);
            model.addAttribute("todo", todo);
            model.addAttribute("errorMessage", errorMessage);
            return "edit";
        }
        todo.setTitle(trimmed);
        todo.setDone(done);
        todoRepository.save(todo);
        return "redirect:/todos/" + id;
    }

    private String validateTitle(String trimmed) {
        if (trimmed.isEmpty()) {
            return "제목을 입력해 주세요.";
        }
        if (trimmed.length() > 200) {
            return "제목은 200자 이하로 입력해 주세요.";
        }
        return null;
    }
}

▼ Explain

    @GetMapping("/todos/{id}/edit")
수정 폼을 여는 주소입니다. 상세와 같은 방법으로 한 건을 찾아 edit.html에 넘깁니다. 없는 번호면 상세와 같은 TodoNotFoundException이 나서 404 오류 화면이 됩니다.

    @PostMapping("/todos/{id}")
수정 폼이 보낸 POST /todos/번호를 받습니다. 상세 화면과 주소는 같고 방식만 POST입니다.

                         @RequestParam(defaultValue = "false") boolean done,
체크칸을 비우면 done 값이 오지 않으므로 기본값 false를 씁니다.

        String errorMessage = validateTitle(trimmed);
등록 장에서 만든 validateTitle을 그대로 씁니다. 빈 제목과 200자 초과를 등록과 같은 문구로 막습니다.

            todo.setTitle(title == null ? "" : title);
검사에 걸리면 사용자가 넣은 값을 객체에 담아 수정 폼을 다시 그립니다. save를 부르지 않으므로 데이터베이스는 바뀌지 않습니다. 이 책은 트랜잭션 없이 저장소를 바로 부르므로 객체 값을 바꾸기만 해서는 UPDATE가 나가지 않습니다.

        todo.setDone(done);
체크칸에서 받은 done 값으로 완료 여부를 바꿉니다. 검사에 걸렸을 때도 같은 값을 담아 폼에 다시 보여 줍니다.

        todoRepository.save(todo);
등록과 같은 save지만 이번에는 id가 있는 객체라 INSERT가 아닌 UPDATE가 실행됩니다.

        return "redirect:/todos/" + id;
저장 뒤 그 할 일의 상세 화면으로 돌아갑니다.


개념 정리: save가 INSERT와 UPDATE를 고르는 방식

JpaRepository의 save는 엔티티의 id가 비어 있으면 새 행으로 보고 INSERT를 실행합니다. 등록에서 new Todo(trimmed)로 만든 객체는 id가 null이라 INSERT가 됩니다. 수정에서는 findById로 읽어 온 객체라 id가 있으므로 save가 기존 행을 다시 조회한 뒤 UPDATE를 실행합니다. 이 책의 앱을 실행해 콘솔에 찍힌 SQL을 보면 등록은 insert into todo, 수정은 update todo set ... where id=? 로 나옵니다.

실무에서는: 트랜잭션과 변경 감지

이 책은 수정할 때 save를 직접 부릅니다. 실무에서는 서비스 메서드에 @Transactional을 붙이고 그 안에서 조회한 엔티티의 값을 바꾸면 트랜잭션이 끝날 때 UPDATE가 자동으로 실행되는 방식(변경 감지)을 많이 씁니다. 여러 테이블을 함께 바꿀 때 하나라도 실패하면 모두 되돌리는 것도 트랜잭션의 역할입니다.

자주 하는 실수

  • 체크박스 defaultValue를 빠뜨림
    • 증상 체크를 끄고 저장하면 done 값이 없어 400 오류가 납니다.
    • 원인 체크하지 않은 체크박스는 값을 아예 보내지 않습니다. @RequestParam은 기본이 필수라서 done이 없으면 400이 납니다.
    • 고치는 법 @RequestParam(defaultValue = "false") boolean done으로 받습니다.
  • 수정 뒤 이동 주소를 목록으로 둠
    • 증상 저장은 되지만 상세가 아니라 목록이 열려 결과를 바로 못 봅니다.
    • 원인 redirect 주소가 / 이면 브라우저는 목록을 다시 요청합니다. 저장은 정상으로 되어 있습니다.
    • 고치는 법 return "redirect:/todos/" + id; 로 상세 화면으로 돌아갑니다.

안 될 때

  • 완료를 끄고 저장하면 400 오류
    • 확인할 곳 update 메서드의 done 매개변수
    • 고치는 방법 @RequestParam(defaultValue = "false")를 붙입니다.

댓글

아직 댓글이 없습니다.