AddPetForm.java 2.3 KB
Newer Older
1

A
Arjen Poutsma 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
package org.springframework.samples.petclinic.web;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.Owner;
import org.springframework.samples.petclinic.Pet;
import org.springframework.samples.petclinic.PetType;
import org.springframework.samples.petclinic.validation.PetValidator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
15 16
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
A
Arjen Poutsma 已提交
17
import org.springframework.web.bind.annotation.ModelAttribute;
18
import org.springframework.web.bind.annotation.PathVariable;
A
Arjen Poutsma 已提交
19 20 21 22 23 24 25 26
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

/**
 * JavaBean form controller that is used to add a new <code>Pet</code> to the
 * system.
27
 * 
A
Arjen Poutsma 已提交
28 29
 * @author Juergen Hoeller
 * @author Ken Krebs
A
Arjen Poutsma 已提交
30
 * @author Arjen Poutsma
A
Arjen Poutsma 已提交
31 32
 */
@Controller
A
Arjen Poutsma 已提交
33
@RequestMapping("/owners/{ownerId}/pets/new")
A
Arjen Poutsma 已提交
34 35 36 37 38
@SessionAttributes("pet")
public class AddPetForm {

	private final Clinic clinic;

39

A
Arjen Poutsma 已提交
40 41 42 43 44 45 46 47 48 49
	@Autowired
	public AddPetForm(Clinic clinic) {
		this.clinic = clinic;
	}

	@ModelAttribute("types")
	public Collection<PetType> populatePetTypes() {
		return this.clinic.getPetTypes();
	}

50 51
	@InitBinder
	public void setAllowedFields(WebDataBinder dataBinder) {
52
		dataBinder.setDisallowedFields(new String[] {"id"});
53
	}
A
Arjen Poutsma 已提交
54

55
	@RequestMapping(method = RequestMethod.GET)
A
Arjen Poutsma 已提交
56
	public String setupForm(@PathVariable("ownerId") int ownerId, Model model) {
A
Arjen Poutsma 已提交
57 58 59 60
		Owner owner = this.clinic.loadOwner(ownerId);
		Pet pet = new Pet();
		owner.addPet(pet);
		model.addAttribute("pet", pet);
61
		return "pets/form";
A
Arjen Poutsma 已提交
62 63 64 65 66 67
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) {
		new PetValidator().validate(pet, result);
		if (result.hasErrors()) {
68
			return "pets/form";
A
Arjen Poutsma 已提交
69 70 71 72
		}
		else {
			this.clinic.storePet(pet);
			status.setComplete();
73
			return "redirect:/owners/" + pet.getOwner().getId();
A
Arjen Poutsma 已提交
74 75 76 77
		}
	}

}