zoukankan      html  css  js  c++  java
  • cookie学习

    /**
    在服务器中的Servlet判断是否有一个名为lastTime的cookie
    1. 有:不是第一次访问
    1. 响应数据:欢迎回来,您上次访问时间为:2018年6月10日11:50:20
    2. 写回Cookie:lastTime=2018年6月10日11:50:01
    2. 没有:是第一次访问
    1. 响应数据:您好,欢迎您首次访问
    2. 写回Cookie:lastTime=2018年6月10日11:50:01

    了解一下
    URLEncoder编码和URLDecoder解码,都需要使用一个变量来接收

    */

    @WebServlet("/cookieDemo")
    public class CookieDemo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //设置响应的消息体的数据格式以及编码
    response.setContentType("text/html;charset=utf-8");
    boolean flag=false;
    Cookie[] cookies = request.getCookies();


    if (cookies!=null&&cookies.length>0){
    for (Cookie cookie : cookies) {
    String name = cookie.getName();

    if ("lastTime".equals(name)){
    //再次光临
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    String str_date = sdf.format(date);
    str_date=URLEncoder.encode(str_date,"utf-8");

    flag=true;
    String value = cookie.getValue();
    value =URLDecoder.decode(value,"utf-8");
    response.getWriter().write("<h1>再次光临,你上次登录的时间是:"+value+"</h1>");

    cookie.setValue(str_date);
    cookie.setMaxAge(60*60*24*30);
    response.addCookie(cookie);
    break;
    }
    }
    }

    if(cookies==null||cookies.length==0||flag==false){
    //第一次
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    String str_date = sdf.format(date);
    System.out.println("编码前:" + str_date);
    str_date =URLEncoder.encode(str_date,"utf-8");
    System.out.println("编码后:" + str_date);

    Cookie cookie = new Cookie("lastTime",str_date);
    cookie.setMaxAge(60*60*24*30);
    response.addCookie(cookie);
    str_date =URLDecoder.decode(str_date,"utf-8");
    response.getWriter().write("<h1>你好,欢迎首次登录 : "+str_date+"</h1>");
    }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);
    }
    }
  • 相关阅读:
    电源积累
    电感的分类及作用
    电容退耦原理分享
    电容选型
    上拉电阻
    LVTTL与LVCMOS区别
    可重入函数与不可重入函数
    永不改变的PCB设计黄金法则
    os_cpu_a.asm
    [原创]Getting Started with Skywalking
  • 原文地址:https://www.cnblogs.com/shiguanzui/p/11714209.html
Copyright © 2011-2022 走看看