当用户请求LastAccessServlet 时,服务器会调用HTTPServletResponse接口的addCookie(Cookie cookie)方法,该方法会在发送给浏览器的HTTP响应消息中增加一个Set-Cookie头字段,将新创建的Cookie对象作为Set-Cookie头字段的值传递给浏览器。
LastAccessServlet类的具体实现如下:
package cn.itcast.chapter06.cookie.example;
import java.io.IOException;
import java.text.SimpleDateFormat;
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 LastAccessServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//指定服务器输出内容的编码方式UTF-8
response.setContentType("text/html;charset=utf-8");
/*
* 设定一个cookie的name:lastAccessTime
* 读取客户端发送cookie获得用户上次的访问时间显示
*/
String lastAccessTime = null;
//获取所有的cookie,并将这些cookie存放在数组中
Cookie[] cookies = request.getCookies();
for(int i=0; cookies != null && i<cookies.length; i++) {
//显然,第一次访问时,下面if语句里不会找到"lastAccess"键
if("lastAccess".equals(cookies[i].getName())) {
//如果cookie的名称为lastAccess,则获取该cookie的值
lastAccessTime = cookies[i].getValue();
break;
}
}
//判断是否存在名称为lastAccess的cookie
if(lastAccessTime==null) {
response.getWriter().print("您是首次访问本站!!!");
}else {
response.getWriter().print("您上次的访问时间是:" + lastAccessTime);
}
//创建cookie,将当前时间作为cookie的值发送给客户端
String currenttime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
.format(new Date());
Cookie cookie = new Cookie("lastAccess",currenttime);
cookie.setMaxAge(60);
//将Cookie的有效时间为1分钟
//发送cookie
response.addCookie(cookie);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}