|
| 1 | +package com.baeldung.sessionattrs; |
| 2 | + |
| 3 | +import java.time.LocalDateTime; |
| 4 | + |
| 5 | +import org.springframework.stereotype.Controller; |
| 6 | +import org.springframework.ui.Model; |
| 7 | +import org.springframework.web.bind.annotation.GetMapping; |
| 8 | +import org.springframework.web.bind.annotation.ModelAttribute; |
| 9 | +import org.springframework.web.bind.annotation.PostMapping; |
| 10 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 11 | +import org.springframework.web.bind.annotation.SessionAttributes; |
| 12 | +import org.springframework.web.servlet.mvc.support.RedirectAttributes; |
| 13 | +import org.springframework.web.servlet.view.RedirectView; |
| 14 | + |
| 15 | +@Controller |
| 16 | +@RequestMapping("/sessionattributes") |
| 17 | +@SessionAttributes("todos") |
| 18 | +public class TodoControllerWithSessionAttributes { |
| 19 | + |
| 20 | + @GetMapping("/form") |
| 21 | + public String showForm( |
| 22 | + Model model, |
| 23 | + @ModelAttribute("todos") TodoList todos) { |
| 24 | + if (!todos.isEmpty()) { |
| 25 | + model.addAttribute("todo", todos.peekLast()); |
| 26 | + } else { |
| 27 | + model.addAttribute("todo", new TodoItem()); |
| 28 | + } |
| 29 | + return "sessionattributesform"; |
| 30 | + } |
| 31 | + |
| 32 | + @PostMapping("/form") |
| 33 | + public RedirectView create( |
| 34 | + @ModelAttribute TodoItem todo, |
| 35 | + @ModelAttribute("todos") TodoList todos, |
| 36 | + RedirectAttributes attributes) { |
| 37 | + todo.setCreateDate(LocalDateTime.now()); |
| 38 | + todos.add(todo); |
| 39 | + attributes.addFlashAttribute("todos", todos); |
| 40 | + return new RedirectView("/sessionattributes/todos.html"); |
| 41 | + } |
| 42 | + |
| 43 | + @GetMapping("/todos.html") |
| 44 | + public String list( |
| 45 | + Model model, |
| 46 | + @ModelAttribute("todos") TodoList todos) { |
| 47 | + model.addAttribute("todos", todos); |
| 48 | + return "sessionattributestodos"; |
| 49 | + } |
| 50 | + |
| 51 | + @ModelAttribute("todos") |
| 52 | + public TodoList todos() { |
| 53 | + return new TodoList(); |
| 54 | + } |
| 55 | +} |
0 commit comments