spring MVC session传递model

来源:互联网 发布:js禁止浏览器刷新按钮 编辑:程序博客网 时间:2024/05/18 00:04

通过spring MVC提供的@SessionAttributes 可以通过将model存在session实现跨controller的model传递,实现方法:

在存和取的controller类上都要添加注解,例如:

@Controller@RequestMapping("/myController/demo1")@SessionAttributes("demoModel")public class Demo1Controller {.......//在某个处理方法中调用model.addAttribute("demoModel", demoModel);}

在取的controller中同样需要注解,例如:

@Controller@RequestMapping("/myController/demo2")@SessionAttributes("demoModel")public class Demo2Controller {.......//在某个处理方法参数中声明@ModelAttribute("demoModel") DemoModel demoModel}


值得注意的是如果采用了validator, 比如Demo1Controller中采用了针对xxModel的validator, 那么spring MVC会报错,类似target invalid,也就是说spring MVC对session中的model也进行了验证,尽管这个model并不是要验证的xxModel,解决方法是通过注解显式指明要验证的model,例如:

@InitBinder("xxModel")    public void initBinder(WebDataBinder binder) {        binder.setValidator(new xxModelValidator());    }


原创粉丝点击