@SessionAttributes
@SessionAttributes
- 使用时需在控制器类上标注一个@SessionAttributes注解,SpringMVC会将对应的属性存储到Session作用域中
- @SessionAttributes可以通过属性名和属性的对象类型来指定所有共享作用域中的符合要求的数据放在Session作用域中
- 语法:
- @SessionAttributes(types=User.class) :将隐含模型中所有类型为User属性添加到Session中。
- @SessionAttributes(value={"user1","user2"}):将user1对象和user2放入Session中。
- @SessionAttributes(types={User.class,Dept.class})
- @SessionAttributes(value={"user1","user2"},types={Dept.class}):
使用实例:
//将map中的user数据注入session作用域
@SessionAttributes("user")
@Controller
public class ControllerTest {
@RequestMapping("/test")
public String test(Map<String,Object> map){
UserVO userVO = new UserVO(1,"风烟",18);
//将userVO对象加入map
map.put("user",userVO);
return "test";
}
}
前台jsp页面获取数据,以下request session作用域都获取到了数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
hello springmvc<br />
姓名:${sessionScope.user.name} 年龄:${sessionScope.user.age}<br />
姓名:${requestScope.user.name}
</body>
</html>
- 这里我猜测方法中的map对象就等同于request作用域,所以将数据加入map就是加入request作用域中,然后@SessionAttributes再从中匹配数据到Session作用域中。
仅供参考