TodoController로 넘어온 요청을 저장하기 위해 TodoService를 개선해보겠습니다.
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Service
public class TodoService {
private static List<Todo> todos = new ArrayList<>();
private static int todosCount = 0;
static {
todos.add(new Todo(++todosCount, "test1", "Learn AWS",
LocalDate.now().plusYears(1), false));
todos.add(new Todo(++todosCount, "test1", "Learn DevOps",
LocalDate.now().plusYears(2), false));
todos.add(new Todo(++todosCount, "test1", "Learn Full Stack Development",
LocalDate.now().plusYears(3), false));
}
public List<Todo> findByUsername(String username) {
return todos;
}
public void addTodo(String username, String description, LocalDate targetDate, boolean done) {
Todo todo = new Todo(++todosCount, username, description, targetDate, done);
todos.add(todo);
}
}
addTodo() : 요청으로 받아온 사용자 이름, 설명, 목표 날짜, 완료 여부를 새로운 Todo 인스턴스로 저장하고 List에 추가합니다.
TodoController에서 name속성을 사용하기 위해 ModelMap을 추가합니다.
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import java.time.LocalDate;
import java.util.List;
@Controller
@SessionAttributes("name")
public class TodoController {
private TodoService todoService;
public TodoController(TodoService todoService) {
this.todoService = todoService;
}
//list-todos
@RequestMapping("/list-todos")
public String listAllTodos(ModelMap model) {
List<Todo> todos = todoService.findByUsername("test1");
model.addAttribute("todos", todos);
return "listTodos";
}
@RequestMapping(value = "/add-todo", method = RequestMethod.GET)
public String showNewTodoPage() {
return "todo";
}
@RequestMapping(value = "/add-todo", method = RequestMethod.POST)
public String addNewTodo(@RequestParam String description, ModelMap model) {
String username = (String) model.get("name");
todoService.addTodo(username, description, LocalDate.now().plusYears(1), false);
return "redirect:list-todos";
}
}