1. 程式人生 > >【cookie的使用】&【Session】

【cookie的使用】&【Session】

on() 服務端 引入 一點 如何獲取 bject web bsp 服務器端

明確一點:
cookie由服務器創建Cookie cookie=new Cookie("haha","xixi") 通過HtttpServletResponse對象的addCookie(cookie)方法存儲到瀏覽器端
cookie是一個鍵值對。cookie不能存中文,若存中文需要編碼處理。
①創建Cookie
Cookie cookie=new Cookie(String key,String value);
②將Cookie寫回瀏覽器
通過HtttpServletResponse對象的addCookie(Cookie cookie)方法
③服務器端如何獲取cookie
通過HtttpServletRquest對象的Cookie[] cookies = request.getCookies();方法
getName();
getValue(String name)

【Session】

1.cookie 大小數量有限制 ---引入服務端的會話技術--session
(已時間換空間,以空間換時間)

1.獲取session
HttpSession session=request.getSession();
2.往session存數據
存數據:setAttribute(String key,Object value);
取數據:getAttribute(String key);
移除數據:removerAttribute(String key);

三個域對象:(範圍由大到小依次排序)
ServletContext(整個web項目) -----> HttpSession(一次會話) ----> HttpServletRequest(一次請求(轉發可以獲取前一個Servlet存的數據))

【cookie的使用】&【Session】