zoukankan      html  css  js  c++  java
  • Jsp--Cookie

    什么是Cookie

       Cookie翻译成中文是小甜点,小饼干的意思。在HTTP中它表示服务器送给客户端浏览器的小甜点。

    其实Cookie就是一个键和一个值构成的,随着服务器端的响应发送给客户端浏览器。

    然后客户端浏览器会把Cookie保存起来,当下一次再访问服务器时把Cookie再发送给服务器。

    并会标注出Cookie的来源(哪个服务器的Cookie)

    当客户端向服务器发出请求时会把所有这个服务器Cookie包含在请求中发送给服务器,这样服务器就可以识别客户端了

    注意: Cookie不能跨浏览器,

    IE浏览器有IE浏览器的Cookie,   Chrome浏览器有Chrome的cookie, IE浏览器使用Chrome浏览器的存放cookie

    Cookie的覆盖

      如果服务器端发送重复的Cookie那么会覆盖原有的Cookie

    例:第一个请求服务器端发送的Cookie是:Set-Cookie: a=A;

    第二请求服务器端发送的是:Set-Cookie: a=AA,那么客户端只留下一个Cookie,即:a=AA。

    代码实现:

    创建cookie

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //1、创建一个cookice对象
            Cookie a = new Cookie("aaa","123");
            //设置cookie存在时间为7天
            a.setMaxAge(7*24*60*60);
            //更改储存地址setpath、不写默认为项目名
                    //request.getContextPath()当前项目名+访问的servlet后加上test
            a.setPath(request.getContextPath()+"/test");
            //将cookie相应的硬盘中
            response.addCookie(a);
        }    

    取值

        //将本项目中的所有cookie拿到
            Cookie[] cookie = request.getCookies();
            //遍历
            if(cookie != null){
                for (int i = 0; i < cookie.length; i++) {
                    Cookie c = cookie[i];
                    System.out.println(c.getName()+"-->"+c.getValue());
                }
            }

    Cookie常用方法

    1、Cookie的构造方法

    Cookie cookie = new Cookie(String name,String value);

    2、获取cookie的value    :getValue()

    3、修改cookie的value    :setValue()

    4、获取cookie的name    :getName()

    5、设置cookie存放时间, 默认单位为妙    setMaxAge(int expiry)  --即cookie的生命

    •    0: 立即删除cookie
    •   -1: 默认值, cookie存在客户端内存, 当浏览器关闭的时候, cookie清除
    •   >0:  存放时间  60  表示cookie存放60秒, 一旦到达60秒, 浏览器自动删除cookie

    6、设置cookie访问的路径  : setPath()   

      cookie.setPath(request.getContextPath()+"/servlet");

    •    不写默认为本项目
    •  setPath(/)   :为所有的项目都可以拿到这个cookie

    中文传值的编码与解码

    • 编码:URLEncoder.encode(String,"编码格式");
    • 解码:URLDecoder.decode(String,"编码格式");
    代码实现:
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Cookie c = new Cookie("test",URLEncoder.encode("中国", "UTF-8"));
            response.addCookie(c);
        }
    <body>
        <%
            Cookie[] cookies = request.getCookies();
            if(cookies != null){
                for(int i =0 ; i< cookies.length;i++){
                    if(cookies[i].getName().equals("test")){
                        out.print(URLDecoder.decode(cookies[i].getValue(),"UTF-8"));
                    }
                }
            }
        %>
    </body>

     案例:实现历史记录

    jsp页面

    <body>
        <%
            String path = request.getContextPath();
        %>
    
        <h1>商品列表</h1>
        <a href="<%=path%>/HistoryServlet?name=ThinkPad">ThinkPad</a>
        <br />
        <a href="<%=path%>/HistoryServlet?name=Lenovo">Lenovo</a>
        <br />
        <a href="<%=path%>/HistoryServlet?name=Apple">Apple</a>
        <br />
        <a href="<%=path%>/HistoryServlet?name=HP">HP</a>
        <br />
        <a href="<%=path%>/HistoryServlet?name=SONY">SONY</a>
        <br />
        <a href="<%=path%>/HistoryServlet?name=ACER">ACER</a>
        <br />
        <a href="<%=path%>/HistoryServlet?name=DELL">DELL</a>
        <br />
        <hr/>
        <h1>历史记录</h1>
        <!-- 从cookie中获取数据并显示 -->
        <%
            String nameValue = "";
            Cookie[] cookies = request.getCookies();
            if(cookies != null){
                for (int i = 0; i < cookies.length; i++) {
                    cookies[i].equals("goodName");
                    nameValue = cookies[i].getValue();
                }
            }
            out.print(nameValue);
        %>
    </body>
    View Code

    servlet页面

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //1、编码处理
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;UTF-8");
            //2、获取请求数据
            String name = request.getParameter("name");
            //3、业务代码
            //获取cookie的数据
            //返回name为goodName的值
            String nameValue = null;
            //
            String listStr = name;
            Cookie[] cookies = request.getCookies();
            if(cookies != null){
                for (int i = 0; i < cookies.length; i++) {
                    if(cookies[i].getName().equals("goodName")){
                        nameValue = cookies[i].getValue();
                    }
                }
            }
            //将cookie转成集合,ArrayList
            if(nameValue != null){
                String[] goods = nameValue.split(",");
                //存在toString中有空格,去除
                for (int i = 0; i < goods.length; i++) {
                    goods[i] = goods[i].trim();
                }
                //Arrays.asList(goods)转成的集合是只读的,创建一个新的list
                List<String> list = new ArrayList<>(Arrays.asList(goods));
                //判断是否存在,存在remove后再添加
                if(list.contains(name)){
                    list.remove(name);
                }
                //不管是否存在都要加入list中
                list.add(name);
                //将list转为字符串
                listStr = list.toString();
                //去除toString前后的【】
                listStr = listStr.substring(1,listStr.length()-1);
                }
            //创建一个Cookie对象,并设置属性
            Cookie c = new Cookie("goodName",listStr);
            //设置存活时间
            c.setMaxAge(24*60*60);
            //响应cookie到浏览器
            response.addCookie(c);
            
            //4、响应页面
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
    View Code

     由于cookie版本问题

    版本0 : 由Netscape公司制定的,也被几乎所有的浏览器支持。Java中为了保持兼容性, 目前只支持到版本0, Cookie的内容中不能空格,方括号,圆括号,等于号(=),逗号,双引号,斜杠,问号,@符号,冒号,分号。

    版本1 : 根据RFC2109文档制定的。放宽了很多限制。版本0中所限制的字符都可以使用。但为了保持兼容性,程序开发者都会尽量避免使用这些特殊字符。
    servlet兼容代码更改

    改为手动传值,将上面的去除空格循环可以删除。。。
    //listStr = list.toString();
                //去除toString前后的【】
                //listStr = listStr.substring(1,listStr.length()-1);
                //由于cookie兼容版本,讲分割符改为#
                //提升效率使用StringBuffer
                StringBuffer sb = new StringBuffer();
                for (String string : list) {
                    sb.append(string+"#");
                }
                //去除最后一个#
                sb.deleteCharAt(sb.length()-1);
                listStr = sb.toString();
                }
    View Code
  • 相关阅读:
    Shell 批量搜索关键词并保存结果到文件中(数组、循环)
    解决tensorflow的Session Exception问题
    解决h5py的FutureWarning问题
    【转】Ubuntu16.04安装WPS
    [Linux] 随机切分文件内容
    [Python] 动态函数调用(通过函数名)
    [Python] dict字典的浅复制与深复制
    基于sklearn进行文本向量化
    Asp.Net MVC SingleServiceResolver类剖析
    Asp.Net MVC 高级特性(附带源码剖析)
  • 原文地址:https://www.cnblogs.com/64Byte/p/12878238.html
Copyright © 2011-2022 走看看