@SessionAttributes可以让我们指定把Model中的哪些数据放到Session中,也就是说,使模型对象的特定属性具有 Session范围的作用域。例如:
@Controller
@RequestMapping("/pets")
@SessionAttributes("pet")
public class EditPetForm {
// ...
@RequestMapping(method = RequestMethod.GET)
public String setupForm(int petId, ModelMap model) {
Pet pet = this.clinic.loadPet(petId);
model.addAttribute("pet", pet);
return "petForm";
}
// ...
}
上例中,如果往模型中添加了pet,如:model.addAttribute("pet", pet);
,那么这个pet就会放到Session中去。
我们可以在需要访问Session属性的controller上加上@SessionAttributes,然后在需要用的Pet参数上加上@ModelAttribute,并保证两者的属性名称一致,SpringMVC就会自动将@SessionAttributes 定义的属性放到ModelMap对象中,只要不调用SessionStatus的setComplete()方法,这个对象就会一直保留在 Session 中。如:
@RequestMapping
public String processSubmit(@ModelAttribute("pet") Pet pet) { ... }