本文實例講述了Java讀寫Cookie記錄的方法。分享給大家供大家參考。具體如下:
寫Cookie ,cookie的value可以使String, list , map,int :
?
1 2 3 4 5 6 7 Cookie usernameCookie = new Cookie("username_" + schoolId, encodedUsername); usernameCookie.setMaxAge(60 * 60 * 24 * 365); response.addCookie(usernameCookie); //設置useriCookie--用於心教育的猜你喜歡課程 Cookie userIdCookie = new Cookie("userId_" + schoolId, userId); userIdCookie.setMaxAge(60 * 60 * 24 * 365); response.addCookie(userIdCookie);讀Cookie:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); String userId=null; Cookie[] cookies = request.getCookies(); //cookies不為空,則清除 if(cookies!=null) { for(Cookie cookieTemp : cookies){ String cookieIdentity = cookieTemp.getName(); //查找身份串 if(cookieIdentity.equals("userId_"+schoolId)) { userId=cookieTemp.getValue(); } } }希望本文所述對大家的java程序設計有所幫助。