java操作cookie。本站提示廣大學習愛好者:(java操作cookie)文章只能為提供參考,不一定能成為您想要的結果。以下是java操作cookie正文
基於SpringMVC框架寫的:
/** * 讀取一切cookie * 留意二、從客戶端讀取Cookie時,包括maxAge在內的其他屬性都是不可讀的,也不會被提交。閱讀器提交Cookie時只會提交name與value屬性。通常開發時先用以下的代碼將獲取的cookie停止封裝:
* 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; }