Cookie Overview
What is a cookie?
The cookie is a small piece of text information, Along with the user requests and pages are passed between the Web server and the browser. A cookie contains information that a Web application can read every time a user accesses a site.
Span style= "font-size:large;" >
because the HTTP protocol is stateless, For multiple requests made by a single browser, the Web server cannot differentiate whether it originated from the same browser. Therefore, additional data is required for the maintenance session. The cookie is exactly the extra data that is passed along with the HTTP request.
what can cookies do?
Cookie is just a piece of text, So it can only save strings. and the browser has a size limit and it will be sent to the server with each request, so it should be guaranteed not to be too large. The contents of the cookie are also stored in plaintext, and some browsers provide an interface modification, so it is not appropriate to store important or privacy-related content
Each browser has a file that holds the cookie, which is stored on the client. When we visit a website, we return not only the HTML page, but also a file: a cookie. So, whenever we visit a page with a browser, we will first walk through the cookie and see if there is any.
You can use the Setxxx method of cookies to set some corresponding values
setName (String name)/getname ()
SetValue (String value)/getvalue ()
Setmaxage (int age)/getmaxage ()
Use the HttpServletResponse Addcookie (Cookie) method to set it to the client
Use HttpServletRequest's GetCookies () method to read all cookies from the client and return a cookie array
Set cookies
Setcookies.java
Read cookies
Showcookies.java
Set the cookie by following this code:
Public class_06_servletcookieextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; @Overrideprotected voiddoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException { for(inti = 0; I < 6; i++) {Cookie Cookie=NewCookie ("session-cookie-" + I, "Cookie-value:" +i); Resp.addcookie (cookie); //only cookies that have a lifecycle set with the Javax.servlet.http.Cookie.setMaxAge () function are written to the client computer's hard disk//If this is not the case, the cookie will exist .//If the lifecycle is not set, it will only be saved in the browser's domain memory and will be deleted when the browser is closed.Cookie Cookie2 =NewCookie ("persistent-cookie-" + I, "cookie-value-p" +i); Cookie2.setmaxage (3000); //by Javax.servlet.http.HttpServletResponse.addCookie (); Send cookies to the client at that timeResp.addcookie (COOKIE2); } resp.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out=Resp.getwriter (); String title= "Setting Cookie"; Out.println ("); } @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {doPost (req, resp); }}
Use the following code to display the cookie information we set
Public class_07_showcookiesextendsHttpServlet {@Overrideprotected voiddoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {resp.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out=Resp.getwriter (); String title= "Active Cookie"; Out.println (" ); Cookie[] Cookies=req.getcookies (); if(Cookies! =NULL) {cookie cookie; for(inti = 0; i < cookies.length; i++) {Cookie=Cookies[i]; Out.println ("<tr>\n" + "<td>" + cookie.getname () + "</td>" + "<TD&G t; "+ cookie.getvalue () +" </td></tr>\n " ); } out.println ("</table></body>); }Else{out.println ("<tr><td colspan= ' 2 ' > No cookie</td></tr> on this site"); Out.println ("</table></body>); }} @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {doget (req, resp); }}
before we run, we'll look at the cookie saved by the browser, because I've emptied the cookie before, so there's no cookie saved here.
Then we run the code, run _06_servletcookie first, set the cookie,
and look at the cookie saved by the browser.
Then click on the hyperlinks in _06_servletcookie, and the cookies we set up are all displayed.
There are 2 types of cookies in _06_servletcookie, one with a time limit and the other with no set time.
This closes the browser and then goes directly into the _07_showcookies
"
we can see from the results that no cookie has been set for the time, and the cookie for setting the time is still there. So if the cookie does not set a time limit, the saved cookie will be deleted automatically when the browser is closed.
What if you don't run _06_servletcookie and run _07_showcookies directly?
show cookies that are not saved because cookies are not set
Session
The session mechanism is a server-side mechanism where the server uses a hash-like structure to hold information.
when a program needs to create a session for a client request, the server first checks to see if the client's request contains a session representation, which becomes a sessionid, If a SessionID is already included, it indicates that the session was previously created for this client, and the server uses SessionID to retrieve the session if the client request does not contain SessionID. Creating a session for this client and generating a value for the Sessionid,sessionid associated with this session should be a string that is neither duplicated nor easily found to mimic the pattern, and this sessionid will be returned to the client in this response
If the browser supports cookies, the SessionID is saved in a cookie when the session is created.
If cookies are not supported, you must programmatically implement the session using URL rewriting methods
Public class_08_setsessionservletextendsHttpServlet {@Overrideprotected voiddoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {//set MIME type to text/htmlResp.setcontenttype ("Text/html;charset=utf-8"); //gets the current session, if none can be created//getsession (), if False, no session is created//If true: No session will create aHttpSession mysession= Req.getsession (true); PrintWriter out=Resp.getwriter (); //Generating HTML documentsOut.println ("mysession.isnew ()+ "</br><b>SessionID:</b>" +Mysession.getid ()//Show the session creation time+ "</br><b>session Create time:</b>" +Newjava.util.Date (Mysession.getcreationtime ())//show the last time the session was accepted+ "</br><b>session last accessed time:</b>" +Newjava.util.Date (Mysession.getlastaccessedtime ())+ "//returns the session ID that came with the client request. May or may not be the same as the current session ID+ "</br><b>session ID from request:</b>" +Req.getrequestedsessionid ()//the current session ID, if obtained from a cookie, is true+ "</br><b>sessionid via cookie:</b>" +Req.isrequestedsessionidfromcookie ()//The current session ID is true if it is obtained by URL+ "</br><b>sessionid via rewrite url:</b>" +Req.isrequestedsessionidfromurl ()//returns True if the current client's session ID represents a valid session. Otherwise (for example, the session expires or does not exist at all), returns false+ "</br><b>valid sessionid:<b>" +req.isrequestedsessionidvalid ()+ "<br><a href=" + resp.encodeurl ("_08_setsessionservlet") + ">refresh</a>" + "</body& Gt;); Out.close (); } @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {doget (req, resp); }}
First look at the cookie saved by the browser, I emptied it before, so this is empty
run code
Refresh and try.
You can see the New Session:
Session Last accessed time:
SessionID via Cookie:
Valid SessionID:
This information has changed.
The browser is set to not accept cookies, click Refresh:
SessionID via rewrite URL:
This message will become true
1. A piece of memory on the server (storage key-value)
2. Corresponding to the Client window (child window) (unique)
3. The client and server have the corresponding SessionID
4. The client sends SessionID to the server side in two ways:
1.cookie (Memory cookie)
2.rewriten URL
5. The browser will not be able to use the session (session with cookie)
6. If you want to use the session safely (regardless of whether the client prohibits cookies), you can only use URL rewriting ( Significantly increased programming burden), so many websites require clients to open cookies
Cookie and Session summary