• JavaWeb11-Cookie


    应用场景:用于自动登录, 浏览记录, 购物车等等。

    使用Cookie步骤如下:

    1. 首先添加Cookie

      resp.addCookie(new Cookie("name", "张三"));
    2. 获取Cookie

      Cookie[] cookies = req.getCookies();
    3. 获取Cookie的name以及value

      String name = cookie.getName();
      String value = cookie.getValue();

    完整代码如下:

    public class CookieServlet extends HttpServlet {
       @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           req.setCharacterEncoding("utf-8");
           resp.setCharacterEncoding("utf-8");
           resp.setContentType("text/html;charset=utf-8");
           PrintWriter out = resp.getWriter();
           // 添加cookie
           resp.addCookie(new Cookie("name", "张三"));
           // 获取cookie, 并将其遍历出来
           Cookie[] cookies = req.getCookies();
           if(cookies != null) {
               for (Cookie cookie : cookies) {
                   out.write(cookie.getName() + cookie.getValue() + "<br/>");
              }
          }
      }
       @Override
       protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           doGet(req, resp);
      }
    }

    小案例:获取上一次的访问时间。

     @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           req.setCharacterEncoding("utf-8");
           resp.setCharacterEncoding("utf-8");
           resp.setContentType("text/html;charset=utf-8");
           PrintWriter out = resp.getWriter();
           Cookie[] cookies = req.getCookies();
           if(cookies != null) { // 如果cookie不为空输出上一次访问的时间
               for (Cookie cookie : cookies){
                   if (cookie.getName().equals("currentTime")){ // 获取下面添加的Cookie:currentTime属性
                       String value = cookie.getValue();
                       long time = Long.parseLong(value);
                       Date date = new Date(time);
                       out.write("上一次访问的时间" + date.toLocaleString());
                  }
              }
          }
           Cookie cookie = new Cookie("currentTime", System.currentTimeMillis() + "");// 访问时,添加一个访问的当前时间
           cookie.setMaxAge(10); // 还有一个设置最大有效时间
           resp.addCookie(cookie);
      }
       @Override
       protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           doGet(req, resp);
      }
    }
  • 相关阅读:
    xcode debug
    ios 使用Quartz 2D画虚线
    ios UIGestureRecognizer
    ios 实现带矩形框的屏幕截图
    ios UISegemetedControl
    centos最小安装之后无法使用ifconfig
    无线LoRa智能远传水表
    智能水表188协议汇总
    无线LoRa远传智能水表
    静电除尘器除尘原理
  • 原文地址:https://www.cnblogs.com/Patrick20726/p/13586387.html
Copyright © 2020-2023  润新知