參考連接:https://www.studytonight.com/servlet/storing-session-using-cookies.phpphp
即Cookie是web container生成的,存儲一小塊信息,是web container經過response返回給client的,Cookie存儲在client的瀏覽器中,它有個存活時間,到時間了就會被瀏覽器銷燬。java
Cookie有個缺點就是,若是Cookie被存儲在瀏覽器中了,那麼它是不能被修改的,由於瀏覽器不容許修改Cookie。web
public class Cookie implements Cloneable, Serializable { private static final long serialVersionUID = -6454587001725327448L; private static final String TSPECIALS; private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings"; private static ResourceBundle lStrings = ResourceBundle.getBundle(LSTRING_FILE); static { if (Boolean.valueOf(System.getProperty("org.glassfish.web.rfc2109_cookie_names_enforced", "true"))) { TSPECIALS = "/()<>@,;:\\\"[]?={} \t"; } else { TSPECIALS = ",; "; } } // // The value of the cookie itself. // private String name; // NAME= ... "$Name" style is reserved private String value; // value of NAME // // Attributes encoded in the header's cookie fields. // private String comment; // ;Comment=VALUE ... describes cookie's use // ;Discard ... implied by maxAge < 0 private String domain; // ;Domain=VALUE ... domain that sees cookie private int maxAge = -1; // ;Max-Age=VALUE ... cookies auto-expire private String path; // ;Path=VALUE ... URLs that see the cookie private boolean secure; // ;Secure ... e.g. use SSL private int version = 0; // ;Version=1 ... means RFC 2109++ style private boolean isHttpOnly = false;
圖1 servlet-3.0.1 中的Cookie屬性,支持HTTP/1.0和HTTP/1.1apache
Cookie中的name,多個Cookie時,name容許重複,可是這個value是全局惟一的,這個value的值就是咱們平時所說的HttpSession ID。瀏覽器
下面的圖2是在Chrome中截圖的:cookie
圖2 Chrome中截的Cookie信息session
下面的圖3,原圖地址。dom
圖3 建立Cookie、設置屬性ide
在Servlet中,能夠在HttpServletResponse中經過addcookie()方法添加Cookie到response中,將cookie返回給client的browser。spa
在Servlet中,能夠在HttpServletRequest中,經過getCookies()方法,得到全部的Cookie。
來看下Tomcat8中,HttpServletResponse的addCookie()是怎麼實現的,具體能夠看下org.apache.catalina.connector.Response的實現,以下圖4所示:
@Override public void addCookie(final Cookie cookie) { // Ignore any call from an included servlet if (included || isCommitted()) { return; } String header = generateCookieString(cookie); //if we reached here, no exception, cookie is valid // the header name is Set-Cookie for both "old" and v.1 ( RFC2109 ) // RFC2965 is not supported by browsers and the Servlet spec // asks for 2109. addHeader("Set-Cookie", header); }
圖4 HttpServletResponse的addCookie方法
在generateCookieString(cookie)中,會將Cookie中的屬性拼接爲String類型,以後經過addHeader("Set-Cookie", header),將Cookie信息放入Response的Header。
HttpServletResponse的addCookie(Cookie)能夠被屢次調用,這樣就能夠設置多個Cookie到同一個Response中。