让cookie失效要注意的问题

让cookie失效要注意的问题

下面的代码无法让cookie 失效,



 

因为保存的cookie 设置了path,

失效时没有设置path, 所以无法cookie 失效,

注意:想让cookie 失效,除了设置有效期为0,其他参数(path,domain)必须完全一样,

正确的:



 

/***
	 * 是否保存cookie
	 * @param response
	 * @param emaiCookieName
	 * @param cookieValue
	 * @param isSave : 是否保存用户名(记住用户名)
	 * @return
	 */
	public static Cookie rememberMe(Cookie[] cookies , /*HttpServletRequest request,*/HttpServletResponse response,String emaiCookieName, String cookieValue,
			boolean isSave) {
//		HttpServletRequest request = ServletActionContext.getRequest();

		boolean flag = false;
		// Cookie passwordCook = null;
		Cookie emailCook = null;
		if (cookies != null) {
			System.out.println("cookie 不为空");
			for (Cookie c : cookies) {
				// if (passwordCookieName.equals(c.getName()))
				// {
				// c.setValue(URLEncoder.encode(password, "utf-8"));
				// passwordCook = c;
				// flag = true;
				// continue;
				// }
//				if(c.getName().equals(Constant2.COOKIE_KEY_ISAUTO_LOGIN )){
//					System.out.println(Constant2.COOKIE_KEY_ISAUTO_LOGIN+":"+cookieValue);
//				}
				if (emaiCookieName.equals(c.getName()) ) {
					System.out.println("找到了 " + emaiCookieName);
					System.out.println("cookie的值为 " + c.getValue());
					if((! ValueWidget.isNullOrEmpty(cookieValue))){
					try {
						c.setValue(URLEncoder.encode(cookieValue, "utf-8"));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					}
					emailCook = c;
					flag = true;
					break;
				}
			}

		}

//		HttpServletResponse response = ServletActionContext.getResponse();
		if (isSave) {
			if (!flag) {
				System.out.println("没有找到 " + emaiCookieName);
				// passwordCook = new Cookie(passwordCookieName, URLEncoder
				// .encode(password, "utf-8"));
				try {
					emailCook = new Cookie(emaiCookieName, URLEncoder.encode(
							cookieValue, "utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			emailCook.setMaxAge(10000000);//单位是秒,所以大概115 天
            emailCook.setPath("/");//设置cookie时,设置path为根路径
            response.addCookie(emailCook);
			flag=true;
			System.out.println("保存cookie:"+emailCook.getValue());
		} else {
			if (flag) {
				System.out.println("让 cookie 失效");
				emailCook.setMaxAge(0);
                emailCook.setPath("/");//设置cookie时,设置path为根路径 ,如果不设置path ,则无法让cookie 失效
                response.addCookie(emailCook);
			}
		}


		return emailCook;
	}

参考:

http://hw1287789687.iteye.com/blog/2050040

猜你喜欢

转载自hw1287789687.iteye.com/blog/2368228