Cookie入门实例

cookie介绍:Cookie通常用于网站记录客户的某些信息,比如客户的用户名、客户的喜好比如,上一次浏览的宝贝)等。一旦用户下次登录,网站可以获取到客户相关的信息,根据这些客户信息,网站可以对客户进行更友好的服务(比如,您浏览过的商品是哪些等)。session会随浏览器关闭而失效,但cookie会一直保存在客户端机器上,除非超出cookie的生命周期
 
一、增加cookie的步骤:(使用response对象)
    (1)创建cookie,构造器为 Cookie(java.lang.String name, java.lang.String value)

Constructs a cookie with the specified name and value.

 
java.lang.Object
  javax.servlet.http.Cookie
 (2)设置cookie生命周期,即该cookie在多长时间内有效  
public void setMaxAge(int expiry)
Sets the maximum age in seconds for this Cookie.
 (3)向客户端写cookie, response.addCookie(c)
void addCookie(Cookie cookie)
Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.
response对象:
    (1)、输出非字符内容:大部分时候,程序无须使用response来响应客户端请求,因为有个更简单的out对象,但out对象只能响应字符内容,假如需要在JSP页面中动态生成一副位图、或者输出一个PDF文档,只能用response对象
    (2)、重定向请求
    (3)、向客户端增加cookie
 

PS:response也是JSP内置的9大对象之一,对应于Servelt的对象为javax.servlet.http.HttpServletResponse

例1:addCookie.jsp

 1 <%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title>增加cookie</title> 
 5 </head>
 6 <body>
 7 <%
 8 //获取请求参数
 9 String name = request.getParameter("name");
10 //以获取到的请求参数为值,创建一个cookie对象
11 Cookie cookie = new Cookie("username", name);
12 //设置cookie对象的生成周期
13 cookie.setMaxAge(24*3600);
14 //向客户端增加cookie对象
15 response.addCookie(cookie);
16 %>
17 </form>
18 </body>
19 </html>

演示:访问http://localhost:8888/webDemo/jspObject/addCookie.jsp?name=wxdlut

当没有如下两行代码时结果如下:

12 //设置cookie对象的生成周期

13 cookie.setMaxAge(24*3600);

 

时间为2013-12-14 15:29,而cookie里的expires时间为2013-12-15 07:29GMT

 
二、读取cookie的步骤:使用request对象
Cookie[] getCookies()     request.getCookies()
        Returns an array containing all of the Cookie objects the client sent with this request. This method returns null if no cookies were sent.

例2:readCookies.jsp

 1 <%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title>读取cookie</title> 
 5 </head>
 6 <body>
 7 <%
 8 //获取本站在客户端上保留的所有cookie
 9 Cookie[] cookies = request.getCookies();
10 //遍历客户端上的每个cookie
11 for (Cookie c : cookies) {
12     out.println("name=" + c.getName() + ", value=" + c.getValue());
13 }
14 %>
15 </form>
16 </body>
17 </html>

演示:

posted on 2013-12-14 15:57  gogoy  阅读(516)  评论(0编辑  收藏  举报

导航