欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringMVC存取Session的两种方法

程序员文章站 2024-03-09 11:21:05
web 应用通常会引入 session,用来在服务端和客户端之间保存一系列动作/消息的状态,比如网上购物维护 user 登录信息直到 user 退出。springmvc存取...

web 应用通常会引入 session,用来在服务端和客户端之间保存一系列动作/消息的状态,比如网上购物维护 user 登录信息直到 user 退出。springmvc存取session的两种方法,具体如下:

方法一:使用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"; 
  } 
} 

方法二:使用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"; 
  } 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。