View Javadoc

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.Owner;
9   import org.springframework.samples.petclinic.Pet;
10  import org.springframework.samples.petclinic.PetType;
11  import org.springframework.samples.petclinic.validation.PetValidator;
12  import org.springframework.stereotype.Controller;
13  import org.springframework.ui.Model;
14  import org.springframework.validation.BindingResult;
15  import org.springframework.web.bind.WebDataBinder;
16  import org.springframework.web.bind.annotation.InitBinder;
17  import org.springframework.web.bind.annotation.ModelAttribute;
18  import org.springframework.web.bind.annotation.PathVariable;
19  import org.springframework.web.bind.annotation.RequestMapping;
20  import org.springframework.web.bind.annotation.RequestMethod;
21  import org.springframework.web.bind.annotation.SessionAttributes;
22  import org.springframework.web.bind.support.SessionStatus;
23  
24  /**
25   * JavaBean form controller that is used to add a new <code>Pet</code> to the
26   * system.
27   * 
28   * @author Juergen Hoeller
29   * @author Ken Krebs
30   * @author Arjen Poutsma
31   */
32  @Controller
33  @RequestMapping("/owners/{ownerId}/pets/new")
34  @SessionAttributes("pet")
35  public class AddPetForm {
36  
37  	private final Clinic clinic;
38  
39  
40  	@Autowired
41  	public AddPetForm(Clinic clinic) {
42  		this.clinic = clinic;
43  	}
44  
45  	@ModelAttribute("types")
46  	public Collection<PetType> populatePetTypes() {
47  		return this.clinic.getPetTypes();
48  	}
49  
50  	@InitBinder
51  	public void setAllowedFields(WebDataBinder dataBinder) {
52  		dataBinder.setDisallowedFields("id");
53  	}
54  
55  	@RequestMapping(method = RequestMethod.GET)
56  	public String setupForm(@PathVariable("ownerId") int ownerId, Model model) {
57  		Owner owner = this.clinic.loadOwner(ownerId);
58  		Pet pet = new Pet();
59  		owner.addPet(pet);
60  		model.addAttribute("pet", pet);
61  		return "pets/form";
62  	}
63  
64  	@RequestMapping(method = RequestMethod.POST)
65  	public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) {
66  		new PetValidator().validate(pet, result);
67  		if (result.hasErrors()) {
68  			return "pets/form";
69  		}
70  		else {
71  			this.clinic.storePet(pet);
72  			status.setComplete();
73  			return "redirect:/owners/" + pet.getOwner().getId();
74  		}
75  	}
76  
77  }