Exercise Solutions: Edit Model Classes¶
Create the two handler methods listed below in
EventController
. We’ll add code to these in a moment, so just put the method outline in place for now.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
@Controller @RequestMapping("events") public class EventController { @GetMapping public String displayAllEvents(Model model) { model.addAttribute("title", "All Events"); model.addAttribute("events", EventData.getAll()); return "events/index"; } @GetMapping("create") public String displayCreateEventForm(Model model) { model.addAttribute("title", "Create Event"); return "events/create"; } @PostMapping("create") public String processCreateEventForm(@ModelAttribute Event newEvent) { EventData.add(newEvent); return "redirect:"; } @GetMapping("delete") public String displayDeleteEventForm(Model model) { model.addAttribute("title", "Delete Events"); model.addAttribute("events", EventData.getAll()); return "events/delete"; } @PostMapping("delete") public String processDeleteEventsForm(@RequestParam(required = false) int[] eventIds) { if (eventIds != null) { for (int id : eventIds) { EventData.remove(id); } } return "redirect:"; } @GetMapping("edit/{eventId}") public String displayEditForm(Model model, @PathVariable int eventId){ } @PostMapping("edit") public String processEditForm(int eventId, String name, String description) { } }
Back in the
displayEditForm
handler, round out the controller method.@GetMapping("edit/{eventId}") public String displayEditForm(Model model, @PathVariable int eventId){ Event eventToEdit = EventData.getById(eventId); model.addAttribute("event", eventToEdit); String title = "Edit Event " + eventToEdit.getName() + " (id=" + eventToEdit.getId() + ")"; model.addAttribute("title", title ); return "events/edit"; }
In
processEditForm
,@PostMapping("edit") public String processEditForm(int eventId, String name, String description) { Event eventToEdit = EventData.getById(eventId); eventToEdit.setName(name); eventToEdit.setDescription(description); return "redirect:"; }