我正在通过 servlet 试验 cookie。当我通过 javascript 向该 servlet 发出请求时,响应标头具有set-cookie
,但是在向同一域上的同一 servlet 或其他 servlet 发出后续请求时,请求标头没有cookie
标头。我已经粘贴了下面的实验代码,请让我知道我哪里出错了。
package com.java.servlet;
import java.io.IOException;
@SuppressWarnings("serial")
public class ServletTest extends HttpServlet {
public void init() throws ServletException {
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Create cookies for first and last names.
Cookie userId = new Cookie("userId",
request.getParameter("userId"));
// Set expiry date after 24 Hrs for both the cookies.
userId.setMaxAge(60 * 60 * 24);
// Add both the cookies in the response header.
response.addCookie(userId);
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Credentials", "false");
response.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Cookie");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
List<String> ls = new ArrayList<String>();
ls.add("111");
ls.add("aaa");
pw.print(ls); //some random data
}
public void destroy() {
}
}
我使用的 javascript 直接来自 w3schools 的 xmlHttpRequest。我贴在下面
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://192.168.1.10:8080/ServletTest/servlet", true);
xmlhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
我注意到 cookie 没有存储在这个 servlet 的浏览器 cookie 存储中。帮帮我