如果您有现有的代码,那么毫无疑问您已经使用了 java servlet Cookie 对象。我们当然有,所以我们想要破坏性最小的选择。 @kriegaex 的答案简洁明了,但基本上是对 cookie 进行硬编码,并且不重用 cookie 对象。为了扩展他的答案,我们编写了这个函数来处理相同的站点功能,同时维护现有的 Cookie 对象功能。此答案旨在用于您需要在响应对象上添加多个 cookie 的情况下,而无需更改可能已经在标头上的现有 cookie。当然,另一种选择是编写一个新的 cookie 类并扩展功能,但这需要对现有代码进行比我们在这里提出的更多的更改。
请注意,使用此解决方案,只需更改一行现有代码(每个 cookie)即可添加相同的网站功能。
示例用法:
// Existing code that doesn't change:
Cookie cookie1=new Cookie("cookie1",Util.encodeURL(id));
cookie1.setHttpOnly(false);
cookie1.setPath("/");
Cookie cookie2=new Cookie("cookie2",Util.encodeURL(id));
cookie2.setHttpOnly(false);
cookie2.setPath("/");
// Old Code that is replaced by new code
// httpResponse.addCookie(cookie1);
// httpResponse.addCookie(cookie2);
// New Code - see static helper class below
HttpService.addCookie(httpResponse, cookie1, "none");
HttpService.addCookie(httpResponse, cookie2, "Strict");
使用 cURL 时的示例响应标头:
< HTTP/1.1 200 OK
< Connection: keep-alive
< X-Powered-By: Undertow/1
< Set-Cookie: cookie1=f871c026e8eb418c9c612f0c7fe05b08; path=/; SameSite=none; secure
< Set-Cookie: cookie2=51b405b9487f4487b50c80b32eabcc24; path=/; SameSite=Strict; secure
< Server: WildFly/9
< Transfer-Encoding: chunked
< Content-Type: image/png
< Date: Tue, 10 Mar 2020 01:55:37 GMT
最后是静态辅助类:
public class HttpService {
private static final FastDateFormat expiresDateFormat= FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss zzz", TimeZone.getTimeZone("GMT"));
public static void addCookie(HttpServletResponse response, Cookie cookie, String sameSite) {
StringBuilder c = new StringBuilder(64+cookie.getValue().length());
c.append(cookie.getName());
c.append('=');
c.append(cookie.getValue());
append2cookie(c,"domain", cookie.getDomain());
append2cookie(c,"path", cookie.getPath());
append2cookie(c,"SameSite", sameSite);
if (cookie.getSecure()) {
c.append("; secure");
}
if (cookie.isHttpOnly()) {
c.append("; HttpOnly");
}
if (cookie.getMaxAge()>=0) {
append2cookie(c,"Expires", getExpires(cookie.getMaxAge()));
}
response.addHeader("Set-Cookie", c.toString());
}
private static String getExpires(int maxAge) {
if (maxAge<0) {
return "";
}
Calendar expireDate = Calendar.getInstance();
expireDate.setTime(new Date());
expireDate.add(Calendar.SECOND,maxAge);
return expiresDateFormat.format(expireDate);
}
private static void append2cookie(StringBuilder cookie, String key, String value) {
if (key==null ||
value==null ||
key.trim().equals("")
|| value.trim().equals("")) {
return;
}
cookie.append("; ");
cookie.append(key);
cookie.append('=');
cookie.append(value);
}
}