AddPetForm.java
上传用户:dezhong
上传日期:2022-08-10
资源大小:167k
文件大小:2k
源码类别:

Java编程

开发平台:

Java

  1. package org.springframework.samples.petclinic.web;
  2. import java.util.Collection;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.samples.petclinic.Clinic;
  5. import org.springframework.samples.petclinic.Owner;
  6. import org.springframework.samples.petclinic.Pet;
  7. import org.springframework.samples.petclinic.PetType;
  8. import org.springframework.samples.petclinic.validation.PetValidator;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.ui.Model;
  11. import org.springframework.validation.BindingResult;
  12. import org.springframework.web.bind.annotation.ModelAttribute;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RequestMethod;
  15. import org.springframework.web.bind.annotation.RequestParam;
  16. import org.springframework.web.bind.annotation.SessionAttributes;
  17. import org.springframework.web.bind.support.SessionStatus;
  18. /**
  19.  * JavaBean form controller that is used to add a new <code>Pet</code> to the
  20.  * system.
  21.  *
  22.  * @author Juergen Hoeller
  23.  * @author Ken Krebs
  24.  */
  25. @Controller
  26. @RequestMapping("/addPet.do")
  27. @SessionAttributes("pet")
  28. public class AddPetForm {
  29. private final Clinic clinic;
  30. @Autowired
  31. public AddPetForm(Clinic clinic) {
  32. this.clinic = clinic;
  33. }
  34. @ModelAttribute("types")
  35. public Collection<PetType> populatePetTypes() {
  36. return this.clinic.getPetTypes();
  37. }
  38. @RequestMapping(method = RequestMethod.GET)
  39. public String setupForm(@RequestParam("ownerId") int ownerId, Model model) {
  40. Owner owner = this.clinic.loadOwner(ownerId);
  41. Pet pet = new Pet();
  42. owner.addPet(pet);
  43. model.addAttribute("pet", pet);
  44. return "petForm";
  45. }
  46. @RequestMapping(method = RequestMethod.POST)
  47. public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) {
  48. new PetValidator().validate(pet, result);
  49. if (result.hasErrors()) {
  50. return "petForm";
  51. }
  52. else {
  53. this.clinic.storePet(pet);
  54. status.setComplete();
  55. return "redirect:owner.do?ownerId=" + pet.getOwner().getId();
  56. }
  57. }
  58. }