我正在尝试为会话cookie设置一个属性,并将该属性用于后续请求(在第一个请求之后(。以下是我的代码。在这里,我使用check
变量来检查代码的功能。对于第一个请求,它应该为后续请求提供"init"和"original"。但是,我得到"init"作为所有请求的输出。此问题的原因是什么?
@Override
protected void doGet(HttpServletRequest reqest, HttpServletResponse response) throws IOException {
HttpSession ssn = reqest.getSession();
reqest.getSession(true);
String check="original";
if(ssn.getAttribute("currentQuestion")==null){
check="init";
ssn.setAttribute("currentQuestion","0");
}
response.addHeader("Access-Control-Allow-Origin", "*");
response.getWriter().println(check);
}
我正在使用 folloeing AJAX 客户端发送请求
function submitAnswer() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "http://example.com:8080/Simple/hello?username=malintha", true);
xhttp.send();
}
代码的逻辑很好。 但是,我注意到您调用了两次getSession。这不是必需的。 尝试删除第二个 getSession(true( 调用。
另外,请确保使用外部浏览器,例如Chrome或Firefox,而不是eclipse内置的浏览器。