Java web learning journey 4-Cookie

Cookie understanding

Each web application will send its own set of cookies to each browser. The backend can operate these sets of cookies. Cookies between applications are independent (set cookies, which can be shared between applications)

Reading, writing and deleting cookies

package com.my.test.web;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author lf
 * @Title: CookieServlet
 * @Description: TODO
 * @date 2019/4/2 10:49
 */
public class CookieServlet extends HttpServlet {

    private int counter=0;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        //Read cookie
        Cookie[] cookies = req.getCookies();
        if(cookies==null || cookies.length<1){
            out.println("no cookies!");
        }else{
            for(Cookie cookie : cookies){
                if("tom6".equals(cookie.getName())){
                    //delete cookie
                    cookie.setMaxAge(0);
                }
                out.println("name:"+cookie.getName());
                out.println("value:"+cookie.getValue());
                out.println("time:"+cookie.getMaxAge()); //Valid time is greater than zero save x seconds; equal to 0 don't save; less than 0 browser close invalidate
            }
        }
        //Write to cookie
        Cookie cookie1 = new Cookie("tom"+counter,"wuhan");
        resp.addCookie(cookie1);
        counter++;
    }
}

Sharing cookies between apps

  1. cookie.setDomain(".test.com"); applications with domain names ending in ". test.com" share a cookie Set
  2. cookie.setPath("/"); all apps under tomcat Webapps share a cookie Set
  3. cookie.setPath("/test /"); the test application under tomcat Webapps owns this cookie collection alone

Keywords: Java Tomcat less

Added by thyscorpion on Sat, 07 Dec 2019 07:14:34 +0200