登錄后保存用戶信息到Session


 

前端通過JS把用戶信息傳到Controller,然后在Controller里將信息放入HttpSession中

  1.  
    @ResponseBody
  2.  
    @RequestMapping(value = "/loginIn", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
  3.  
    public String loginIn(HttpServletRequest request, HttpSession httpSession) {
  4.  
    String loginuser = request.getParameter( "username");
  5.  
    String pwd = request.getParameter( "password");
  6.  
    logger.info( "loginuser:" + loginuser + ",pwd:" + pwd);
  7.  
    JSONObject jsonObject = userFacade.loginIn(loginuser, pwd);
  8.  
    // 將用戶保存到session內
  9.  
    if ( "0".equals(jsonObject.getString( "ecode"))) { //判斷不用管
  10.  
    httpSession.setAttribute( "username", loginuser);
  11.  
    httpSession.setAttribute( "password", pwd);
  12.  
    }
  13.  
    return FastJsonConvert.convertObjectToJSON(jsonObject);
  14.  
    }
再在前端js中調用Controller第二個方法,獲取session內容

JS中代碼:

  1.  
    var username = "";
  2.  
    $.ajax({
  3.  
    "url" : "getUserSession",
  4.  
    "method" : "POST",
  5.  
    "cache" : false,
  6.  
    "async" : false,
  7.  
    }).success( function(data){
  8.  
    if(data.username != null){
  9.  
    username = data.username;
  10.  
    }
  11.  
    })
Controller獲取代碼:(return JSON對象)

 

  1.  
    @ResponseBody
  2.  
    @RequestMapping(value = "/getUserSession", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
  3.  
    public String getUserSession(HttpServletRequest request, HttpSession httpSession) {
  4.  
    JSONObject jsonObject = new JSONObject();
  5.  
    if(httpSession!= null){
  6.  
    jsonObject.put( "username", httpSession.getAttribute( "username"));
  7.  
    jsonObject.put( "password", httpSession.getAttribute( "password"));
  8.  
    }
  9.  
    return FastJsonConvert.convertObjectToJSON(jsonObject);
  10.  
    }
這樣就可把user信息保存到session中,並返回到前端

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM