Cookie 一般可以使用于用来记录客户访问网页的时间,用户购物等。
客户端访问服务器,服务器返回一个Cookie用于便于下次客户继续访问。
Cookie cookie = new Cookie("bookHistory", cookieValue);
//设置cookie的存活时间,单位为秒
cookie.setMaxAge(1*30*24*3600);
//设置访问路径
cookie.setPath("/WebProject1");
response.addCookie(cookie);
cookieValue即为返回的数据,而bookHistory是用于下次客户访问时候用于区别不同cookie的标志。
客户端接收cookie,接收的cookie为一个数组
Cookie cookie[] = request.getCookies();
package cn.itcast.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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 CookieDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
pw.print("<a href='/WebProject1/servlet/CookieDemo2'>清除上次访问时间</a><br/>");
pw.print("你上次访问的时间:");
//获取用户的时间
Cookie cookie[] = request.getCookies();
for(int i=0;i<cookie.length&&cookie!=null;i++){
if(cookie[i].getName().equals("LastAccessTime")){
long cookieValue = Long.parseLong(cookie[i].getValue());
Date date = new Date(cookieValue);
pw.print(date.toLocaleString());
}
}
//给用户回送最新的访问时间
Cookie cookies = new Cookie("LastAccessTime", System.currentTimeMillis()+"");
cookies.setMaxAge(1*30*24*3600);
cookies.setPath("/WebProject1");
response.addCookie(cookies);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}