處理模型數據(3) - SessionAttribute

上面提到ModelAndView和Map對象。他們都是把對象保存在了request請求域裏面。那麼有沒有可能保存在Sesison裏?那就用到@SessionAttributes註解。

如果希望在多個請求之間公用一個模型屬性數據,則可以在控制器類上標註一個@SessionAttributes,SpringMVC將在模型中對應的屬性暫時保存到HttpSession中。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SessionAttributes {

	/**
	 * The names of session attributes in the model, to be stored in the
	 * session or some conversational storage.
	 * <p>Note: This indicates the model attribute names. The session attribute
	 * names may or may not match the model attribute names; applications should
	 * not rely on the session attribute names but rather operate on the model only.
	 */
	String[] value() default {};

	/**
	 * The types of session attributes in the model, to be stored in the
	 * session or some conversational storage. All model attributes of this
	 * type will be stored in the session, regardless of attribute name.
	 */
	Class<?>[] types() default {};

}
看到,這個只能標示在類上面,有兩個屬性,一個字符串數組, 這裏面可以放一些屬性名。第二個是一個class的數組,可以放屬性的類型;

做一個小示例:

@RequestMapping("/testSessionAttributes")
	public String getSessionAttributes(Map<String,Object> map){
		User user = new User("zs", "he39923", 23);
		map.put("user", user);
		return "success";
	}
如果是這樣來寫, 結果那麼肯定是放在了request域裏面。看一下結果


這個時候,這個user只是在請求域裏面,sesison裏面是沒有的,結果和預計的一樣,那怎麼給放到sesison裏面呢

@SessionAttributes({"user"})
public class HelloSpring {

在控制器類上面加上SessionAttributs註解,其value屬性爲我們在map中put的key一致。再看一下結果。

說明:當有SessionAttributs修飾後,會把map中的屬性,同時放在request域裏面和session域裏面。

SessionAttributs的參數有兩個,上面提到一個是value,是一個數組對象,可以放多個那個鍵的名字。還有一個就是type類型的class數組。來測驗一下

修改一下目標方法:

@RequestMapping("/testSessionAttributes")
	public String getSessionAttributes(Map<String,Object> map){
		User user = new User("zs", "he39923", 23);
		map.put("user", user);
		map.put("str", "spring SessionAttributes");
		map.put("num",123);
		return "success";
	}
map中放入了一個字符串和數字。

修改SessionAttributs註解。

@SessionAttributes(value={"user"},types={String.class,Integer.class})
加入了String.class和Integer.class,看一下執行結果;


看到結果所示: 得到了那個鍵爲user的對象,有得到了類型爲String,和integer類型的參數。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章