码迷,mamicode.com
首页 > 其他好文 > 详细

Cookie 和Session

时间:2018-07-13 22:15:30      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:except   tco   open   分享图片   读取   charset   bubuko   技术分享   one   

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

标签:except   tco   open   分享图片   读取   charset   bubuko   技术分享   one   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!