上面提到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类型的参数。