1. 程式人生 > >登入記住功能,資訊儲存到Cookie

登入記住功能,資訊儲存到Cookie

 

儲存到cookie時,中文和部分符號會亂碼。

value要用URLEncoder.encode(value, "UTF-8")編碼;取值時用URLDecoder.decode(cookie.getValue(), "UTF-8")解碼

 Cookie工具類

package orglizyuu.util;

import java.net.URLEncoder;

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

/**
 * Cookie工具類
 * 
 */
public class CookieUtil {

    private CookieUtil() {
    }

    /**
     * 新增cookie
     * 
     * @param response
     * @param name
     * @param value
     * @param maxAge
     */
    public static void addCookie(HttpServletRequest request ,HttpServletResponse response, String name, String value, int maxAge) {
       try {
    	   Cookie cookie = getCookieByName(request, name);
    	   if(cookie == null) {
    		   cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
    	   }
           cookie.setPath("/");//設定作用域
           if (maxAge > 0) {
               cookie.setMaxAge(maxAge);//設定cookie存活時間,eg:記住3天--60*60*24*3
           }
           response.addCookie(cookie);
	} catch (Exception e) {
		e.printStackTrace();
	}
    }

    /**
     * 刪除cookie
     * 
     * @param response
     * @param name
     */
    public static void removeCookie(HttpServletResponse response, String name) {
        Cookie uid = new Cookie(name, null);
        uid.setPath("/");
        uid.setMaxAge(0);
        response.addCookie(uid);
    }

    /**
     * 獲取cookie值
     * 
     * @param request
     * @return
     */
    public static Cookie getCookieByName(HttpServletRequest request,String cookieName) {
        Cookie cookies[] = request.getCookies();
        if(cookies==null){
        	return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                return cookie;
            }
        }
        return null;
    }
}