spring mvc中保存数据到session可以利用:
1. 基于HttpSession
2. 基于注解@SessionAttributes
首先需要明确的是,SessionAttributes和SessionAttribute两者是不同的,@SessionAttributes用于在会话中存储Model的属性,一般作用在类的级别。@SessionAttribute是用于获取已经存储的session数据,并且作用在方法的层面上。
使用SessionAttributes可以使用Model、ModelMap、ModelAndView,这三种都可以实现相同的效果。
使用Model:
1. 注解@SessionAttributes在类上:
2. 利用Model同步数据到session:
3.这样userInfo对象就保存到了session中,如果在jsp页面获取相关数据则使用:
<c:out value="${ sessionScope.currentUser.username}"></c:out>
如果在Controller中获取数据可以写相关的方法:
//获取session
@RequestMapping("/session")
public void session(HttpSession session) {
UserInfo u = (UserInfo) session.getAttribute("currentUser");
System.out.println("session:" + u);
}
//删除session
@RequestMapping("/outLogin")
public void tologout(HttpSession session, HttpServletRequest request, HttpServletResponse response, SessionStatus sessionStatus) {
session.removeAttribute("currentUser");
sessionStatus.setComplete();
}
其中,获取session也可以使用注解的形式。@SessionAttributes需要清除时,使用SessionStatus.setComplete();来清除。session.removeAttribute只清除@SessionAttributes的session,不会清除HttpSession的数据,要根据实际情况选择。
2. 使用ModelMap保存数据到session:
modelMap.put("currentUser", userInfo);
3. 使用modelAndView时有两种方法,一种是直接保存,一种是先保存在map中,再保存到session中。
map.put("currentUser", userInfo);
modelAndView.addAllObjects(map);
modelAndView.addObject("currentUser", userInfo);
关于Model、ModelMap和ModelAndView的区别:
https://blog.csdn.net/DFSETHTDFD/article/details/89288532