效果如下图所示:
详细代码如下:
package star.july;
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 CookieServletDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//输出中文问题
response.setContentType("text/html;charset=utf-8");
//生成当前时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String curTime = format.format(new Date());
//获取从浏览器发过来的cookie
Cookie[] cookies = request.getCookies();
String lastTime = null;
//如果不为空,就遍历输出cookie
if(cookies != null){
for(Cookie c : cookies){
if(c.getName().equals("lastTime")){
lastTime = c.getValue();
response.getWriter().write("你好,你的上一次浏览时间是:"+ lastTime);
c.setValue(curTime);
c.setMaxAge(Integer.MAX_VALUE);
response.addCookie(c);
break;
}
}
}
if(cookies == null || lastTime == null){
//创建一个cookie对象
Cookie cookie = new Cookie("lastTime",curTime);
cookie.setMaxAge(Integer.MAX_VALUE);
response.getWriter().write("这是你的第一次访问,当前时间是:"+ curTime);
response.addCookie(cookie);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}