1、分析
2、实现步骤
●设置浏览器响应内容类型和编码
●获取客户端携带的cookie
●判断key为time的cookie是否存在
●存在
■获取value值,响应给浏览器
■覆盖cookie,更新值
●不存在
■响应给浏览器,比如:“你是首次访问”
■创建cookie,并且发送cookie到客户端
3、代码实现
package com.bdit;
import javax.servlet.http.Cookie;
public class DBCookie {
public static Cookie getCookie(Cookie[] cookies,String cookiekey){
if(cookies!=null&&cookies.length>0){
for(Cookie cookie:cookies){
if(cookie.getName().equals(cookiekey)){
return cookie;
}
}
}
return null;
}
}
package com.bdit;
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;
import java.io.IOException;
import java.time.LocalDateTime;
@WebServlet(urlPatterns = {"/cookieServlet04"})
public class CookieServlet04 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 {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
Cookie key=DBCookie.getCookie(request.getCookies(),"key");
if(key!=null){
String result=key.getValue();
response.getWriter().print("你上次访问的时间是:"+result);
}else{
response.getWriter().print("<h2>第一次访问</h2>");
}
String date=LocalDateTime.now().toString();
Cookie cookie=new Cookie("key",date);
cookie.setPath(request.getContextPath());
cookie.setMaxAge(60*60*24*5);
response.addCookie(cookie);
}
}