本文研究的主要春天是学习之@SessionAttributes的相关内容,具体如下。
一、@ModelAttribute
在默认情况下,ModelMap中的属性作用域是请求级别是,也就是说,当本次请求结束后,ModelMap中的属性将销毁。如果希望在多个请求中共享ModelMap中的属性,必须将其属性转存到会话中,这样ModelMap的属性才可以被跨请求访问。
<强> 强>春季允许我们有选择地指定ModelMap中的哪些属性需要转存到会话中,以便下一个请求属对应的ModelMap的属性列表中还能访问到这些属性。这一功能是通过类定义处标注<代码> @SessionAttributes 代码>注解来实现的。
<强>使模型对象的特定属性具有会话范围的作用域强>
包com.baobaotao.web; … 进口org.springframework.ui.ModelMap; 进口org.springframework.web.bind.annotation.SessionAttributes; @ controller @RequestMapping ("/bbtForum.do”) @SessionAttributes (“currUser”)//①将ModelMap中属性名为currUser的属性,放到会话属性列表中,以便这个属性可以跨请求访问 公开课BbtForumController { … @RequestMapping (params=胺椒?listBoardTopic”) 公共字符串listBoardTopic (@RequestParam (" id ") int topicId用户用户, ModelMap模型){ bbtForumService.getBoardTopics (topicId); system . out。println (“topicId:“+ topicId); system . out。println(“用户:”+用户); model.addAttribute (“currUser”、用户);//②向ModelMap中添加一个属性 返回“listTopic”; } }
我们在②处添加了一个ModelMap属性,其属性名为currUser,而①处通过<代码> @SessionAttributes 代码>注解将ModelMap中名为currUser的属性放置到会话中,所以我们不但可以在listBoardTopic()请求所对应的JSP视图页面中通过<代码> request.getAttribute (currUser) 代码>和<代码> session.getAttribute (currUser) 代码>获取用户对象,还可以在下一个请求所对应的JSP视图页面中通过<代码> session.getAttribute (currUser) 代码>或<代码> ModelMap #得到(currUser) 代码>访问到这个属性。
这里我们仅将一个ModelMap的属性放入会话中,其实<代码> @SessionAttributes 代码>允许指定多个属性。你可以通过字符串数组的方式指定多个属性,如<代码> @SessionAttributes ({“attr1”、“attr2”})> 代码。此外<代码>,@SessionAttributes> 代码还可以通过属性类型指定要会话化的ModelMap属性,如<代码> @SessionAttributes(类型=User.class)> 代码,当然也可以指定多个类,如<代码> @SessionAttributes(类型={User.class, Dept.class})> 代码,还可以联合使用属性名和属性类型指定:<代码> @SessionAttributes(类型={User.class, Dept.class},价值=https://www.yisu.com/zixun/{“attr1”、“attr2”}) 代码>。
二,@ModelAttribute
我们可以在需要访问会话属性的控制器上加上<代码> @SessionAttributes> 代码,然后在行动需要的用户参数上加上<代码> @ModelAttribute> 代码,并保证两者的属性名称一致.SpringMVC就会自动将<代码> @SessionAttributes 代码>定义的属性注入到ModelMap对象,在设置行动的参数列表时,去ModelMap中取到这样的对象,再添加到参数列表。只要我们不去调用SessionStatus的<代码> setComplete() 代码>方法,这个对象就会一直保留在会话中,从而实现会话信息的共享。
@ controller @SessionAttributes (“currentUser”) & lt;/span> 公开课GreetingController { @RequestMapping 公共空你好(@ModelAttribute (currentUser)用户用户){//user.sayHello () } }
总结
以上就是本文关于春季学习之@SessionAttributes实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!