Cookie入门

2019-04-09  本文已影响0人  丫甘九

Http协议与Cookie(了解)

一个Cookie最大4kb
一个服务器最多向一个浏览器保存20个Cookie
一个浏览器最多可以保存300个Cookie

Cookie的用途

javaweb中使用Cookie

使用reponse发送set-Cookie响应头
使用request获取响应头

使用response.addCookie()方法向浏览器保存Cookie
使用request.getCookie()方法获取浏览器归还的Cookie

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>保存Cookie</h1>
<%
Cookie cookie1 = new Cookie("aaa","AAA");
response.addCookie(cookie1);

Cookie cookie2 = new Cookie("bbb","BBB");
response.addCookie(cookie2);
%>
</body>
</html>


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>保存Cookie</h1>
<%
Cookie[] cookies = request.getCookies();
if (cookies!=null){
    for (Cookie c : cookies){
        out.print(c.getName()+"="+c.getValue()+"<br/>");
    }
}
%>
</body>
</html>
image.png
image.png

Cookie详解

maxAge>0:浏览器会把Cookie保存到客户端硬盘上,有效时长为maxAge的值决定
maxAge<0:Cookie只在浏览器内存中存在,当用户关闭浏览器时,浏览器进程结束,同时Cookie也就死亡了
maxAge=0:浏览器会马上删除这个Cookie

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>保存Cookie</h1>
<%
Cookie cookie1 = new Cookie("aaa","AAA");
cookie1.setMaxAge(60*60);
response.addCookie(cookie1);
%>
</body>
</html>
image.png
image.png
image.png
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>保存Cookie</h1>
<%
    Cookie cookie1 = new Cookie("aaa","AAA");
    cookie1.setMaxAge(0);
    response.addCookie(cookie1);
%>
</body>
</html>

image.png
image.png

Cookie的path(理解)

acookie.path=/day11/;bcookie.path=/day11/jsps/;ccookie.path=/day11/jsps/cookie/;
访问:/day11/index.jsp/时,归还:aCookie
访问:/day11/jspa/index.jsp时,归还:acookie,bcookie
访问://day11/jsps/cookie/index.jsp时,归还acookie,bcookie,ccookie

Cookie的domain(了解)

上一篇 下一篇

猜你喜欢

热点阅读