the concept of a session
A session can be simply understood as: A user opens a browser, clicks multiple hyperlinks, accesses multiple Web resources on the server, and then closes the browser, the entire process is called a session.
Cookies
A cookie is a client-side technology in which a program writes each user's data to a user's browser in the form of a cookie. When users use a browser to access Web resources on the server, they take their own data. In this way, the Web resource handles the user's own data.
Java-provided API for manipulating cookies
The Javax.servlet.http.Cookie class in Java is used to create a cookie
The main methods of the cookie class |
No. |
Method |
Type |
Describe |
1 |
Cookie (string name, String value) |
Construction method |
Instantiate a cookie object, passing in the value of the Cooke name and cookie |
2 |
Public String GetName () |
Common methods |
Get the name of a cookie |
3 |
Public String GetValue () |
Common methods |
Get the value of a cookie |
4 |
public void setvalue (string newvalue) |
normal method |
Set the value of the cookie |
5 |
public void setmaxage (int expiry) |
normal method |
set the maximum save time for cookies, that is, the expiration date of the cookie, when the server sends a cookie back to the browser, If the Setmaxage method is not invoked on the server side to set the validity period of the cookie, the cookie is valid only for one session, and the user opens a browser, clicks multiple hyperlinks, accesses multiple Web resources on the server, and then closes the browser. The whole process is called a session , when the user closes the browser, the session ends, and the cookie expires, and if the cookie is set to expire on the server side using the Setmaxage method, such as setting a 30-minute Then when the server sends the cookie to the browser, the cookie will be stored on the client's hard disk for 30 minutes, and in 30 minutes, even if the browser is turned off, the cookie still exists, and within 30 minutes, the browser will bring the cookie with you when you open the browser to access the server. This allows the server side to get to the client browser passed the information in the cookie, which is the difference between the cookie settings maxage and not set MaxAge, do not set maxage, then the cookie is only valid in one session, once the user closes the browser, Then the cookie does not have, then how does the browser do this, we start a browser, it is equivalent to launch an application, and the server sends back the cookie first exists in the browser cache, when the browser is closed, the browser's cache will naturally be absent, So the cookie stored in the cache is naturally cleared, and if the cookie is set to expire, the cookie will be stored on the hard disk when the browser is closed, so that the cookie can persist. |
6 |
public int Getmaxage () |
Common methods |
Get the validity of cookies |
7 |
public void SetPath (String uri) |
Common methods |
Setting a valid path to a cookie, such as setting the valid path of a cookie to "/XDP", when a browser accesses a Web resource in the "XDP" directory, it takes a cookie and, for example, sets the valid path of the cookie to "/xdp/gacl", Then the browser will only be accessed with a cookie when accessing Web resources in the directory "GaCl" in the "XDP" directory, and when accessing Web resources in the "XDP" directory, the browser is not a cookie |
8 |
Public String GetPath () |
Common methods |
Get a valid path to a cookie |
9 |
public void SetDomain (String pattern) |
Common methods |
Set a valid domain for a cookie |
10 |
Public String GetDomain () |
Common methods |
Get the valid domain of a cookie |
The response interface 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.
Use cookies to record when a user last visitedCookie Note 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.
accessing Chinese in cookies
Packagecookies;Importjava.io.IOException;ImportJava.io.PrintWriter;Importjava.util.Date;Importjavax.servlet.ServletException;ImportJavax.servlet.http.Cookie;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/** * @author* Cookie instance: Gets the time the user last visited*/ Public classCookieDemo01extendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//set the server side to output UTF-8 encodingResponse.setcharacterencoding ("UTF-8"); //set the browser to receive UTF-8 encoding to solve Chinese garbled problemResponse.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out=Response.getwriter (); //gets the array of cookies passed over when the browser accesses the servercookie[] Cookies =request.getcookies (); //If the user is a first-time access, then the resulting cookie will be null if(cookies!=NULL) {Out.write ("The last time you visited was:"); for(inti = 0; i < cookies.length; i++) {Cookie Cookie=Cookies[i]; if(Cookie.getname (). Equals ("LastAccessTime") {Long LastAccessTime=Long.parselong (Cookie.getvalue ()); Date Date=NewDate (LastAccessTime); Out.write (Date.tolocalestring ()); } } }Else{out.write ("This is your first time to visit this site!" "); } //after the user has accessed, reset the user's access time, store it in a cookie, and then send it to the client browserCookie cookie =NewCookies ("LastAccessTime", System.currenttimemillis () + "");//Create a Cookie,cookie whose name is LastAccessTime//The cookie object is added to the response object so that the server outputs the cookie to the client browser when it outputs the contents of the response object.Response.addcookie (cookie); } Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}
To store Chinese in a cookie, you must use the encode (string s, String enc) method inside the Urlencoder class to transcode in Chinese, for example:
1 Cookie cookie = new Cookie ("UserName", Urlencoder.encode ("Aloof Wolf", "UTF-8")); 2 Response.addcookie (cookie);
When acquiring the Chinese data in a cookie, it is decoded using the decode (string s, String enc) inside the Urldecoder class, for example:
1 Urldecoder.decode (Cookies[i].getvalue (), "UTF-8")
Session
In Java, the session object for HTTP is represented by Javax.servlet.http.HttpSession.
In web development, the server can create a session object for each user browser (Session object), note that a browser exclusively has a Session object (by default). Therefore, when the user data needs to be saved, the server program can write the user data to the user's browser exclusive session, when users use the browser to access other programs, other programs can remove the user's data from the user's session, to serve the user.
Time the session was created
Until a server-side program calls Httpservletrequest.getsession (true) such a statement is created, note that if the JSP is not displayed using <% @page session= "false"%> When the session is closed, the JSP file is automatically added to the servlet as a statement HttpSession session = Httpservletrequest.getsession (TRUE), which is also implied in the JSP. The origin of the session object.
Because the session consumes memory resources, if you do not intend to use the session, you should close it in all JSPs.
A static resource that accesses *.html is not compiled into a servlet and does not involve session issues.
When the JSP page does not explicitly prohibit the session, when the browser is opened for the first time, the server will automatically create a session for it, and give it a sessionid, sent to the client's browser. When the client then requests additional resources in the application, it is automatically added to the request header:
Cookie:jsessionid= client Gets the session ID for the first time
The session is created and used on the server, and the browser never gets the session object. However, the browser can request that the servlet (JSP is also a servlet) to get information about the session. The client browser really gets the SessionID, which is invisible to the browser operator, and the user doesn't have to worry about which session they're in.
Server creation session, will be the session ID number, as a cookie back to the client, so as long as the client's browser is not closed, and then to access the server, will take the session ID number to go, the server found the client browser with session ID comes in, it will use the corresponding session in memory to serve.
<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "http://java.sun.com/xml/ns/ Java ee " xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xsi:schemalocation=" http://java.sun.com/ Xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> <!--Set the session's effective time: in minutes > <session-config> <session-timeout>15</session-timeout> </session-config ></web-app>
When you need to manually set the session failure in the program, you can manually call the session.invalidate method to destroy the session.
1 HttpSession session = Request.getsession (); 2//Manual call Session.invalidate method, destroy Session3 session.invalidate ();
The main differences between session and Cookie
- A cookie is a browser that writes the user's data to a user.
- Session Technology writes the user's data to the user's exclusive session.
- The session object is created by the server and the developer can invoke the GetSession method of the request object to get the session object.
HTTP Cookie Session