SpringMVC中 Session的使用情况

时间:2023-03-09 19:33:24
SpringMVC中 Session的使用情况

在SpringMVC中,使用Session可以用通过两种方式

  1、servlet-api 即HttpSession

     session.setAttritute(),session.getAttribute();

  2、使用@sessionAttributes()注解

   ①Spring框架会在调用完Controller之后、渲染View之前检查Model的信息,并把@SessionAttributes()注释标明的属性加入session中

   ②@ModelAttribute在声明Controller的参数的时候,可以用来表明此参数引用某个存在在Model中的对象,如果 这个对象已经存在于Model中的话(Model可以在调用Controller之前就已经保存有数据,这应该不仅仅因为 HandlerInterceptor或者@ModelAttribute标记的方法已经显式的将一些对象加入到了Model对象中,也因为Spring会默认将一些对象加入到Model中,这一点很重要)。    

   ③如果Session中已经存在某个对象,那么可以直接使用ModelAttribute声明Controller的参数,在Controller中可以直接使用它。

eg.1

@Controller
public class ManagerController { @RequestMapping(value = "/login",method = RequestMethod.GET)
public ModelAndView login(HttpSession httpSession){ httpSession.setAttribute("username", "admin");
    return new ModelAndView("login");
}
@RequestMapping(value = "/logout",method = RequestMethod.GET)
public String logout(HttpSession httpSession){
String name=httpSession.getAttribute("username");
      return "success";
}

eg.2

@Controller
@SessionAttributes("username")
public class ManagerController { @RequestMapping(value = "/login",method = RequestMethod.GET)
public ModelAndView login(Model model)
model.addAttribute("username", "admin");
return new ModelAndView("login"); } @RequestMapping(value = "/logout",method = RequestMethod.GET)
public String logout(@ModelAttribute("username") String name){
    System.out.println(name);
    return "success"; } }

参考链接:http://www.cnblogs.com/waytofall/p/3460533.html