码迷,mamicode.com
首页 > 其他好文 > 详细

cookie 案例 记住上一次的访问时间

时间:2020-03-10 01:07:03      阅读:49      评论:0      收藏:0      [点我收藏+]

标签:value   post   utf-8   equal   imp   bre   row   doget   enc   

  1. 需求:记住上一次的访问时间
    1. 第一次访问Servlet 提示 欢迎首次访问
    2. 之后的访问 都提示 您上次的访问时间为:“”“”“”“”“”;
  2. 分析:
    public class cookieServlet4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html;charset=utf-8");//设置消息体的数据格式以及编码

    Cookie[] cs = request.getCookies();

    if (cs!=null) {

    int i =0;

    for (Cookie c : cs) {

    if((c.getName()).equals("lasttime"))
    {
    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");//URL编码

    System.out.println("编码后"+str_date);

    String value = c.getValue();

    //URL解码

    System.out.println("解码前:"+value);

    value = URLDecoder.decode(value,"utf-8");

    response.getWriter().write("欢迎回来 你上次的访问时间是:"+value);

    c.setValue(str_date);
    //设置存活时间

    c.setMaxAge(60 * 60);

    response.addCookie(c);


    break;

    }else if (cs.length==++i){//所有的cookie都不是last time 添加一个 name 为lasttime 的

    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");

    Cookie cookie = new Cookie("lasttime",str_date);

    cookie.setMaxAge(60 * 60); //设置存活时间

    response.addCookie(cookie);

    response.getWriter().write("欢迎首次访问");


    }


    }
    }





    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);
    }
    }
  3. URLEncoder.encode(str_date,"utf-8"); 编码 解码为
    URLDecoder.decode(value,"utf-8"); 返回字符串类型

 

cookie 案例 记住上一次的访问时间

标签:value   post   utf-8   equal   imp   bre   row   doget   enc   

原文地址:https://www.cnblogs.com/yitaqiotouto/p/12452752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!