基於SpringMVC框架寫的:
/** * 讀取所有cookie * 注意二、從客戶端讀取Cookie時,包括maxAge在內的其他屬性都是不可讀的,也不會被提交。浏覽器提交Cookie時只會提交name與value屬性。
* maxAge屬性只被浏覽器用來判斷Cookie是否過期 * @param request * @param response */ @RequestMapping("/showCookies") public void showCookies(HttpServletRequest request,HttpServletResponse response ){ Cookie[] cookies = request.getCookies();//這樣便可以獲取一個cookie數組 if (null==cookies) { System.out.println("沒有cookie========="); } else { for(Cookie cookie : cookies){ System.out.println("name:"+cookie.getName()+",value:"+ cookie.getValue()); } } } /** * 添加cookie * @param response * @param name * @param value */ @RequestMapping("/addCookie") public void addCookie(HttpServletResponse response,String name,String value){ Cookie cookie = new Cookie(name.trim(), value.trim()); cookie.setMaxAge(30 * 60);// 設置為30min cookie.setPath("/"); System.out.println("已添加==============="); response.addCookie(cookie); } /** * 修改cookie * @param request * @param response * @param name * @param value * 注意一、修改、刪除Cookie時,新建的Cookie除value、maxAge之外的所有屬性,例如name、path、domain等,
*都要與原Cookie完全一樣。否則,浏覽器將視為兩個不同的Cookie不予覆蓋,導致修改、刪除失敗。 */ @RequestMapping("/editCookie") public void editCookie(HttpServletRequest request,HttpServletResponse response,String name,String value){ Cookie[] cookies = request.getCookies(); if (null==cookies) { System.out.println("沒有cookie=============="); } else { for(Cookie cookie : cookies){ if(cookie.getName().equals(name)){ System.out.println("原值為:"+cookie.getValue()); cookie.setValue(value); cookie.setPath("/"); cookie.setMaxAge(30 * 60);// 設置為30min System.out.println("被修改的cookie名字為:"+cookie.getName()+",新值為:"+cookie.getValue()); response.addCookie(cookie); break; } } } } /** * 刪除cookie * @param request * @param response * @param name */ @RequestMapping("/delCookie") public void delCookie(HttpServletRequest request,HttpServletResponse response,String name){ Cookie[] cookies = request.getCookies(); if (null==cookies) { System.out.println("沒有cookie=============="); } else { for(Cookie cookie : cookies){ if(cookie.getName().equals(name)){ cookie.setValue(null); cookie.setMaxAge(0);// 立即銷毀cookie cookie.setPath("/"); System.out.println("被刪除的cookie名字為:"+cookie.getName()); response.addCookie(cookie); break; } } } }
/** * 根據名字獲取cookie * @param request * @param name cookie名字 * @return */ public Cookie getCookieByName(HttpServletRequest request,String name){ Map<String,Cookie> cookieMap = ReadCookieMap(request); if(cookieMap.containsKey(name)){ Cookie cookie = (Cookie)cookieMap.get(name); return cookie; }else{ return null; } } /** * 將cookie封裝到Map裡面 * @param request * @return */ private Map<String,Cookie> ReadCookieMap(HttpServletRequest request){ Map<String,Cookie> cookieMap = new HashMap<String,Cookie>(); Cookie[] cookies = request.getCookies(); if(null!=cookies){ for(Cookie cookie : cookies){ cookieMap.put(cookie.getName(), cookie); } } return cookieMap; }