Javaweb Learning Summary (11)--Using Cookies for session management

Source: Internet
Author: User
Tags browser cache

Javaweb Learning Summary (11)--session management using cookies 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.
Stateful session: A classmate came to the classroom, next time to come to the classroom, we will know that this classmate has come, this is called a stateful session.

Second, the conversation process to solve some problems?

Each user in the process of using the browser and the server session, will inevitably produce some data, the program to find a way to save the data for each user.

Iii. two techniques for saving session data 3.1, 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.

3.2. Session

Session is a server-side technology, using this technology, the server at run time can be used for each user's browser to create a unique session object, because the session for the user browser exclusive, so the user access to the server's Web resources, Can put their own data in the session, when the user to access other Web resources on the server, the other Web resources from the user's own session to remove data for the user Service.

Iv. 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






Cookie (string name, String value)

Construction method

Instantiate a cookie object, passing in the value of the Cooke name and cookie


Public String GetName ()

Common methods

Get the name of a cookie


Public String GetValue ()

Common methods

Get the value of a cookie


public void SetValue (String newvalue)

Common methods

Set the value of a cookie


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.


public int Getmaxage ()

Common methods

Get the validity of cookies


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


Public String GetPath ()

Common methods

Get a valid path to a cookie


public void SetDomain (String pattern)

Common methods

Set a valid domain for a cookie


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.

V. Cookies use example 5.1, use cookies to record the time of the user's last visit
 1 package Gac.xdp.cookie; 2 3 Import; 4 Import; 5 Import Java.util.Date; 6 Import javax.servlet.ServletException; 7 Import Javax.servlet.http.Cookie; 8 Import Javax.servlet.http.HttpServlet; 9 Import javax.servlet.http.httpservletrequest;10 Import javax.servlet.http.httpservletresponse;11/**13 * @author Gacl14 * Cookie instance: Gets the user's last access time */16 public class CookieDemo01 extends HttpServlet {page public void doget (Httpser Vletrequest request, HttpServletResponse response) throws Servletexception, IOException {20//Set server side Output with UTF-8 encoding response.setcharacterencoding ("UTF-8"); 22//Set browser to receive UTF-8 encoding, solve the problem of Chinese garbled response.s Etcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter (); 25//Get the browser to access the server when it passes over Cookie array cookie[] cookies = request.getcookies (); 27//If the user is the first time access, then the resulting cookie will be null28 if (Cookie S!=null) {Out.write ("youThe time of the second visit is: "); (int i = 0; i < cookies.length; i++) {to Cookie cookie = cookies[i];32 if (Cookie.getname (). Equals ("LastAccessTime")) {LastAccessTime =long.parselong (c Ookie.getvalue ()); Date date = new Date (lastaccesstime); Out.write (Date.toloca Lestring ());}37}38}else {out.write ("This is your first time to visit this site!") "); 40}41 42//The user's access time is reset, stored in a cookie, and then sent to the client browser. Cookie cookie = new Cookie (" Las Taccesstime ", System.currenttimemillis () +" ");//Create a Cookie,cookie whose name is lastAccessTime44//Add the cookie object to the Response object, When the server outputs the contents of the response object, it also outputs the cookie to the client browser Response.addcookie (cookie);}47-public void DoPost (HttpS Ervletrequest request, HttpServletResponse response) throws Servletexception, IOException {doget ( request, response); 51}52 53}

The first time you visit this servlet, the effect is as follows:

Click on the browser's refresh button for a second visit, at which point the server can get the time of the browser's last visit through a cookie, the effect is as follows:

In the above example, the Setmaxage method is not used in the program code to set the validity period of the cookie, so when the browser is closed, the cookie is invalidated and if the cookie is still valid after the browser is closed, when the cookie is created, Set an expiration date for the cookie. As shown below:

cookie.setmaxage (24*60*60); 5//Add the cookie object to the response object so that the server will output the cookie to the client browser 6 Response.addcookie (cookie) when outputting the contents of the response object;

The cookie that the server sends to the browser is stored on the hard disk the first time the user accesses it, as shown below:

This way, even if you close the browser, the next time you visit, you will still be able to get the user's last visit by Cookie.

Vi. note the details of cookies
    1. A cookie can only identify a single message that contains at least one name and set value (value) that identifies the information.
    2. A Web site can send multiple cookies to a Web browser, and a Web browser can store cookies provided by multiple Web sites.
    3. Browsers generally allow only 300 cookies, with a maximum of 20 cookies per site and a limit of 4KB per cookie size.
    4. 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.
6.1. Delete Cookies

Note: When you delete a cookie, path must be the same, or it will not be deleted

 1 package Gac.xdp.cookie; 2 3 import; 4 5 import javax.servlet.ServletException; 6 import Java X.servlet.http.cookie; 7 Import Javax.servlet.http.HttpServlet; 8 Import Javax.servlet.http.HttpServletRequest; 9 Import javax.servlet.http.httpservletresponse;10/**12 * @author gacl13 * Delete cookie14 */15 public class CookieDemo0             2 extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) 18 Throws Servletexception, IOException {19//Create a COOKIE20 cookie with the name lastaccesstime a cookie = new Cookie ("Las         Taccesstime ", System.currenttimemillis () +" "); 21//Set the cookie's validity period to 0, the command browser to delete the Cookie22 cookie.setmaxage (0); 23 Response.addcookie (cookie);}25 public void DoPost (HttpServletRequest request, HttpServletResponse re Sponse) throws Servletexception, IOException {doget (request, response);}30} 
6.2.accessing Chinese in cookies

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")

Javaweb Learning Summary (11)--Using Cookies for session management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.