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.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.RequestMapping;
15  import org.springframework.web.bind.annotation.RequestMethod;
16  
17  /**
18   * JavaBean Form controller that is used to search for <code>Owner</code>s by
19   * last name.
20   * 
21   * @author Juergen Hoeller
22   * @author Ken Krebs
23   * @author Arjen Poutsma
24   */
25  @Controller
26  @RequestMapping(method = RequestMethod.GET)
27  public class FindOwnersForm {
28  
29  	private final Clinic clinic;
30  
31  
32  	@Autowired
33  	public FindOwnersForm(Clinic clinic) {
34  		this.clinic = clinic;
35  	}
36  
37  	@InitBinder
38  	public void setAllowedFields(WebDataBinder dataBinder) {
39  		dataBinder.setDisallowedFields("id");
40  	}
41  
42  	@RequestMapping(value = "/owners/search")
43  	public String setupForm(Model model) {
44  		model.addAttribute("owner", new Owner());
45  		return "owners/search";
46  	}
47  
48  	@RequestMapping(value = "/owners")
49  	public String processSubmit(Owner owner, BindingResult result, Model model) {
50  
51  		// allow parameterless GET request for /owners to return all records
52  		if (owner.getLastName() == null) {
53  			owner.setLastName(""); // empty string signifies broadest possible search
54  		}
55  
56  		// find owners by last name
57  		Collection<Owner> results = this.clinic.findOwners(owner.getLastName());
58  		if (results.size() < 1) {
59  			// no owners found
60  			result.rejectValue("lastName", "notFound", "not found");
61  			return "owners/search";
62  		}
63  		if (results.size() > 1) {
64  			// multiple owners found
65  			model.addAttribute("selections", results);
66  			return "owners/list";
67  		}
68  		else {
69  			// 1 owner found
70  			owner = results.iterator().next();
71  			return "redirect:/owners/" + owner.getId();
72  		}
73  	}
74  
75  }