Cookie基础操作工具类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Cookie基础操作工具类相关的知识,希望对你有一定的参考价值。

package com.core.util;

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

public class CookieUtil {

	private CookieUtil() {}
	
	public static final String COOKIE_PATH_ROOT = "/";

	public static Cookie createCookie(String key, String value, int maxAge) {
		Cookie cookie = new Cookie(key, value);
		cookie.setPath(COOKIE_PATH_ROOT);
		if (maxAge > 0) {
			cookie.setMaxAge(maxAge);
		}
		return new Cookie(key, value);
	}
	
	public void addCookie(HttpServletResponse response, Cookie cookie) {
		response.addCookie(cookie);
	}
	
	public static Cookie getCookie(HttpServletRequest request, String cookieName) {
		Cookie[] cookies = request.getCookies();
		if (null == cookies) {
			return null;
		}
		for (Cookie cookie : cookies) {
			if (cookieName.equals(cookie.getName())) {
				return cookie;
			}
		}
		return null;
	}
	
	public static String getCookieValue(HttpServletRequest request, String cookieName) {
		Cookie cookie = getCookie(request, cookieName);
		if (null != cookie) {
			return cookie.getValue();
		}
		return null;
	}
}

  

以上是关于Cookie基础操作工具类的主要内容,如果未能解决你的问题,请参考以下文章

自定义的操作Cookie的工具类

自定义的操作Cookie的工具类

java与javascript对cookie操作的工具类

Cookie工具类代码

elasticsearch代码片段,及工具类SearchEsUtil.java

Java Cookie工具类