当前位置 : 主页 > 编程语言 > java >

怎样将数据存入session

来源:互联网 收集:自由互联 发布时间:2022-10-26
怎么将数据存入session 默认数据都是存入request ,需要自己设置存入session 。 1.方式1 原生session代码 @RequestMapping("/selectUser") public String selectUser(HttpServletRequest request) { User user=new User("zhangs

怎么将数据存入session
默认数据都是存入request ,需要自己设置存入session 。

1.方式1 原生session代码

@RequestMapping("/selectUser")
public String selectUser(HttpServletRequest request)
{
User user=new User("zhangsan","123",23,new Address("湖北","武汉","汉口大道100号"));

HttpSession session= request.getSession();

session.setAttribute("sessionuser",user);

return "showUser4";
}

测试取值:

${sessionScope.sessionuser.uname}

2.通过注解的方式
2.1先将值存入model

@Controller

//@SessionAttributes(value="sessionuser2")
@RequestMapping("/user4")
public class UserController4 {



@RequestMapping("/selectUser2")
public ModelAndView selectUser2()
{
User user=new User("zhangsan2","123",23,new Address("湖北","武汉","汉口大道100号"));

User user2=new User("zhangsan22","123",23,new Address("湖北","武汉","汉口大道100号"));


ModelAndView modelAndView=new ModelAndView();

modelAndView.addObject("sessionuser2",user);

modelAndView.addObject("user2",user2);

modelAndView.setViewName("showUser5");


return modelAndView;

}
}

2.2在 类上加入注解

@SessionAttributes("存入model中的key")

@Controller
// 通过注解的方式将数据存入session
@SessionAttributes("sessionuser2")
//@SessionAttributes(value="sessionuser2")
@RequestMapping("/user4")
public class UserController4 {



@RequestMapping("/selectUser2")
public ModelAndView selectUser2()
{
User user=new User("zhangsan2","123",23,new Address("湖北","武汉","汉口大道100号"));

User user2=new User("zhangsan22","123",23,new Address("湖北","武汉","汉口大道100号"));


ModelAndView modelAndView=new ModelAndView();

modelAndView.addObject("sessionuser2",user);

modelAndView.addObject("user2",user2);

modelAndView.setViewName("showUser5");


return modelAndView;

}
}
网友评论