JavaNote 4.3 Cookie

一、cookie
name:Cookie的名称;
value:Cookie的值;
comment:Cookie的注释;
domain:可以看到Cookie的域;
maxAge:Cookie的失效时间;正值表示Cookie会在指定的时间后过期,负值表示浏览器关闭的时候过期,0会导致Cookie被删除;
path:可以看到Cookie的URL;
secure:是否需要使用安全连接来传输;
version:版本;
isHttpOnly:HttpOnly的Cookie将不会暴露给客户端的脚本代码;
Cookie的名称要符合标识符的命名规则,同时不允许为【Comment,Discard,Domain,Expires,Max-Age,Path,Secure,Version】这几个关键字,也不允许以“$”开头

二、servlet
package com.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "CookieServlet",urlPatterns = "/cookie")
public class CookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                    Cookie cookie = new Cookie("goods","cup");//新建cookie
                    cookie.setMaxAge(60*10);//expire单位是秒,设置为0时关闭浏览器会销毁cookie
                    cookie.setHttpOnly(true);
                    cookie.setPath("/getCookie");//设置需要携带cookie的访问路径,/getCookie路径下的所有链接都需携带该cookie
                    response.addCookie(cookie);//相应添加cookie
                    Cookie cookie1 = new Cookie("wuxiaowei","study");               
                    response.addCookie(cookie1);
                    response.sendRedirect("http://localhost:8080/getCookie");//重定向
    }
}
三、getCookie
package com.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "GetCookieServlet", urlPatterns = "/getCookie")
public class GetCookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
//           String name = cookie.getName();
            response.getWriter().println( cookie.getValue());
//            if (name.equals("wuxiaowei")) {
//                response.getWriter().print("wuxiaowei" + ":" + cookie.getValue());
//            }
        }

    }
}
四、截图

JavaNote 4.3 Cookie_第1张图片

JavaNote 4.3 Cookie_第2张图片

你可能感兴趣的:(Java,Note)