js用ajax请求获取session的值,json方式

登录后保存用户信息到Session login登录只要添加红色的2个地方

HttpSession httpSession
 httpSession.setAttribute("username", username);
 httpSession.setAttribute("password", pwd);

Controller获取代码:(return JSON对象)

@PostMapping("/getUserSession")
    public String getUserSession(HttpServletRequest request, HttpSession httpSession) {
          
   
        JSONObject jsonObject = new JSONObject();
        if(httpSession!=null){
          
   
            jsonObject.put("usernameaa", httpSession.getAttribute("username"));
//            jsonObject.put("password", httpSession.getAttribute("password"));
        }
        return JSONObject.toJSONString(jsonObject);
    }

再在前端js中调用Controller第二个方法,获取session内容 JS中代码:

$.ajax({
          
   
            url: /user/getUserSession,
            dataType:json,
            type: post,
            success: function (data) {
          
    
                alert("usernameaa"+data.usernameaa);
            }
        });

第二种方法 common.js

/**
 * 接受url传的id
 * @param name
 * @returns {string}
 */
function getQueryString(name) {
          
   
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
          
   
        return decodeURIComponent(r[2]);
    }
    return ;
}
经验分享 程序员 微信小程序 职场和发展