01_7_cookies
1. cookies
1.1服务器可以向客户端写内容
1.2只能是文本内容
1.3客户端可以阻止服务器写入
1.4只能拿到自己webapp写入的东西
1.5Cookie分为两种
属于窗口/子窗口(放在内存中)
属于文本(有生命周期的)
1.6一个servlet/jsp设置的cookies能够被同一个路径下面或者子路径下面的servlet/jsp读到(路径 = URL)(路径 != 真实文件路径)
2. 测试类
SetCookies.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close();*/ for (int i = 0; i < 3; i++) { Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-P" + i); response.addCookie(cookie); cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); cookie.setMaxAge(3600); response.addCookie(cookie); } response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); out.print("<H1>设置Cookie</H1>6个Cookie<a href="ShowCookies">查看</a>"); }
ShowCookies.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); String title = "Active Cookies"; out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>获取客户端Cookie</TITLE></HEAD>"); out.println(" <BODY>"); out.print("<H1 ALIGN="CENTER">" + title + "</H1><table border=1 ALIGN="CENTER">" + "<tr><th>Cookie Name</th><th>Cookie Value</th>"); Cookie[] cookies = request.getCookies(); if (cookies != null) { Cookie cookie; for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; out.print("<tr><td>" + cookie.getName()+"</td><td>" + cookie.getValue() + "</td></tr>"); } } out.print("</table>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }