登录后保存用户信息到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中,并返回到前端

 

 

posted @ 2018-11-22 13:31  stalla  阅读(7212)  评论(1)    收藏  举报