一、cookie是服務器端將標示符寫到瀏覽器,瀏覽器訪問服務器自動攜帶
服務器端創建Cookie
Random random = new Random(); Cookie cookie = new Cookie("writeCookie","writeCookie"+random.nextInt(10)); cookie.setMaxAge(60);//設置瀏覽器的Cookie存留時間,單位爲秒 //cookie.setPath(request.getContextPath()); cookie.setPath("/");//設置cookie的作用域爲整個站點 response.addCookie(cookie);
服務器獲取瀏覽器的Cookie
Cookie[] cookies = request.getCookies(); if(cookies!=null){ for(Cookie cookie : cookies){ out.println(cookie.getName()+":"+cookie.getValue()); out.println("<br>"); } }
二、cookie的應用場景
1、用戶自動登錄
2、瀏覽最近的商品