zoukankan      html  css  js  c++  java
  • 设置cookie

    使用servlet设置cookie, 一次设置一个cookie, 多个cookie可以多次设置

    @WebServlet(name = "TestCookie")
    public class TestCookie extends HttpServlet {
    
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            resp.setContentType("text/html;charset=utf-8");
            req.setCharacterEncoding("utf-8");
    
            //临时cookie, 重启浏览器时清除
            Cookie c1 = new Cookie("name", "Ryan");
            //定时cookie, 定时清除
            Cookie c2 = new Cookie("animei", "Naruto");
    
            //单位为秒, 30秒后清除该cookie
            c2.setMaxAge(30);
            //设置有效路径, 一般cookie在访问任何资源都会带, 但设置了有效路径之后, 在cookie有效时, 只有访问有效路径才会带
            c2.setPath("/myServlet/abc");
    
            resp.addCookie(c1);
            resp.addCookie(c2);
    
            resp.getWriter().write("请查看cookie");
        }
    }

    当浏览器访问该servlet时, cookie将写入浏览器中, 临时cookie写入缓存中, 定时cookie写入硬盘中

     只有在访问有效路径时, 请求头中才会带cookie:

  • 相关阅读:
    Business
    Triple Inversions
    protobuf
    16.04 ubuntu python3.6 install
    1.安装
    Tutorial2
    Tutorial1
    geometry_msgs的ros message 类型赋值
    UBUNTU QQ/TIM的救星
    ubuntu17.10升级到ubuntu18.04 LTS
  • 原文地址:https://www.cnblogs.com/Ryan368/p/13705915.html
Copyright © 2011-2022 走看看