作用:在多个请求之间共用数据,用于在session范围内存储对象。
使用方法,@SessionAttributes只能使用在类定义上,可以在控制器类上标注一个 @SessionAttributes,配置需要在session中存放的数据范围,Spring MVC将存放在model中对应的数据暂存到HttpSession 中。
一、@SessionAttributes属性
- value:用于指定存入的属性名称
- type:用于指定存入的数据类型。
- 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的属性添加到会话中。
二、使用案例
UserController.java
@RequestMapping("/user") //请求路径
@Controller
@SessionAttributes({"username", "password"}) //表示在session范围可以存储这两个变量名
public class UserController {
//将用户名、密码存入到Session范围内
@RequestMapping("/testPut")
public void testPut(Model model){
model.addAttribute("username", "zhangsan");
model.addAttribute("password", "123456");
System.out.println("将用户名、密码存入session");
}
//获取session范围内的对象
@RequestMapping("/testGet")
public void testGet(ModelMap modelMap){
System.out.println("获取用户、密码");
Object username = modelMap.get("username");
System.out.println(username);
Object password = modelMap.get("password");
System.out.println(password);
}
//清空session
@RequestMapping("/testClear")
public void testClear(SessionStatus sessionStatus){
sessionStatus.setComplete();//清空session
System.out.println("清空session");
}
}
依次执行
http://localhost/user/testPut
http://localhost/user/testGet
http://localhost/user/testClear
http://localhost/user/testGet