View Javadoc

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