【踩坑】spring每次请求后session不一样导致无法在服务器保存信息

根据网上的资料,若想在服务器用session保存一些信息,方法如下:

    public Xclass Xmethod(HttpServletRequest request, HttpSession session, Params parameterName){
            session.setAttribute("keyName", parameterName);
        }
    }

这样,想获取keyName键的值,可以使用语句:

public void Ymethod(HttpServletRequest request, HttpSession session) {
    String keyValue = (String) session.getAttribute("keyName");
    // do somethong  
}

但是使用ajax获取数据进行测试,keyValue总是null。

 原因:

每次请求服务器所对应的session不一样,导致session.setAttribute()方法保存的信息保存在不同的session中。

解决方法:

1. 后台

在控制器前使用@CrossOrigin注解,设置allowCredentials属性为true,即:

@CrossOrigin(allowCredentials="true") 
@RestController
@RequestMapping("/xxx")
public class xxxController {
    ******
}

2. 前端

ajax请求中,加入 xhrFields:{withCredentials:true} , 即:

$.ajax({
    type: get,
    url: "http://localhost"
    data: {
        data1: "whatever"
    },
    dataType: "json",
    ***
    xhrFields:{
        withCredentials:true
    },
    ***
    success: function(data){
        // do something
    }
});

然后同一浏览器发出ajax在后台就能使用同一session,从而共享相同的信息了。

猜你喜欢

转载自www.cnblogs.com/lipohong/p/10676112.html