js java操作COOKIE__js

來源:互聯網
上載者:User

document.cookie="info="+name+","+passw +";";  //  儲存cookie

 var info = document.cookie.split(";") ;                         //  讀取cookie

   

   ① js 中cookie是以“;”為結束標誌的,表示cookie中一個資料的結束。

   ②在一個cookie檔案中,cookie資料是以索引值對存在的,即:只允許一個同樣的名字存在。


js 讀取cookie:

//根據名字得到cookie的值
function getCookieVal(cookieName)
{
    var  search  =  cookieName  +  "="
    var  returnvalue  =  "";
    if  (document.cookie.length  >  0)
     {
        offset  =  document.cookie.indexOf(search);
        if  (offset  !=  -1)
        {
            offset  +=  search.length
            end  =  document.cookie.indexOf(";",  offset);
            if  (end  ==  -1)
                end  =  document.cookie.length;
            returnvalue=decodeURIComponent(document.cookie.substring(offset,  end));
        }
    }
    returnvalue = returnvalue.replace(/\"/g,'');   //將雙引號全部替換
    return  returnvalue;
}


java刪除cookie:

/**
     * 刪除cookie
     * @param cookieName
     * @param response
     * @param request
     */
    private void deleteCookie(HttpServletResponse response, HttpServletRequest request) {
          Cookie[] cookies = request.getCookies();
          if (cookies != null && cookies.length > 0) {
               for (int i = 0; i < cookies.length; i++) {
                   Cookie tmpCookie = new Cookie(cookies[i].getName(), cookies[i].getValue());
                   tmpCookie.setMaxAge(0);
                   tmpCookie.setPath("/");
                   response.addCookie(tmpCookie);
             }
          }
    }



java將值添加到COOKIE中:

Cookie cookie = new Cookie(cookie的名字,cookie的值);

cookie.setPath("/");
        cookie.setMaxAge(99999999);
        response.addCookie(cookie);



參考:http://mojianpo.iteye.com/blog/1137122

如需查看js寫cookie,在百度中搜尋下,反正是,java寫的cookie,js可以讀,js寫的,java也能讀到。。越來越喜歡用cookie了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.