@SessionAttribute详解
如果多个请求之间需要共享数据,就可以使用@SessionAttribute。
配置的方法:
在控制器类上标注@SessionAttribute。
配置需要共享的数据范围。
这样,就可以将model中的属性同步到session中了。
注意:
默认情况,SpringMVC会将model的数据存放在request域中。
此时,当一个请求结束之后,数据将会失效。
因此,当数据需要跨页面使用时,就需要将数据存放到session中。
@SessionAttributes就是将指定的model中的数据拷贝到session中。
使用方法:
@SessionAttribute中,
value指定需要放入会话的属性名称。
type指定需要放入会话的属性类型。
@SessionAttributes(types=User.class)会将model中所有类型为 User的属性添加到会话中。
@SessionAttributes(value={“user1”, “user2”}) 会将model中属性名为user1和user2的属性添加到会话中。
@SessionAttributes(types={User.class, Dept.class}) 会将model中所有类型为 User和Dept的属性添加到会话中。
@SessionAttributes(value={“user1”,“user2”},types={Dept.class})会将model中属性名为user1和user2以及类型为Dept的属性添加到会话中。
@SessionAttributes(value={"names"},types={Integer.class}) @Controller public class Test { @RequestMapping("/test") public String test(Map<String,Object> map){ map.put("names", Arrays.asList("caoyc","zhh","cjx")); map.put("age", 18); return "hello"; } }
在前端取值:
${requestScope.names}
${sessionScope.names}