java cookie的編輯 修改 刪除等用法

來源:互聯網
上載者:User

Cookie是WEB伺服器通過瀏覽器儲存在WWW使用者端硬碟上的一個文字檔,這個文字檔中包含了文本資訊。

   文本資訊的內容以“名/值”對(key/value)的形式進行儲存。

   可以讓WEB開發人員通過程式讀寫這個文字檔。

   XP中儲存Cookie的目錄是“C://Documents and Settings使用者名稱Cookies”

Cookie的作用

   解決瀏覽器使用者與Web伺服器之間無狀態通訊。
//建立對象

import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

public class FetchCookie {
  public static void main(String args[]) throws Exception {
    String urlString = "http://www.111cn.net/58/";
    CookieManager manager = new CookieManager();
    CookieHandler.setDefault(manager);
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    Object obj = connection.getContent();
    url = new URL(urlString);
    connection = url.openConnection();
    obj = connection.getContent();
    CookieStore cookieJar = manager.getCookieStore();
    List<HttpCookie> cookies = cookieJar.getCookies();
    for (HttpCookie cookie : cookies) {
      System.out.println(cookie);
    }
  }
}

綜合執行個體

        Date date = new Date() ;

        Cookie c = new Cookie("lastVisited",date.toString()) ;

//設定有效時間  以s為單位

        c.setMaxAge(60) ;

//設定Cookie路徑和網域名稱

        c.setPath("/") ;

        c.setDomain(".zl.org") ;  //網域名稱要以“.”開頭

//發送Cookie檔案

        response.addCookie(c) ;

//讀取Cookie

        Cookie cookies[] = request.getCookies() ;

        Cookie c1 = null ;

        if(cookies != null){

            for(int i=0;i<cookies.length;i++){

               c1 = cookies[i] ;

               out.println("cookie name : " + c1.getName() + "   ") ;

               out.println("cookie value :" + c1.getValue() + "<br>");

            }

        }

  //修改Cookie

       Cookie cookies[] = request.getCookies() ;

       Cookie c = null ;

       for(int i=0;i<cookies.length;i++){

           c = cookies[i] ;

           if(c.getName().equals("lastVisited")){

              c.setValue("2010-04-3-28") ;

              c.setMaxAge(60*60*12) ;

              response.addCookie(c) ;     //修改後,要更新到瀏覽器中    

           }

       }

 

//刪除Cookie,(將Cookie的有效時間設為0)

   

    Cookie cookies[] = request.getCookies() ;

       Cookie c = null ;

       for(int i=0;i<cookies.length;i++){

           c = cookies[i] ;

           if(c.getName().equals("lastVisited")){

              c.setMaxAge(0);

              response.addCookie(c) ;

           }

       }

 

使用Cookie的注意事項
·Cookie的大小和數量是有限制的。

·Cookie在個人硬碟上所儲存的文本資訊是以明文格式進行儲存的,沒有任何的加密措施。

·瀏覽器使用者可以設定不使用Cookie。

5、執行個體:Servlet中的Cookie編

執行個體

import java.io.IOException;
import java.net.CookieHandler;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class Fetch5 {
  public static void main(String args[]) throws Exception {
    String urlString = "java.sun.com";
    CookieHandler.setDefault(new ListCookieHandler());
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    Object obj = connection.getContent();
    url = new URL(urlString);
    connection = url.openConnection();
    obj = connection.getContent();
  }
}

class ListCookieHandler extends CookieHandler {
  private List<Cookie> cookieJar = new LinkedList<Cookie>();

  public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
    List<String> setCookieList = responseHeaders.get("Set-Cookie");
    if (setCookieList != null) {
      for (String item : setCookieList) {
        Cookie cookie = new Cookie(uri, item);
        for (Cookie existingCookie : cookieJar) {
          if ((cookie.getURI().equals(existingCookie.getURI()))
              && (cookie.getName().equals(existingCookie.getName()))) {
            cookieJar.remove(existingCookie);
            break;
          }
        }
        cookieJar.add(cookie);
      }
    }
  }

  public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders)
      throws IOException {
    StringBuilder cookies = new StringBuilder();
    for (Cookie cookie : cookieJar) {
      // Remove cookies that have expired
      if (cookie.hasExpired()) {
        cookieJar.remove(cookie);
      } else if (cookie.matches(uri)) {
        if (cookies.length() > 0) {
          cookies.append(", ");
        }
        cookies.append(cookie.toString());
      }
    }

    Map<String, List<String>> cookieMap = new HashMap<String, List<String>>(requestHeaders);

    if (cookies.length() > 0) {
      List<String> list = Collections.singletonList(cookies.toString());
      cookieMap.put("Cookie", list);
    }
    System.out.println("CookieMap: " + cookieMap);
    return Collections.unmodifiableMap(cookieMap);
  }
}

class Cookie {

  String name;

  String value;

  URI uri;

  String domain;

  Date expires;

  String path;

  private static DateFormat expiresFormat1 = new SimpleDateFormat("E, dd MMM yyyy k:m:s 'GMT'",
      Locale.US);

  private static DateFormat expiresFormat2 = new SimpleDateFormat("E, dd-MMM-yyyy k:m:s 'GMT'",
      Locale.US);

  public Cookie(URI uri, String header) {
    String attributes[] = header.split(";");
    String nameValue = attributes[0].trim();
    this.uri = uri;
    this.name = nameValue.substring(0, nameValue.indexOf('='));
    this.value = nameValue.substring(nameValue.indexOf('=') + 1);
    this.path = "/";
    this.domain = uri.getHost();

    for (int i = 1; i < attributes.length; i++) {
      nameValue = attributes[i].trim();
      int equals = nameValue.indexOf('=');
      if (equals == -1) {
        continue;
      }
      String name = nameValue.substring(0, equals);
      String value = nameValue.substring(equals + 1);
      if (name.equalsIgnoreCase("domain")) {
        String uriDomain = uri.getHost();
        if (uriDomain.equals(value)) {
          this.domain = value;
        } else {
          if (!value.startsWith(".")) {
            value = "." + value;
          }
          uriDomain = uriDomain.substring(uriDomain.indexOf('.'));
          if (!uriDomain.equals(value)) {
            throw new IllegalArgumentException("Trying to set foreign cookie");
          }
          this.domain = value;
        }
      } else if (name.equalsIgnoreCase("path")) {
        this.path = value;
      } else if (name.equalsIgnoreCase("expires")) {
        try {
          this.expires = expiresFormat1.parse(value);
        } catch (ParseException e) {
          try {
            this.expires = expiresFormat2.parse(value);
          } catch (ParseException e2) {
            throw new IllegalArgumentException("Bad date format in header: " + value);
          }
        }
      }
    }
  }

  public boolean hasExpired() {
    if (expires == null) {
      return false;
    }
    Date now = new Date();
    return now.after(expires);
  }

  public String getName() {
    return name;
  }

  public URI getURI() {
    return uri;
  }

  public boolean matches(URI uri) {

    if (hasExpired()) {
      return false;
    }
    String path = uri.getPath();
    if (path == null) {
      path = "/";
    }

    return path.startsWith(this.path);
  }

  public String toString() {
    StringBuilder result = new StringBuilder(name);
    result.append("=");
    result.append(value);
    return result.toString();
  }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.