1
2 package org.springframework.samples.petclinic.web;
3
4 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.samples.petclinic.Clinic;
6 import org.springframework.samples.petclinic.Owner;
7 import org.springframework.samples.petclinic.validation.OwnerValidator;
8 import org.springframework.stereotype.Controller;
9 import org.springframework.ui.Model;
10 import org.springframework.validation.BindingResult;
11 import org.springframework.web.bind.WebDataBinder;
12 import org.springframework.web.bind.annotation.InitBinder;
13 import org.springframework.web.bind.annotation.ModelAttribute;
14 import org.springframework.web.bind.annotation.PathVariable;
15 import org.springframework.web.bind.annotation.RequestMapping;
16 import org.springframework.web.bind.annotation.RequestMethod;
17 import org.springframework.web.bind.annotation.SessionAttributes;
18 import org.springframework.web.bind.support.SessionStatus;
19
20
21
22
23
24
25
26
27 @org.springframework.stereotype.Controller
28 @RequestMapping("/owners/{ownerId}/edit")
29 @SessionAttributes(types = Owner.class)
30 public class EditOwnerForm {
31
32 private final Clinic clinic;
33
34
35 @Autowired
36 public EditOwnerForm(Clinic clinic) {
37 this.clinic = clinic;
38 }
39
40 @InitBinder
41 public void setAllowedFields(WebDataBinder dataBinder) {
42 dataBinder.setDisallowedFields("id");
43 }
44
45
46
47
48
49
50
51
52 @RequestMapping(method = RequestMethod.GET)
53 public String setupForm(@PathVariable("ownerId") int ownerId, Model model) {
54 Owner owner = this.clinic.loadOwner(ownerId);
55 model.addAttribute(owner);
56 return "owners/form";
57 }
58
59
60
61
62
63
64
65
66
67 @RequestMapping(method = RequestMethod.PUT)
68 public String processSubmit(@ModelAttribute Owner owner, BindingResult result, SessionStatus status) {
69 new OwnerValidator().validate(owner, result);
70 if (result.hasErrors()) {
71 return "owners/form";
72 }
73 else {
74 this.clinic.storeOwner(owner);
75 status.setComplete();
76 return "redirect:/owners/" + owner.getId();
77 }
78 }
79
80 }