深入解读Spring Framework Web MVC(第八弹:@SessionAttributes的使用)

@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) { ... }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值