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);
	}
}