CookieHelper cook crud 工具类

package com.sd.sdactivity.utils;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class CookieHelper {

  /**

     * 设置cookie

     */

    public static void set(String cookieKey, String val, HttpServletResponse response) {

        Cookie cookie = new Cookie(cookieKey, val);

        //String url = request.getHeader("host");

 //url = NetHelper.GetMainDomain(url);



        //cookie.setDomain(url);

        cookie.setMaxAge(-1);

  cookie.setPath("/");

        response.addCookie(cookie);

    }

 /**

     * 获取cookie对象

     *

     * @param cookieKey

     * @param request

     * @return

     */

    public static Cookie get(String cookieKey, HttpServletRequest request) {

  Cookie[] cookies = request.getCookies();

        if (cookies != null) {

            for (Cookie cookie : cookies) {

                if (cookie.getName().toLowerCase()

                        .equals(cookieKey.toLowerCase())) {

                      return cookie;

                }

            }

        }

        return null;

    }

 /**

     * 获取cookie值

     *

     * @param cookieKey

     * @param request

     * @return

     */

  public static String getValue(String cookieKey, HttpServletRequest request) {

        Cookie cookie = get(cookieKey, request);

        if (cookie != null) {

            return cookie.getValue();

        } else {

  return null;

        }

    }

 /**

     * 移除COOKIE

     *

     * @param cookieKey

     * @param request

     * @param response

     */

  public static void remove(String cookieKey, HttpServletRequest request,

                              HttpServletResponse response) {

        Cookie cookie = get(cookieKey, request);

        if (cookie != null) {

  cookie.setValue(null);

            cookie.setMaxAge(0);

            response.addCookie(cookie);

        }

    }

}

你可能感兴趣的:(CookieHelper cook crud 工具类)