原文鏈接
Cookie作用域
Cookie 在二級域名下是可以共享的,如www.a.com 和m.a.com 他們的Cookie 是可以共享的,這也是很多單點登錄利用Cookie實現的原理,但是很多站點不是二級域名的如www.taobao.com和www.tmall.com,它們是完成兩個不同的域名,那麼完全不同的域名可以共享Cookie嗎?答案是可以的,我們看一下實現思路。
跨域寫Cookie
跨域寫Cookie 的原理主要是利用html中的 《script>標籤可以跨域獲來實現的
現有a.com 和b.com 兩個站點,可以通過Hosts文件配置,如下圖所示
在b.com 中建立一個serlvet 負責寫Cookie ,代碼 如下:
@WebServlet("/SetCookie")
public class SetCookie extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String cookieName=request.getParameter("cookieName");
String cookieValue=request.getParameter("cookieValue");
response.addCookie(new Cookie(cookieName, cookieValue));
response.getWriter().append("add Cookie");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
該Serlvet的訪問地址爲:http://b.com/ClientB/SetCookie?cookieName=userId&cookieValue=123458787456 主要作用就是獲取請求中的cookieName和cookieValue 然後寫到b.com中
在a.com 中添加一個index.html 頁面,頁面中代碼 如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="http://b.com/ClientB/SetCookie?cookieName=userId&cookieValue=123458787456"/>
</head>
<body>
hello
</body>
</html>
這段代碼主要是通過 《script》 標籤訪問b.com中的寫Cookie接口,從而將Cookie 寫到b.com中
測試
查看b.com Cookie
跨域讀Cookie
跨域讀Cookie 主要利用《iframe》標籤可以跨域的特性完成的。
- b.com 下有一個2.html 內容如下:
<html>
<head>
</head>
<body>
<script>
window.location="http://a.com/ClientA/3.html?"+document.cookie;
</script>
</body>
</html>
這段代碼主要是將b.com下的所有cookie通過url參數方式跳轉到a.com下的3.html
- a.com下有 1.html 內容如下:
<html>
<head>
</head>
<body>
<iframe src='http://b.com/ClientB/2.html' width='100' height='100'> </iframe>
<textarea id="zhaochao">
</textarea>
</body>
</html>
這段代碼主要作用是通過一個《iframe》標籤訪問b.com下的2.html
- a.com下有3.html 內容如下:
<html>
<head>
</head>
<body>
<script>
window.parent.document.getElementById("zhaochao").value=window.location.toString().substring(window.location.toString().indexOf("?"));
</script>
</body>
</html>
這段代碼主要是將b.com下的2.html中的url參數寫到 1.html中textarea中
防問http://a.com/ClientA/1.html 獲取b.com下的所有Cookie