java 获取cookies

我是把保存读取写在工具类里面,优化cookie的时候就在工具类优化就好了,其实原理就那几行,主要就是在response写入cookie,resp.addCookie(new Cookie(key,value));这个代码那里都可以写,只要你拿的到response就可以了。

public class CookieUtil {

    /**
     * 保存Cookies
     * @param response
     * @param key
     * @param value
     * @param time
     * @param ip
     * @return
     */
    public static HttpServletResponse setCookie(HttpServletResponse response, String key, String value, int time,String ip) {
        // new一个Cookie对象,键值对为参数
        Cookie cookie = new Cookie(key, value);
        // tomcat下多应用共享
        cookie.setPath("/");
        //cookie.setDomain(ip);
        // 如果cookie的值中含有中文时,需要对cookie进行编码,不然会产生乱码.
        try {
            URLEncoder.encode(value, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //秒为单位
        cookie.setMaxAge(time);
        // 将Cookie添加到Response中,使之生效
        response.addCookie(cookie); // addCookie后,如果已经存在相同名字的cookie,则最新的覆盖旧的cookie
        return response;
    }

    /**
     * 将cookie封装到Map里面
     * @param request
     * @return
     */
    private static Map, Cookie> ReadCookieMap(HttpServletRequest request) {
        Map, Cookie> cookieMap = new HashMap, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
    /**
     * 根据名字获取cookie
     *
     * @param request
     * @param name
     *            cookie名字
     * @return
     */
    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        Map, Cookie> cookieMap = ReadCookieMap(request);
        if (cookieMap.containsKey(name)) {
            Cookie cookie = (Cookie) cookieMap.get(name);
            return cookie;
        } else {
            return null;
        }
    }

    /**
     * 删除无效cookie
     * @param request
     * @param response
     * @param deleteKey
     * @throws NullPointerException
     */
    private void delectCookieByName(HttpServletRequest request, HttpServletResponse response,String deleteKey) throws NullPointerException {
        Map, Cookie> cookieMap = ReadCookieMap(request);
        for (String key : cookieMap.keySet()) {
            if (key == deleteKey && key.equals(deleteKey)) {
                Cookie cookie = cookieMap.get(key);
                cookie.setMaxAge(0);//设置cookie有效时间为0
                cookie.setPath("/");//不设置存储路径
                response.addCookie(cookie);
            }
        }
    }
}

写入方式:(调用工具类接口传参就完事了)

//将userId,tiken存入cookie
CookieUtil.setCookie(response,"userId",userSession.getUser().getId().toString(),1800,userSession.getIp());

读取cookie有3种方式,反正我现在只知道3种:

//1.获取的是数组类型的cookie
Cookie[] cookies=request.getCookies();
//循环或者这么取都行
String cookie = request.getCookies()[0].getValue();
//2.使用自己封装好的的工具类
CookieUtil.getCookieByName(request,"userId");

3.如果你是spring boot,在需要使用cookie的方法下面使用注解@CookieValue,userId自动获取,name要对的上哦,完事!

@RequestMapping(value = "/isStore",method = RequestMethod.GET)
public ResponseEntity isStore(@CookieValue(value = "userId")String userId){


你可能感兴趣的:(java,Cookie)