a、该注解只能应用在类中;
b、该注解用于将Map、ModelMap、Model或ModelAndView中的数据暂存到HttpSession中以使其可以在多个请求之间共用数据,如下代码:
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<br>
<a href="./userinfo/userInfoView.do">链接</a>
<a href="./userinfo/show.do">显示</a>
</body>
</html>
UserInfoController.java
package com.jd.userinfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.jd.vo.UserInfo;
@Controller
@SessionAttributes("userInfo")
public class UserInfoController {
@RequestMapping("userinfo/userInfoView.do")
public String view(Model model) {
UserInfo userInfo = new UserInfo();
userInfo.setName("Speike");
userInfo.setMobile("333");
model.addAttribute("userInfo", userInfo);
return "userinfo/userInfoView";
}
@RequestMapping("userinfo/show.do")
public String show() {
return "userinfo/show";
}
}
分别在两个目标jsp中都输出结果:
登录界面
我们点击链接会出现以下结果:
返回之后点击显示会出现同样的结果:
这就是SessionAttributes注解的作用;简单的说它可以通过 @SessionAttributes("userInfo") 的方法将 目标数据 userinfo 放到 session 中,供其他请求使用。
注意:该注解只能将Map、ModelMap、Model或ModelAndView中的数据暂存到HttpSession中。