Cook
The Javax.servlet.http.Cookie class is used to create an Cookie,response interface that also defines a Addcookie method that is used to add a corresponding Set-cookie header field to its response header. Similarly, a getcookies method is defined in the request interface, which is used to obtain the cookie submitted by the client. Methods of the Cookie class:
- Public Cookie (String name,string value)
- SetValue and GetValue method
- Setmaxage and Getmaxage method
- SetPath and GetPath method
- GetName method
Show user last access time
Cookie.setmaxage (760*60)
Cookie.setpath ("/day0x");
HttpWatch observation
Cookie.setmaxage (0) Delete cookie with same name
Import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.cookie;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Demo1 extends HttpServlet {public void doget (HttpServletRequest re Quest, HttpServletResponse response) throws Servletexception, IOException {/*//server-generated cookie Cookie Co Okie = new Cookie ("username", "haha"); Set cookie Survival time Cookie.setmaxage (1*24*60*60); The server writes the cookie to the client staging Response.addcookie (cookie); *///Get all cookies from the client cookie[] cookies = request.getcookies (); Cookie Usernamecookie = null; if (Cookies!=null) {for (Cookie c:cookies) {if (C.getname (). Equals ("username")) { Usernamecookie = C; Break }}//If a cookie is found if (usernamecookie!=null) {SysteM.out.println ("The name of the cookie:" + usernamecookie.getname ()); System.out.println ("Value of the cookie:" + usernamecookie.getvalue ()); System.out.println ("Life of the Cookie:" + usernamecookie.getmaxage ()); SYSTEM.OUT.PRINTLN ("Path of the cookie:" + usernamecookie.getpath ()); } } }}
Cookie Details
A cookie can only identify a single message that contains at least one name and set value (value) that identifies the information.
A Web site can send multiple cookies to a Web browser, and a Web browser can store cookies provided by multiple Web sites.
Browsers generally allow only 300 cookies, with a maximum of 20 cookies per site and a limit of 4KB per cookie size.
If a cookie is created and sent to the browser, by default it is a session-level cookie (that is, stored in the browser's memory) that is deleted after the user exits the browser. If you want the browser to store the cookie on disk, you need to use maxage and give a time in seconds. Setting maximum aging to 0 is the command browser to delete the cookie.
Note that when you delete a cookie, path must be the same, or it will not be deleted
Cookies Learn Common API notes