1;在方法参数列表中直接添加HttpSession httpSession,然后调用servlet-api存取session属性
@RequestMapping(value = "manager/login",method = RequestMethod.GET)
public ModelAndView login(Manager manager,HttpSession httpSession){
Manager managerTemp = managerService.getManager(manager);
if(managerTemp!=null){
managerTemp .setPassword("");
httpSession.setAttribute("managerTemp ", managerTemp );
return new ModelAndView(new RedirectView("../admin/main.jsp"));
}else{
return new ModelAndView(new RedirectView("../admin/login.jsp"));
}
}
2;使用@SessionAttributes注解——注意这是个类注解,在同个controller有效通过ModelMap可以操作注解的注的value等于操作session
@Controller
@SessionAttributes({"User","Y"}) //此处定义此Controller中将要创建和使用哪些session中的对象名
public class UserController {
@Resource
private UserService userService;
@RequestMapping("user_login")
public String login(User user, ModelMap modelMap){
//modelMap自动与session对应,你在往modelmap中添加对应属性便是往session中添加属性(前提是你已经在@SessionAttributes注解中定义好)
User userTemp = this.userService.findByName(user.getName());
if((userTemp.getState() == 1) && (userTemp.getPassword().equals(user.getPassword())){
modelMap.addAttribute("User", userTemp); //成功将userTemp存入session中
modelMap.addAttribute("Y",1); //成功将1存入session中
return "/user/index";
}else {
return "index";
}
@RequestMapping("user_logout")
public String logout(@ModelAttribute("User") User user, SessionStatus sessionStatus){
//@ModelAttribute("User")相当于将session中名为"User"的对象注入user对象中
//sessionStatus中的setComplete方法可以将session中的内容全部清空
sessionStatus.setComplete();
return "index";
}
}