package Cookie;
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.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
@WebServlet("/CookieTest")
public class CookieTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//获取所有的cookie
Cookie[] cookies = request.getCookies();
boolean flag = false;//没有cookie为lasttime
if(cookies.length>0&&cookies!=null){
for(Cookie ck:cookies){
if(ck.getName().equals("lasttime")){
flag = true;//有cookie为lasttime
//获取当前时间
Date time = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:hh:mm:ss");
String str = sdf.format(time);
//编码为utf-8格式
str = URLEncoder.encode(str,"utf-8");
ck.setValue(str);
ck.setMaxAge(60);
response.addCookie(ck);
String values = ck.getValue();
values = URLDecoder.decode(values,"utf-8");
response.getWriter().write("<h1>欢迎访问:"+values+"</h1>");
break;
}
}
}
if(cookies.length<0||cookies==null||flag==false){
Date d= new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:hh:mm:ss");
String str_date = sdf.format(d);
str_date = URLEncoder.encode(str_date,"utf-8");
Cookie ck = new Cookie("lasttime",str_date);
ck.setMaxAge(60);
response.addCookie(ck);
response.getWriter().write("<h1>欢迎首次访问</h1>");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
|
|