JavaWeb篇——Cookie讲解
程序员文章站
2024-02-04 13:36:04
...
Cookie讲解
- 从请求中拿到cookie信息
- 服务器响应给客户端cookie
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
//Cookie,服务器从客户端获取
Cookie[] cookies = req.getCookies();//获取cookie
//判断cookie是否为空
if (cookies!=null){
out.write("您上次访问的时间是:");
for(int i=0;i<cookies.length;i++){
Cookie cookie = cookies[i];
if (cookie.getName().equals("loginTime")){//获取cookie的key与设置的cookie的key进行比较
long loginTime = Long.parseLong(cookie.getValue());//获得cookie的value值
Date date = new Date(loginTime);
out.write(date.toLocaleString());
}
}
}else{
out.write("这是您第一次访问本站");
}
Cookie cookie = new Cookie("loginTime",System.currentTimeMillis()+"");//新建一个cookie值
cookie.setMaxAge(24*60*60);//设置cookie的有效期(24小时)
resp.addCookie(cookie);//响应给客户端的cookie
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
上一篇: lua学习之基础概念篇