• 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);
    }
    }
  • 相关阅读:
    vue基础04计算属性
    vue基础01条件渲染
    vue基础14vuex
    其他03动态拼接地址,使用本地的图片不显示
    其他05vue中ref
    HTML基础02CSS
    其他12es6...运算符
    其他11依赖注入
    其他07插槽
    其他06js类型判断
  • 原文地址:https://www.cnblogs.com/shiguanzui/p/11714209.html
Copyright © 2020-2023  润新知