
1,判断来访者是否第一次
public class VistorTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
String msg = null;
boolean isNew = true;
PrintWriter out = resp.getWriter();
Cookie[] cookies = req.getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
Cookie cookie = cookies[i];
if(cookie.getName().equals("repeatVistor")&&
cookie.getValue().equals("yes")){
isNew=false;
break;
}
}
}
if(isNew){
Cookie c = new Cookie("repeatVistor", "yes");
c.setMaxAge(365*24*60*60);
resp.addCookie(c);
msg = "welcome aboard";
}
else
msg="welcome back";
out.write(msg);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}
}
会话Cookie与持续性cookie(区别就是是否设置了setMaxAge)
设置时间1小时
public class PesistAndTemp extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
for(int i=0;i<3;i++){
Cookie cookie=new Cookie("temp-cookie"+i, "cookie-value"+i);
resp.addCookie(cookie);
cookie = new Cookie("pesist-cookie-"+i, "pesis-vlaue"+i);
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
out.write("<p>active cookies</p>");
Cookie[] cookies=req.getCookies();
if(cookies==null){
out.write("<p>NO MATCHES</p>");
}
else{
for(int i=0;i<cookies.length;i++){
Cookie c = cookies[i];
out.write("<p>cookieName:"+c.getName()+" cookie-value:"+c.getValue());
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}
}
第一次访问
在同一会话中1小时内访问
首次访问一小时内另一个会话再次访问:
3。修改Cookie值:记录用户的访问计数:
public class CountVistor extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
boolean isFirst=true;
int count=1;
Cookie c;
Cookie[] cookies = req.getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
c = cookies[i];
if(c.getName().equals("accesscount")){
c = new Cookie("accesscount", String.valueOf(Integer.parseInt(c.getValue())+1));
c.setMaxAge(60*60);
resp.addCookie(c);
count =Integer.parseInt( c.getValue());
System.out.println("not first");
isFirst=false;
}
}
}
else if(isFirst){
c = new Cookie("accesscount", String.valueOf(count));
c.setMaxAge(60*60);
resp.addCookie(c);
System.out.println("first");
}
out.write("this is you "+count+" time vistor");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}
}
输出:this is you 36 time vistor