1
2 package org.springframework.samples.petclinic.web;
3
4 import java.util.Collection;
5
6 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.samples.petclinic.Clinic;
8 import org.springframework.samples.petclinic.Pet;
9 import org.springframework.samples.petclinic.PetType;
10 import org.springframework.samples.petclinic.validation.PetValidator;
11 import org.springframework.stereotype.Controller;
12 import org.springframework.ui.Model;
13 import org.springframework.validation.BindingResult;
14 import org.springframework.web.bind.WebDataBinder;
15 import org.springframework.web.bind.annotation.InitBinder;
16 import org.springframework.web.bind.annotation.ModelAttribute;
17 import org.springframework.web.bind.annotation.PathVariable;
18 import org.springframework.web.bind.annotation.RequestMapping;
19 import org.springframework.web.bind.annotation.RequestMethod;
20 import org.springframework.web.bind.annotation.SessionAttributes;
21 import org.springframework.web.bind.support.SessionStatus;
22
23
24
25
26
27
28
29
30 @Controller
31 @RequestMapping("/owners/*/pets/{petId}/edit")
32 @SessionAttributes("pet")
33 public class EditPetForm {
34
35 private final Clinic clinic;
36
37
38 @Autowired
39 public EditPetForm(Clinic clinic) {
40 this.clinic = clinic;
41 }
42
43 @ModelAttribute("types")
44 public Collection<PetType> populatePetTypes() {
45 return this.clinic.getPetTypes();
46 }
47
48 @InitBinder
49 public void setAllowedFields(WebDataBinder dataBinder) {
50 dataBinder.setDisallowedFields("id");
51 }
52
53
54
55
56
57
58
59
60 @RequestMapping(method = RequestMethod.GET)
61 public String setupForm(@PathVariable("petId") int petId, Model model) {
62 Pet pet = this.clinic.loadPet(petId);
63 model.addAttribute("pet", pet);
64 return "pets/form";
65 }
66
67
68
69
70
71
72
73
74
75 @RequestMapping(method = { RequestMethod.PUT, RequestMethod.POST })
76 public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) {
77 new PetValidator().validate(pet, result);
78 if (result.hasErrors()) {
79 return "pets/form";
80 }
81 else {
82 this.clinic.storePet(pet);
83 status.setComplete();
84 return "redirect:/owners/" + pet.getOwner().getId();
85 }
86 }
87
88
89
90
91
92
93
94 @RequestMapping(method = RequestMethod.DELETE)
95 public String deletePet(@PathVariable int petId) {
96 Pet pet = this.clinic.loadPet(petId);
97 this.clinic.deletePet(petId);
98 return "redirect:/owners/" + pet.getOwner().getId();
99 }
100
101 }