Spring Boot 할 일 목록 만들기

코드 작성과 설명

· 3 views

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

list.html 의 제목 아래에 도구 줄을 추가하고 등록 버튼을 넣습니다.
나머지 표 코드는 그대로 둡니다.

▼ Code

Path: src/main/resources/templates/list.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>
    <div class="toolbar">
        <a class="button" th:href="@{/todos/new}">등록</a>
    </div>
    <p class="empty" th:if="${#lists.isEmpty(todos)}">할 일이 없습니다.</p>
    <table th:if="${!#lists.isEmpty(todos)}">
        <thead>
        <tr>
            <th>번호</th>
            <th>제목</th>
            <th>상태</th>
            <th>등록일</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="todo : ${todos}">
            <td th:text="${todo.id}">1</td>
            <td th:text="${todo.title}">제목</td>
            <td th:text="${todo.done} ? '완료' : '미완료'">미완료</td>
            <td th:text="${#temporals.format(todo.createdAt, 'yyyy-MM-dd HH:mm')}">2026-11-23 10:00</td>
        </tr>
        </tbody>
    </table>
</div>
</body>
</html>

▼ Explain

        <a class="button" th:href="@{/todos/new}">등록</a>
등록 화면 주소 /todos/new로 가는 단추입니다.

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

등록 폼을 새로 작성합니다.
name="title" 은 컨트롤러의 @RequestParam String title 과 이름이 같아야 합니다.

▼ Code

Path: src/main/resources/templates/form.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}" method="post">
        <p>
            <label for="title">제목</label>
            <input id="title" type="text" name="title" th:value="${title}" maxlength="200">
        </p>
        <div class="actions">
            <button type="submit">저장</button>
            <a class="button secondary" th:href="@{/}">목록</a>
        </div>
    </form>
</div>
</body>
</html>

▼ Explain

    <p class="error" th:if="${errorMessage != null and !errorMessage.isEmpty()}" th:text="${errorMessage}">오류</p>
오류 문구가 있을 때만 빨간 글자로 보여 줍니다.

    <form th:action="@{/todos}" method="post">
저장을 누르면 POST /todos로 입력값을 보냅니다.

            <input id="title" type="text" name="title" th:value="${title}" maxlength="200">
name="title"이 컨트롤러의 @RequestParam String title과 짝입니다. th:value는 오류가 났을 때 입력한 글자를 되살립니다.

개념 정리: 폼 전송과 @RequestParam

form 태그의 method="post"와 th:action="@{/todos}"는 저장 버튼을 누를 때 POST /todos 요청을 보내게 합니다. 입력칸의 name="title"이 요청에 담기는 값의 이름입니다. 컨트롤러의 @RequestParam String title은 같은 이름의 값을 받아 매개변수에 넣습니다. 두 이름이 다르면 값이 넘어오지 않으므로 폼의 name과 컨트롤러 매개변수 이름을 항상 같이 확인합니다.

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

컨트롤러에 두 메서드를 추가합니다. 기존 list 메서드는 그대로 둡니다.

▼ 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.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:/";
    }

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

▼ Explain

    @GetMapping("/todos/new")
GET /todos/new는 빈 등록 화면을 보여 줍니다.

        model.addAttribute("title", "");
처음 열 때는 입력칸과 오류 문구를 빈 값으로 넘깁니다.

    @PostMapping("/todos")
폼이 보낸 POST /todos를 받아 저장합니다. 같은 /todos라도 GET과 POST는 다른 메서드가 맡습니다.

    public String create(@RequestParam String title, Model model) {
@RequestParam은 폼의 name="title" 값을 받습니다.

        String trimmed = title == null ? "" : title.trim();
앞뒤 공백을 지웁니다. 공백만 넣은 제목을 빈 제목으로 보기 위해서입니다.

        String errorMessage = validateTitle(trimmed);
제목 검사는 클래스 맨 아래의 validateTitle 메서드가 맡습니다. 통과하면 null을, 막아야 하면 화면에 보여 줄 문구를 돌려줍니다.

        if (errorMessage != null) {
문구가 있으면 저장하지 않고 입력값과 문구를 모델에 담아 등록 화면으로 돌려보냅니다.

        Todo todo = new Todo(trimmed);
다듬은 제목으로 새 할 일 객체를 만듭니다. 앞 장에서 Todo에 만든 생성자를 씁니다.

        todoRepository.save(todo);
저장소의 save로 INSERT가 실행됩니다. id는 MySQL이 채우고 등록 시각은 @PrePersist가 채웁니다.

        return "redirect:/";
저장 뒤 목록 주소로 다시 보냅니다. 새로고침해도 같은 할 일이 두 번 저장되지 않습니다.

    private String validateTitle(String trimmed) {
제목 규칙을 한곳에 모은 메서드입니다. 다음 장의 수정 기능도 이 메서드를 그대로 씁니다. 클래스 안에서만 쓰므로 private입니다.

        if (trimmed.isEmpty()) {
빈 제목이면 "제목을 입력해 주세요."를 돌려줍니다.

        if (trimmed.length() > 200) {
todo 테이블의 title은 VARCHAR(200)입니다. 200자를 넘는 제목을 그대로 저장하면 MySQL이 거부해 500 오류가 나므로 저장 전에 막습니다.
입력칸의 maxlength="200"은 브라우저 화면에서만 막아 줍니다. Postman처럼 요청을 직접 보내면 그대로 들어오므로 서버에서도 검사합니다.
length()는 이모지처럼 두 칸을 쓰는 글자를 2로 셉니다. 그만큼 조금 일찍 막을 뿐 저장 오류는 나지 않습니다.

개념 정리: 입력 검증

사용자가 보낸 값은 저장하기 전에 확인해야 합니다. 이 책에서는 trim()으로 앞뒤 공백을 지운 뒤 validateTitle 메서드에서 두 가지를 봅니다. 비었으면 "제목을 입력해 주세요.", 200자를 넘으면 "제목은 200자 이하로 입력해 주세요."를 돌려줍니다. 문구가 있으면 저장하지 않고 오류 문구와 입력값을 모델에 넣어 같은 폼을 다시 보여 줍니다. 공백만 넣은 제목도 trim() 뒤에는 빈 문자열이 되므로 함께 걸러집니다.

입력칸의 maxlength="200"은 브라우저 화면에서만 막아 줍니다. Postman이나 다른 프로그램은 화면을 거치지 않고 요청을 보내므로, 데이터베이스 컬럼 크기(VARCHAR(200))를 넘는 값은 서버에서 한 번 더 막아야 500 오류가 나지 않습니다.

개념 정리: 리다이렉트와 PRG 패턴

저장에 성공하면 화면 이름 대신 "redirect:/"를 돌려줍니다. 그러면 서버는 302 응답과 함께 / 로 다시 가라고 알리고 브라우저는 GET / 를 새로 요청합니다. POST 다음에 Redirect, 그다음 GET으로 이어지는 이 흐름을 PRG(Post/Redirect/Get) 패턴이라고 부릅니다. 브라우저의 마지막 요청이 GET이 되므로 새로고침해도 저장 요청이 다시 나가지 않습니다.

실무에서는: 입력 검증 도구

이 책은 검증을 if 문 하나로 직접 씁니다. 실무에서는 spring-boot-starter-validation을 추가하고 @NotBlank, @Size 같은 어노테이션으로 검증 규칙을 선언하는 방식을 많이 씁니다. 규칙이 늘어나도 컨트롤러 코드가 길어지지 않고 오류 문구를 한곳에서 관리할 수 있습니다.

자주 하는 실수

  • POST 다음 redirect를 빠뜨림
    • 증상 저장 뒤 return "list"; 처럼 화면을 바로 돌려주면 새로고침할 때마다 같은 제목이 한 줄씩 더 저장됩니다.
    • 원인 브라우저는 새로고침할 때 마지막 요청을 다시 보냅니다. 마지막 요청이 POST이면 저장이 한 번 더 일어납니다. redirect를 하면 마지막 요청이 GET / 가 됩니다.
    • 고치는 법 성공하면 return "redirect:/"; 를 돌려줍니다.
  • 입력칸 name 오타
    • 증상 name="titl"처럼 쓰면 제목을 넣어도 값이 넘어오지 않아 400 오류가 납니다. 콘솔에 Required request parameter 'title' ... is not present가 찍힙니다.
    • 원인 @RequestParam은 기본이 필수입니다. 폼이 title이라는 이름으로 값을 보내지 않으면 필수 값이 없어 400으로 끝납니다.
    • 고치는 법 form.html의 name과 @RequestParam 매개변수 이름을 title로 맞춥니다.

안 될 때

  • 저장 버튼을 누르면 400 오류
    • 확인할 곳 form.html 입력칸의 name
    • 고치는 방법 name="title"로 맞춥니다.
  • /todos/new 가 500 오류이고 Error resolving template [form]이 보임
    • 확인할 곳 templates 폴더의 파일 이름
    • 고치는 방법 form.html로 맞춥니다.

댓글

아직 댓글이 없습니다.