1.什麼是 Cookie?
Cookie 實際上就是使用者通過瀏覽器訪問網站時,Web伺服器在使用者的硬碟上寫入的一個文字檔
它包含了使用者的某些資訊,它是以索引值對的形式儲存的
2. 使用到了 Cookie 的典型應用
下面這些都採用了 Cookie 技術,都是我們經常看到的
3. Cookie 編程
setPath 就是設定儲存的位置
Cookie 的構造方法的參數有兩個,都是 String 類型的,前面是 “鍵”,後面是“值”
setMaxAge 設定有效期間, getMaxAge 得到有效期間
response.add(...) 發送,也就是儲存 Cookie 對象
讀取 request.getCookies()
cookie.setValue()
4. Cookie的 缺陷
5. 編程執行個體
前台 cookieInput.htm
<html><head><title>cookie input page</title><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head><body>請輸入使用者名稱(英文或者數字)<br><form name="form1" action="/webproject3/servlet/setCookies"method="post"><table border="0"><tr><td>使用者名稱:</td><td><input type="text" name="username"></td></tr><tr><td colspan="2" align="center"><input name="submit" value="submit" type="submit"></td></tr></table></form></body></html>
後台
字串處理類
package webbook.util;public class StringUtil {/** * * 判斷輸入的字串參數是否為空白。 * @param args 輸入的字串 * @return true/false */public static boolean validateNull(String args) {if (args == null || args.length() == 0) {return true;} else {return false;}}/** * * 判斷輸入的字串參數是否為空白或者是"null"字元,如果是,就返回target參數,如果不是,就返回source參數。 */public static String chanageNull(String source, String target) {if (source == null || source.length() == 0 || source.equalsIgnoreCase("null")) {return target;} else {return source;}}/** * * 過濾<, >,\n 字元的方法。 * @param input 需要過濾的字元 * @return 完成過濾以後的字串 */public static String filterHtml(String input) {if (input == null) {return null;}if (input.length() == 0) {return input;}input = input.replaceAll("&", "&");input = input.replaceAll("<", "<");input = input.replaceAll(">", ">");input = input.replaceAll(" ", " ");input = input.replaceAll("'", "'");input = input.replaceAll("\"", """);return input.replaceAll("\n", "<br>");}}
設定 Cookie 的Servlet
package webbook.chapter6;import java.io.IOException;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Date;import webbook.util.StringUtil;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class SetCookiesServlet extends HttpServlet {private static final long serialVersionUID = 4400760543502956525L;public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String output = null;String username = request.getParameter("username");if (!StringUtil.validateNull(username)) {Cookie cookie1 = new Cookie("username", StringUtil.filterHtml(username));// cookie的有效期間為1個月cookie1.setMaxAge(24 * 60 * 60 * 30);SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");Cookie cookie2 = new Cookie("lastTime", sdf.format(new Date()));cookie2.setMaxAge(24 * 60 * 60 * 30);response.addCookie(cookie1);response.addCookie(cookie2);output = "本次登入時間與使用者名稱已經寫到Cookie中。<br><a href=\"/webproject3/servlet/getCookies \">查看Cookies</a>";} else {output = "使用者名稱為空白,請重新輸入。<br><a herf=\"/webproject3/cookieInput.htm\">輸入使用者名稱</a>";}response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();out.println("<html>");out.println("<head><title>set cookies </title></head>");out.println("<body>");out.println("<h2>" + output + "</h2>");out.println("</body>");out.println("</html>");out.flush();out.close();}}
得到 Cookie 的 Servlet
package webbook.chapter6;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class GetCookiesServlet extends HttpServlet {private static final long serialVersionUID = 4400760543502956525L;public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();out.println("<html>");out.println("<head><title>display login infomation</title></head>");out.println("<body>");out.println("<h2>從Cookie中獲得上次登入時間與使用者名稱</h2>");Cookie[] cookies = request.getCookies();Cookie cookie = null;for (int i = 0; i < cookies.length; i++) {cookie = cookies[i];if (cookie.getName().equals("username")) {out.println("使用者名稱:" + cookie.getValue());out.println("<br>");}if (cookie.getName().equals("lastTime")) {out.println("上次登入時間:" + cookie.getValue());out.println("<br>");}}out.println("</body>");out.println("</html>");out.flush();out.close();}}
測試結果: