首页 > 其他 > 详细

Cookie 和Session

时间:2018-07-13 22:08:09      阅读:160      评论:0      收藏:0      [点我收藏+]

1Cookie 的概念

Cookie就是若干组键值对。

服务器在响应头中以如下格式设置cookie

技术分享图片l

浏览器将cookie存储在本地,在以后的访问中,在请求中以如下形式发给服务器

技术分享图片

关键API

服务器写Cookie

Cookie c=new Cookie("id", "the id is legion");
esponse.addCookie(c);
//多个依次重复

服务器读cookie

//从请求头中获取cookie数组
Cookie[] cs=request.getCookies();
//对于数组中每一个Cookie,有getName 和getValue的方法
//分别获取键和值

例子:本例子AServlet写若干cookie,其中一个cookie有key为”id“,

BServlet试图读取该id 的值。

技术分享图片
//AServlet Get
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html;charset=utf-8");
        Cookie c=new Cookie("id", "the id is legion");
        response.addCookie(c);
        Cookie c2=new Cookie("something", "sskalsa");
        response.addCookie(c2);
        response.getWriter().print("i sent you an id in cookie");
        
    }

//BServlet Get
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html;charset=utf-8");
        Cookie[] cs=request.getCookies();
        if(cs!=null) {
            for(Cookie c:cs) {
                if(c.getName().equals("id")) {
                    String str="获取ID的值为"+c.getValue();
                    response.getWriter().print(str);
                }
            }
        }
    }
View Code

 

Cookie 和Session

原文:https://www.cnblogs.com/legion/p/9307483.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!