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


import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

    private int counter=0;

    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!");
            for(Cookie cookie : cookies){
                    //delete cookie
                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");

Sharing cookies between apps

  1. cookie.setDomain(""); applications with domain names ending in "." 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