首页 > 代码库 > Servlet第六课:Cookie的使用

Servlet第六课:Cookie的使用

目标规划:

通过这一节课,我们可以懂得如何使用Cookie,以及如何获取Cookie中的内容。

Cookie的详细概述。

1. Cookie 是保存在客户端的一个“键-值”对,用来标识用户的一些信息。

2. Cookie的应用
–在电子商务会话中标识用户
–对站点进行定制
–定向广告
3. 调用Cookie的构造函数,给出cookie的名称和cookie的值,二者都是字符串
Cookie c = new Cookie("userID", "a1234");
4. 如果要告诉浏览器将cookie存储到磁盘上,而非仅仅保存在内存中,使用setMaxAge (参数为秒数)
c.setMaxAge(60*60*24*7); // One week
5. 将Cookie放入到HTTP响应
response.addCookie(c);


6. 调用request.getCookies 获得这会得到Cookie对象组成的数组,在这个数组中循环,调用每个对象的getName,直到找到想要的cookie为止。

7.实例,创建cookie

我们首先创建一个Cookie信息:

核心代码:

Cookie c = new Cookie("goxuexi", "www.goxuexi.com");
		c.setMaxAge(60*60*24*7);
		response.addCookie(c);

全部代码:TestCookieServlet.java

package com.goxuexi.demo;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TestCookieServlet
 */
@WebServlet("/TestCookieServlet")
public class TestCookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestCookieServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Cookie c = new Cookie("goxuexi", "www.goxuexi.com");
		c.setMaxAge(60*60*24*7);
		response.addCookie(c);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

02.写一个获取Cookie的代码:


TestCookie.java

核心代码:

Cookie[] cs =  request.getCookies();
		for (Cookie c : cs) {
			System.out.println(c.getName()+":"+c.getValue());
		}

全部代码:

package com.goxuexi.demo;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TestCookie
 */
@WebServlet("/TestCookie")
public class TestCookie extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestCookie() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Cookie[] cs =  request.getCookies();               if(cs != null)                for (Cookie c : cs) {
			System.out.println(c.getName()+":"+c.getValue());
		}                 }                   }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

8.实例-使用cookie检测初访者

//使用cookie检测初访者   
	String result=null;    
        boolean newUser = true;    
        Cookie[] cookies = request.getCookies();    
        if(cookies!=null){    
                for(int i=0;i<cookies.length;i++){    
                        Cookie c = cookies[i];    
                        if((c.getName().equals("repeatVisitor"))&&(c.getValue().equals("yes"))){    
                        	newUser = false;    
                            break;    
                        }    
                }    
        } 
        
	if (newUser) {
		Cookie returnVisitorCookie = new Cookie("repeatVisitor", "yes");
		returnVisitorCookie.setMaxAge(60 * 60 * 24 * 365);
		response.addCookie(returnVisitorCookie);
		result = "Welcome Aboard";
	} else {
		result = "Welcome Back";
	}
	System.out.println(result);