Cookie的创建:
Cookie cookie = New Cookie(Cookie name,Cookie vlaue);
Response.addCookie(cookie)
注意:Cookie中不能存中文,默认Cookie是会话级别的
设置Cookie在客户端持久化的时间:cookie.setMaxAge(int seconds)
设置同名cookie,时间设置为0,代表删除该cookie,将path设置成与要删除的cookie一致
设置cookie的携带路径:cookie.setPath(String path) -------//客户端地址要加包名
注意:如果不设置携带路径,那么该cookie信息会在访问产生该cookie的 web资源所在的路径都携带cookie信息
服务器获取客户端携带的cookie:
获得客户端携带的cookie:
request.getCookies() //返回值是数组
通过cookie名称获得想要的cookie:
1)通过request获得所有的Cookie:
Cookie[] cookies = request.getCookies();
2)遍历Cookie数组,通过Cookie的名称获得我们想要的Cookie
for(Cookie cookie : cookies){
if(cookie.getName().equal(cookieName)){
String cookieValue = cookie.getValue();
}
}
记录用户的上次访问时间
package com.zys.lassAccessTime;
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 LastAccessTimeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获得当前时间
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String currentTime = format.format(date);
//1、创建Cookie记录当前的最新的访问时间
Cookie cookie = new Cookie("lastAccessTime",currentTime);
cookie.setMaxAge(60*10*500);
response.addCookie(cookie);
//2、获得客户端携带cookie ---- lastAccessTime
String lastAccessTime = null;
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie coo : cookies){
if("lastAccessTime".equals(coo.getName())){
lastAccessTime = coo.getValue();
}
}
}
response.setContentType("text/html;charset=UTF-8");
if(lastAccessTime==null){
response.getWriter().write("您是第一次访问");
}else{
response.getWriter().write("您上次登录的时间为:"+lastAccessTime);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
网友评论