首页 > 编程知识 正文

提取cookies是什么意思,cookies的设置与读取

时间:2023-05-06 08:03:27 阅读:216894 作者:4847

1.设置cookie到客户端
Cookie c1 = new Cookie("username","hzh");
response.addCookie(c1);

Cookie c2 = new Cookie("password","123");
//设置生命周期为1小时,秒为单位
c2.setMaxAge(3600);
response.addCookie(c2);

response.getWriter().print("ok");

查看此时的cookie文件,发现只写入了password,因为此时未给 username设置生命周期,它还在客户端的内存中,并为写到文件中(此时客户端关闭此浏览器窗口,就丢失了),想写到客户端,需要加入c1.setMaxAge(3600)在 response.addCookie(c1);之前

以下是写入我电脑中的cookie





2.读取cookie文件

Cookie[] cookies = request.getCookies();
for(Cookie c :cookies ){
System.out.println(c.getName()+"--->"+c.getValue());
}

控制台输出结果如下:
username--->hzh
password--->123
JSESSIONID--->33BEAF95C526E0DDCF6A64990E533845


注意:
1.服务器可以向客户端写内容, 只能是文本内容
2.客户端可以阻止服务器写入,禁用cookies
3.只能读取自己webapp写入的东西
应用:将重要信息保存到cookie中,下一次用户请求服务,可从cookies中取得想要的值。 如:if(custId == 0){
        custId = Long.parseLong(String.valueOf(CookieUtils.getCookieValue(request, "custId", "0")));
        }
方法: public static String getCookieValue(HttpServletRequest request, String cookieName, String defaultValue)
    {
        String str = defaultValue;
        Cookie cookieList[] = request.getCookies();
        if(cookieList != null && cookieName != null)
        {
            for(int i = 0; i < cookieList.length; i++)
            
                try
                {
                    if(!cookieList[i].getName().equals(cookieName))
                        continue;
                    str = URLDecoder.decode(cookieList[i].getValue(), STORAGE_ENCODING);
                    break;
                }
                catch(UnsupportedEncodingException uee)
                {
                    uee.printStackTrace();
                }


        }
        return str;
    }

/**
* 设置cookie

* @param response
* @param name
*            cookie名字
* @param value
*            cookie值
* @param maxAge
*            cookie生命周期 以秒为单位
*/
public void addCookie(HttpServletResponse response, String name,
String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
if (maxAge > 0)
cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。