-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTodoController.java
More file actions
68 lines (47 loc) · 1.9 KB
/
TodoController.java
File metadata and controls
68 lines (47 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.example.spring_todo.Controller;
import com.example.spring_todo.Model.Todo;
import com.example.spring_todo.Service.TodoService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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;
@Controller
public class TodoController {
private final TodoService todoService;
@Autowired
public TodoController(TodoService todoService) {
this.todoService = todoService;
}
@GetMapping("/")
public String listTodos(Model model) {
model.addAttribute("todos", todoService.findAll()); // Changed to "todos" for list
if(!model.containsAttribute("todo")) {
model.addAttribute("todo", new Todo()); // "todo" for the form
}
return "index";
}
@PostMapping("/add")
public String addTodo(@Valid Todo todo, BindingResult result, Model model) {
if(result.hasErrors()) {
model.addAttribute("todos", todoService.findAll());
return "index";
}
todoService.save(todo);
return "redirect:/";
}
@PostMapping("/update/{id}")
public String updateTodo(@PathVariable Long id, @RequestParam String title, @RequestParam(defaultValue = "false") boolean completed) {
todoService.update(id, title, completed);
return "redirect:/";
}
@PostMapping("/delete/{id}")
public String deleteTodo(@PathVariable Long id) {
todoService.deleteById(id);
return "redirect:/";
}
}