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.RequestMapping;
15 import org.springframework.web.bind.annotation.RequestMethod;
16 import org.springframework.web.bind.annotation.SessionAttributes;
17 import org.springframework.web.bind.support.SessionStatus;
18
19
20
21
22
23
24
25
26
27 @Controller
28 @RequestMapping("/owners/new")
29 @SessionAttributes(types = Owner.class)
30 public class AddOwnerForm {
31
32 private final Clinic clinic;
33
34
35 @Autowired
36 public AddOwnerForm(Clinic clinic) {
37 this.clinic = clinic;
38 }
39
40 @InitBinder
41 public void setAllowedFields(WebDataBinder dataBinder) {
42 dataBinder.setDisallowedFields("id");
43 }
44
45 @RequestMapping(method = RequestMethod.GET)
46 public String setupForm(Model model) {
47 Owner owner = new Owner();
48 model.addAttribute(owner);
49 return "owners/form";
50 }
51
52 @RequestMapping(method = RequestMethod.POST)
53 public String processSubmit(@ModelAttribute Owner owner, BindingResult result, SessionStatus status) {
54 new OwnerValidator().validate(owner, result);
55 if (result.hasErrors()) {
56 return "owners/form";
57 }
58 else {
59 this.clinic.storeOwner(owner);
60 status.setComplete();
61 return "redirect:/owners/" + owner.getId();
62 }
63 }
64
65 }