在现实生活中,cookie就相当于商场的会员卡,当你拥有会员卡之后,以后每次去商场只要拿出会员卡就行了。在web应用中,客户端第一次访问服务端的时候,cookie不存在,这时服务端会在响应信息中添加set-cookie的字段。以后客户端每次访问的时候,服务器都会把用户信息以cookie的形式响应给客户端。
下面是一个可以显示客户端上次访问时间的例子
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LastAccessServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//获取当前的时间 ,注意时间设置不能用空格,不然会一直显示第一个访问的时候
SimpleDateFormat Time = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss");
String current = Time.format(new Date());
String lastAccess = null;
//获取所有的Cookie,并将这些cookie存放在数组中
Cookie[] cookies = request.getCookies();
//遍历cookie数组
if (cookies!=null){
for (Cookie cookie : cookies) {
if (cookie.getName().equals("time")){
lastAccess = cookie.getValue();
break;
}
}
}
//判断是否存在名称为lastAccess的cookie
if (lastAccess == null ){
response.getWriter().print("这是你的第一次访问!..当前的时间为:"+current);
}else {
response.getWriter().print("hello! 你上次访问的时间 " + lastAccess +" .... 而当前网站的时间为"+current);
}
//创建cookie对象,将当前时间作为cookie的值加入到浏览器
Cookie cookie = new Cookie("time",current);
cookie.setMaxAge(60*60);
//将cookie加入浏览器中
response.addCookie(cookie);
}
}
Cookie[] cookies = request.getCookies(); 创建一个cookie数组,相当于客户端的cookie存放区,
lastAccess = cookie.getValue(); 得到cookie的信息
Cookie cookie = new Cookie("time",current); 客户端第一次访问服务器的时候,服务器给响应信息添加set-cookie, 参数名为“time” 以后每次客户端访问的时候,服务端都会知道是哪个用户发出的信息
cookie.setMaxAge(60*60); 设置cookie存放的过期时间,单位是秒
response.addCookie(cookie); 将cookie值响应给客户端