Cookie基本應用

heinika1476775901521發表於2017-12-14

在程式裡怎麼儲存使用者的資料? 資料存在客戶端:cookie 可以用購物車的功能類比。 cookie是客戶端技術,程式把每個使用者的資料以cookie的形式寫給使用者各自的瀏覽器。當使用者再去訪問伺服器中的web資源時,就會帶著各自的資料去。這樣web資源處理的就是使用者各自的資料了。

下面寫一個簡單的例子,使用cookie顯示上一次的訪問時間:

//        顯示上一次的訪問時間
private void showLastAccessTime(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print("您上次訪問的時間是:");

        //獲得使用者的時間cookie
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if(cookies[i].getName().equals("lastAccessTime")){
                long cookieValue = Long.parseLong(cookies[i].getValue());
                SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
                Date date = new Date(cookieValue);
                out.print(format.format(date));
            }
        }

        //給使用者返回最新的訪問時間
        Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
        cookie.setMaxAge(1*30*24*3600);
        cookie.setPath("/cookies");
        response.addCookie(cookie);
    }
複製程式碼

Cookie細節:

  1. Cookie是map
  2. web站點可以傳送多個cookie,瀏覽器可儲存多個cookie
  3. 瀏覽器一般可存放300個cookie,每個站點最多存放20個。每個cookie的大小限制為4kb。
  4. 如果建立一個cookie傳送給瀏覽器,預設情況是一個會話級別的cookie,使用者退出瀏覽器後即被刪除。若希望將瀏覽器儲存到硬碟上,需要設定maxAge,並給出一個以秒為單位的時間。設為0,則是刪除該cookie。
  5. 注意,刪除cookie時path必須一致,否則不會刪除。

刪除cookie:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
    cookie.setMaxAge(0);
    cookie.setPath("/cookies");
    response.addCookie(cookie);
    response.sendRedirect("/cookies");
}
複製程式碼

下面是一個使用cookie完成購物車的例項:

首頁

/**
 * Created by yun on 2017/5/6.
 * 代表購物車網站首頁
 */
public class CookieDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //輸出網站所有商品
        out.write("本網站有如下商品:<br/>");
        Map<String, Book> map = DB.getAll();
        for (Map.Entry<String, Book> entry : map.entrySet()) {
            Book book = entry.getValue();
            out.print("<a href='/CookieDemo2?id=" + book.getId() + "' target='_blank'>" + book.getName() + "</a><br/>");
        }


        //顯示使用者曾經看到過的商品
        out.write("<br/>"+"您曾經看過如下商品有如下商品:<br/>");
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if(cookies[i].getName().equals("bookHistory")){
                String[] ids = cookies[i].getValue().split("a"); //轉義,是為了防止,和正規表示式中的定義衝突
                for(String id:ids){
                    Book book = (Book) DB.getAll().get(id);
                    out.print(book.getName()+"</br>");
                }
            }
        }
    }
}

class DB {
    private static LinkedHashMap<String,Book> map = new LinkedHashMap();  //連結串列map,方便按序列輸出

    static {
        map.put("1", new Book("1", "heinika的程式設計之路", "陳利津", "一場有趣的旅程!"));
        map.put("2", new Book("2", "javaweb開發", "張孝祥", "好書"));
        map.put("3", new Book("3", "全棧工程師之路", "Terry", "全棧!!全棧!!"));
        map.put("4", new Book("4", "shell大全", "陳利津", "一場有趣的旅程!"));
        map.put("5", new Book("5", "heinika的成神之路", "陳利津", "一場有趣的旅程!"));
    }

    public static Map<String,Book> getAll() {
        return map;
    }
}

class Book {
    private String id;
    private String name;
    private String author;
    private String description;

    public Book() {
    }

    public Book(String id, String name, String author, String description) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.description = description;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}
複製程式碼

詳情頁

/**
 * Created by yun on 2017/5/6.
 * 物品詳情頁
 */
public class CookieDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //根據使用者帶貨來的id,顯示商品的詳細資訊
        String id = request.getParameter("id");
        Map<String, Book> map = DB.getAll();
        Book book = map.get(id);
        PrintWriter out = response.getWriter();
        out.print(book.getId() + "<br/>");
        out.print(book.getName() + "<br/>");
        out.print(book.getAuthor() + "<br/>");
        out.print(book.getDescription() + "<br/>");

        //構建cookie,寫回給瀏覽器
        String cookieValue = buildCookie(id, request);
        Cookie cookie = new Cookie("bookHistory", cookieValue);
        cookie.setMaxAge(1 * 30 * 24 * 3600);
        cookie.setPath("/");
        response.addCookie(cookie);
        out.print("<a href='/CookieDemo1'>返回首頁</a>");
    }

    private String buildCookie(String id, HttpServletRequest request) {
        //bookHistory=null          1            1
        //bookHistory=2,1,5         1            1,2,5
        //bookhistory=2,5,4         1            1,2,5
        //bookHistory=2,5           1            1,2,5
        Cookie[] cookies = request.getCookies();
        String bookHistory = null;
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equals("bookHistory")) {
                bookHistory = cookies[i].getValue();
            }
        }

        if (bookHistory == null) {
            return id;
        }

        String[] ids = bookHistory.split("a");
        LinkedList<String> idList = new LinkedList(Arrays.asList(ids));   //為增刪改查提高效能
        if (idList.contains(id)) {
            idList.remove(id);
        } else {
            if (idList.size() == 3) {
                idList.removeLast();
            }
        }
        idList.addFirst(id);
        StringBuffer sb = new StringBuffer();
        for (String bid : idList) {
            sb.append(bid + "a");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }
}
複製程式碼

相關文章