[Spring Boot] TODO - 토이 프로젝트

Hyeonseok Jeong·2023년 8월 31일
0

Spring Boot

목록 보기
1/1

오늘은 Spring Boot를 공부하면서 간단하게 TODO를 만들어봤다

복습을 위해 간단하게 만들어본 TODO 프젝이라 그런지 막상 만들고 난 후에 추가하고 싶은 기능이 있었지만 아직 Spring 시큐리티 부분은 미숙하여 좀더 공부 후 CRUD 게시판 프로젝트를 해볼 예정이다.

구현부분

  • 리스트 출력
  • TODO 생성
  • TODO 삭제
  • TODO 체크

코드

  • Controller
package com.toy.todolist.todo;


import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequiredArgsConstructor
@RequestMapping("/todo")
@Controller
public class TodoController {

    private final TodoService todoService;

    @GetMapping("/list")
    public String list (Model model) {
        List<Todo> todoList = this.todoService.getList();
        model.addAttribute("todoList", todoList);
        return "todo_list";
    }

    @PostMapping("/reg")
    public String reg (@RequestParam String content) {
        this.todoService.create(content);
        return "redirect:/todo/list";
    }

    @PostMapping("/delete/{id}")
    public String delete (@PathVariable("id") Integer id) {
        this.todoService.delete(id);
        return "redirect:/todo/list";
    }

    @PostMapping("/check/{id}")
    public String check(@PathVariable("id") Integer id, @RequestParam String check) {
        if(check.equals("yet")) {
            this.todoService.check(id, true);
            return "redirect:/todo/list";
        }else {
            this.todoService.check(id, false);
            return "redirect:/todo/list";
        }
    }

    @GetMapping("/modify/{id}")
    public String modify(Model model, @PathVariable("id") Integer id) {
        Todo todoContent = this.todoService.getTodo(id);
        model.addAttribute("todoContent", todoContent);
        return "todo_modify";
    }

}
  • Service
package com.toy.todolist.todo;


import com.toy.todolist.DataNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.swing.text.html.Option;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RequiredArgsConstructor
@Service
public class TodoService {

    private final TodoRepository todoRepository;

    public Todo getTodo(Integer id) {
        Optional<Todo> _todo = this.todoRepository.findById(id);
        if(_todo.isPresent()) {
            Todo todo = _todo.get();
            return todo;
        } else {
            throw new DataNotFoundException("question not found");
        }
    }

    public List<Todo> getList() {
        List<Todo> todoList = this.todoRepository.findAll();
        return todoList;
    }

    public void create(String content) {
        Todo todo = new Todo();
        todo.setContent(content);
        todo.setRegDate(LocalDateTime.now());
        todo.setFinished(false);
        this.todoRepository.save(todo);
    }

    public void check(Integer id, boolean finished) {
        Optional<Todo> qt = this.todoRepository.findById(id);
        if(qt.isPresent()) {
            Todo todo = qt.get();
            todo.setFinished(finished);
            this.todoRepository.save(todo);
        }else {
            throw new DataNotFoundException("question not found");
        }
    }

    public void delete(Integer id) {
        Optional<Todo> _todo = this.todoRepository.findById(id);
        if(_todo.isPresent()) {
            Todo todo = _todo.get();
            this.todoRepository.delete(todo);
        }else {
            throw new DataNotFoundException("question not found");
        }
    }

}
  • Error
package com.toy.todolist;


import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "entity not found")
public class DataNotFoundException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    public DataNotFoundException(String message) {
        super(message);
    }
}
  • Entity
package com.toy.todolist.todo;


import jakarta.persistence.*;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Getter
@Setter
@Entity
public class Todo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(length = 200)
    private String content;

    private LocalDateTime regDate;

    @Column(nullable = false)
    private boolean finished;


}
  • View
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8" />
    <title>반갑다</title>
    <link rel="stylesheet" type="text/css" th:href="@{/style.css}">
</head>
<body>
<div class="contain">
<div class="todoInput">
    <form action="/todo/reg" method="post" class="contentForm">
        <input class="content" type="text" name="content" />
        <input class="regBtn" type="submit" name="reg" value="등록" />
    </form>
</div>
<div class="todoContent">
    <table>
        <tbody th:each="todo, loop : ${todoList}">
        <tr>
            <td class="numTd" th:text="${loop.index + 1}"></td>
            <td class="cntTd" th:text="${todo.content}"></td>
            <td class="chTd" th:if="${todo.finished}">
                <form th:action="@{|/todo/check/${todo.id}|}" method="post">
                    <input class="btnSt" type="submit" name="check" value="complete" />
                </form>
            </td>
            <td class="chTd" th:unless="${todo.finished}">
                <form th:action="@{|/todo/check/${todo.id}|}" method="post">
                    <input class="btnSt" type="submit" name="check" value="yet" />
                </form>
            </td>
            <td class="delTd">
                <form th:action="@{|/todo/delete/${todo.id}|}" method="post">
                    <input class="btnSt" type="submit" name="delete" value="삭제" />
                </form>
            </td>
        </tr>
        </tbody>
    </table>
</div>
</div>
</body>
</html>

설명

이번 토이프젝은 스프링부트 와 타입리프에 익숙해지기 위해 간단하게 작업해본 놀이다.

설명은 컨트롤단에서 보여지는 출력, 생성, 삭제, 체크 기능을 만들어 보았고 이번에 해보고싶었던 Error 처리를 위해 따로 DataNotFoundException을 만들어 삭제와 체크를 할경우 Entity가 존재하지 않을경우 에러를 던져주어 에러화면에 보여지는 메세지를 만드는 작업을 해보았다.

사진

마무리

어서 스프링 시큐리티를 배워 로그인과 회원가입 부분을 구성해보고싶은 마음이 크다 그리고 글을 적으면서 생각해보니 Update부분을 안한게 보였다;; 게시판 프젝을 진행할때는 수정하는 부분을 잘 체크해야겠다.

profile
풀스텍 개발자

0개의 댓글