跨域写入cookie
可以通过URL参数实现跨域cookie写入,例如,www.a.com域需要为www.b.com域写入cookie信息,token=abcd。
清单:实现重定向,URL: http://www.a.com/token?from=http://www.b.com/set_cookie
@WebServlet("/token")
public class TokenGeneratorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 生成token
String token = "abcd";
String cookieName = "token";
String cookieVal = token;
//写入本域cookie
//Cookie cookie = new Cookie(cookieName, cookieVal);
//cookie.setPath("/");
//response.addCookie(cookie);
// 请求的原始来源域
String from = request.getParameter("from");
response.sendRedirect(from + "?cname=" + cookieName + "&cval=" + cookieVal); //重定向到目标域
}
}
清单:实现写入cookie,URL:http://www.b.com/set_cookie
@WebServlet("/set_cookie")
public class SetCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 将要写入的cookie项,调用者通过参数传递
String cookieName = request.getParameter("cname"); //cookie的key
String cookieVal = request.getParameter("cval"); //cookie的value
// 生成cookie
Cookie cookie = new Cookie(cookieName, cookieVal);
cookie.setPath("/");
response.addCookie(cookie);
}
}
缺点:只能实现向一个域写入cookie
跨域读取cookie
可以通过js的script标签读取其它域的cookie。
假设页面cookie_reader.jsp 需要读取www.b.com的cookie值token,现在www.b.com域名的网站对外暴露了 URL为http://www.b.com/read_cookies 的API,该API将读取该域所有的cookie键值对,然后把键值对以下面这种形式,返回。
var cookie_key1=cookie_value1; var cookie_key2=cookie_value2
清单:cookie_reader.jsp 读取cookie值:token,并弹窗
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>读取其它域cookie信息</title>
<!--
通过script标签执行另一个域实现的读取cookie的方法,
script标签返回结果将是变量定义形式的js代码,其中每一个变量表示一个cookie项
这些代码加载后,此页面后续js代码可直接读取已定义的变量值,即各cookie值
-->
<script type="text/javascript" src="http://www.b.com/read_cookies"></script>
</head>
<body>
<script type="text/javascript">
alert(token);
</script>
</body>
</html>
清单:read_cookies API接口
@WebServlet("/read_cookies")
public class ReadCookiesServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
StringBuilder builder = new StringBuilder();
// 一定要正确设置响应类型,否则可能导致IE不解析js而直接进行下载操作
response.setContentType("application/javascript");
if (cookies != null) {
PrintWriter writer = response.getWriter();
for (Cookie cookie : cookies) {
builder.setLength(0);
// 结果类似于var token='test123';
builder.append("var ")
.append(cookie.getName())
.append("=")
.append("'")
.append(cookie.getValue())
.append("'")
.append(";");
writer.write(builder.toString());
}
}
}
}