写一个CookieUtil,方便使用cookies

以前用cookies比较少,虽然知道大致上就是那么回事,但是一直不是很清楚,今天查了查,很老的东西了,就不多介绍了,主要是清除cookie的时候,注意setMaxAge, setPath, 还要response.addCookie(cookie)


附件是一个myEclipse下的Web工程,简单实现了一下自动登录

下面是CookieUtil的代码:


package com.djwl.core.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description: <br>
 * 2010-5-12
 * 
 * @author huxiao [email protected]
 */
public class CookieUtil {

	private final static int maxAge = 60 * 60 * 60 * 24 * 365;
	private final static String uri = "/";

	private CookieUtil() {}

	public static void setAttribute(String key, String value, HttpServletResponse response) {
		Cookie cookie = new Cookie(key, value);
		cookie.setMaxAge(maxAge);
		cookie.setPath(uri);
		response.addCookie(cookie);
	}

	public static String getAttribute(String key, HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(key)) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}
	
	public static void removeAllAttribute(HttpServletRequest request, HttpServletResponse response){
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				removeAttribute(cookie.getName(), response);
			}
		}
	}

	public static void removeAttribute(String key, HttpServletResponse response) {
		Cookie cookie = new Cookie(key, null);
		cookie.setMaxAge(0);
		cookie.setPath(uri);
		response.addCookie(cookie);
	}
}


你可能感兴趣的:(Web,MyEclipse,servlet,qq)