欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

spring學(xué)習(xí)之@SessionAttributes實(shí)例解析

 更新時間:2018年02月10日 11:48:41   作者:你的承諾早已氾黃  
這篇文章主要介紹了spring學(xué)習(xí)之@SessionAttributes實(shí)例解析,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下

本文研究的主要是spring學(xué)習(xí)之@SessionAttributes的相關(guān)內(nèi)容,具體如下。

一、@ModelAttribute

在默認(rèn)情況下,ModelMap 中的屬性作用域是 request 級別是,也就是說,當(dāng)本次請求結(jié)束后,ModelMap中的屬性將銷毀。如果希望在多個請求中共享 ModelMap 中的屬性,必須將其屬性轉(zhuǎn)存到 session 中,這樣ModelMap 的屬性才可以被跨請求訪問。

spring 允許我們有選擇地指定 ModelMap 中的哪些屬性需要轉(zhuǎn)存到 session 中,以便下一個請求屬對應(yīng)的 ModelMap 的屬性列表中還能訪問到這些屬性。這一功能是通過類定義處標(biāo)注 @SessionAttributes 注解來實(shí)現(xiàn)的。

使模型對象的特定屬性具有 Session 范圍的作用域

package com.baobaotao.web;
…  
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.SessionAttributes;
@Controller  
@RequestMapping("/bbtForum.do")  
@SessionAttributes("currUser")  
//①將ModelMap中屬性名為currUser的屬性 ,放到Session屬性列表中,以便這個屬性可以跨請求訪問  
public class BbtForumController {
	…  
	  @RequestMapping(params = "method=listBoardTopic")  
	  public String listBoardTopic(@RequestParam("id")int topicId, User user,  
	ModelMap model) {
		bbtForumService.getBoardTopics(topicId);
		System.out.println("topicId:" + topicId);
		System.out.println("user:" + user);
		model.addAttribute("currUser",user);
		//②向ModelMap中添加一個屬性  
		return "listTopic";
	}
}

我們在 ② 處添加了一個 ModelMap 屬性,其屬性名為 currUser,而 ① 處通過 @SessionAttributes 注解將 ModelMap 中名為 currUser 的屬性放置到 Session 中,所以我們不但可以在 listBoardTopic() 請求所對應(yīng)的 JSP 視圖頁面中通過 request.getAttribute(“currUser”) session.getAttribute(“currUser”) 獲取 user 對象,還可以在下一個請求所對應(yīng)的 JSP 視圖頁面中通過 session.getAttribute(“currUser”) ModelMap#get(“currUser”) 訪問到這個屬性。

這里我們僅將一個 ModelMap 的屬性放入 Session 中,其實(shí) @SessionAttributes 允許指定多個屬性。你可以通過字符串?dāng)?shù)組的方式指定多個屬性,如 @SessionAttributes({“attr1”,”attr2”}) 。此外,@SessionAttributes還可以通過屬性類型指定要 session 化的 ModelMap 屬性,如 @SessionAttributes(types = User.class) ,當(dāng)然也可以指定多個類,如 @SessionAttributes(types = {User.class,Dept.class}) ,還可以聯(lián)合使用屬性名和屬性類型指定: @SessionAttributes(types = {User.class,Dept.class},value={“attr1”,”attr2”})

二、@ModelAttribute

我們可以在需要訪問 Session 屬性的 controller 上加上 @SessionAttributes,然后在 action 需要的 User 參數(shù)上加上 @ModelAttribute,并保證兩者的屬性名稱一致。SpringMVC 就會自動將 @SessionAttributes 定義的屬性注入到 ModelMap 對象,在 setup action 的參數(shù)列表時,去 ModelMap 中取到這樣的對象,再添加到參數(shù)列表。只要我們不去調(diào)用 SessionStatus 的 setComplete() 方法,這個對象就會一直保留在 Session 中,從而實(shí)現(xiàn) Session 信息的共享。

@Controller  
@SessionAttributes("currentUser")</span>  
public class GreetingController{
	@RequestMapping  
	public void hello(@ModelAttribute("currentUser")User user){
		//user.sayHello()
	}
}

總結(jié)

以上就是本文關(guān)于spring學(xué)習(xí)之@SessionAttributes實(shí)例解析的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

相關(guān)文章

最新評論