什么是Cookie和Cookie相关API

时间:2024-5-10    作者:老大夫    分类: JavaWeb


Cookie是由服务端产生 但是 存储在 用户浏览器上的一小份数据,他主要存储着用户的标识信息,以便于用户下次登录不用再次输入相同信息。

创建cookie

@WebServlet("/servletA")
public class ServletA extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建cookie
        Cookie cookie1=new Cookie("keya","valuea");
        Cookie cookie2=new Cookie("keyb","valueb");
        //将cookie放入Response对象 就可以发送给客户端浏览器了
        resp.addCookie(cookie1);
        resp.addCookie(cookie2);
    }
}

取出cookie

@WebServlet("/servletB")
public class ServletB extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求中携带的cookie
        Cookie[] cookies = req.getCookies();
        //请求中的多个cookie会进入该数组  请求中如果没有cookie 那么cookies数组为null
        if(null!=cookies){
            for(Cookie cookie:cookies){
                System.out.println(cookie.getName()+"===="+cookie.getValue());
            }
        }
    }
}

持久化Cookie

一般cookie在关闭浏览器时就消失了,如果需要长时间保存cookie,可以设置保存时间

@WebServlet("/servletA")
public class ServletA extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建Cookie
        Cookie cookie1 =new Cookie("c1","c1_message");
        cookie1.setMaxAge(60);
        Cookie cookie2 =new Cookie("c2","c2_message");
        // 将cookie放入响应对象
        resp.addCookie(cookie1);
        resp.addCookie(cookie2);
    }
}

设置cookie提交路径

设置提交路径后会让浏览器只在访问指定路径时才提交cookie

public class ServletA extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建Cookie
        Cookie cookie1 =new Cookie("c1","c1_message");
        // 设置cookie的提交路径
        cookie1.setPath("/web03_war_exploded/servletB");
        Cookie cookie2 =new Cookie("c2","c2_message");
        // 将cookie放入响应对象
        resp.addCookie(cookie1);
        resp.addCookie(cookie2);
    }
}


扫描二维码,在手机上阅读

推荐阅读: