Home  >  Article  >  Web Front-end  >  Two methods for SpringMVC to access Session

Two methods for SpringMVC to access Session

高洛峰
高洛峰Original
2017-01-07 09:25:261393browse

WEB applications usually introduce Session to save the status of a series of actions/messages between the server and the client. For example, online shopping maintains user login information until the user exits. There are two methods for SpringMVC to access Session, as follows:

Method 1: Use servlet-api

@Controller
public class ManagerController { 
  
  @Resource
  private ManagerService managerServiceImpl; 
    
  @RequestMapping(value = "manager/login.do",method = RequestMethod.GET)  
  public ModelAndView login(ManagerModel managerModel,HttpSession httpSession){ 
      
    ManagerModel manager = managerServiceImpl.getManager(managerModel); 
    if(manager!=null){ 
      manager.setPassword(""); 
      httpSession.setAttribute("manager", manager); 
      return new ModelAndView(new RedirectView("../admin/main.jsp")); 
    }else{ 
      return new ModelAndView(new RedirectView("../admin/login.jsp")); 
    } 
  } 
    
  @RequestMapping(value = "manager/logout.do",method = RequestMethod.GET) 
  public String logout(HttpSession httpSession){ 
    httpSession.getAttribute("manager"); 
    return "success"; 
  } 
}

Method 2: Use SessionAttributes

@Controller
@SessionAttributes("manager") 
public class ManagerController { 
  
  @Resource
  private ManagerService managerServiceImpl; 
    
  @RequestMapping(value = "manager/login.do",method = RequestMethod.GET)  
  public ModelAndView login(ManagerModel managerModel,ModelMap model){ 
      
    ManagerModel manager = managerServiceImpl.getManager(managerModel); 
    if(manager!=null){ 
      manager.setPassword(""); 
      model.addAttribute("manager", manager); 
      return new ModelAndView(new RedirectView("../admin/main.jsp")); 
    }else{ 
      return new ModelAndView(new RedirectView("../admin/login.jsp")); 
    } 
  } 
    
  @RequestMapping(value = "manager/logout.do",method = RequestMethod.GET) 
  public String logout(@ModelAttribute("manager")ManagerModel managerModel){ 
    return "success"; 
  } 
}

That’s it for this article I hope that all the content will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.

For more related articles on the two methods of SpringMVC accessing Session, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn