Cookie工具类

package com.rabbit.util;

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

/**
 * Created by vip on 2017/12/29.
 */
public class CookieUtil {

    private CookieUtil() {}//私有无参构造

    private HttpServletRequest req;//请求

    private HttpServletResponse resp;//响应

    private static final String RESULT_NULL = null;//结果null

    private CookieUtil(HttpServletRequest req, HttpServletResponse resp) {
        this.req = req;
        this.resp = resp;
    }

    public static CookieUtil newInstant(HttpServletRequest req, HttpServletResponse resp) {
        return new CookieUtil(req, resp);
    }

    /**
     * 获取所有Cookie
     * @return
     */
    public Cookie[] getAllCookie() {
        return req.getCookies();
    }

    /**
     * 获取指定名字的Cookie
     * @param name
     * @return
     */
    public Cookie getCookieByName(String name) {
        requiredNotNull(name);
        Cookie cookie = null;
        for (Cookie c : this.getAllCookie()) {
            if (c.getName().equals(name)) {
                return c;
            }
        }
        return cookie;
    }

    /**
     * 添加Cookie到Response中
     * @param name
     * @param value
     * @return
     */
    public Cookie setCookieToResponse(String name, String value) {
        Cookie cookie = new Cookie(name, value);
        resp.addCookie(cookie);
        return cookie;
    }

    /**
     * 获取指定Cookie的名称
     * @param name
     * @return
     */
    public String getCookieValue(String name) {
        Cookie cookie = this.getCookieByName(name);
        if (isNull(cookie)) {
            return RESULT_NULL;
        }
        return cookie.getValue();
    }

    /*
    校验参数不能为null
     */
    private void requiredNotNull(Object o) {
        if (o == null) {
            throw new NullPointerException();
        }
    }

    /*
    校验是否为null
     */
    private boolean isNull(Object o) {
        return o == null;
    }

}

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: Age of Ai 设计师: meimeiellie
应支付0元
点击重新获取
扫码支付

支付成功即可阅读