Javaweb the Cookie Object

Source: Internet
Author: User
Tags browser cache

1. The concept of conversation

  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.

2. Some of the issues to be addressed during the session

  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.

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

4. 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)

Common methods

Set the value of a 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.

5. Examples of cookie usage

5.1 Getting the last time a user visited a website

1 Package Gac.xdp.cookie;2 3 import java.io.IOException;4 import Java.io.PrintWriter;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;Ten import Javax.servlet.http.HttpServletResponse; One  A /** - * @author GaCl - * Cookie instance: Gets the time the user last visited the  */ -  Public classCookieDemo01 extends HttpServlet { -  -      Public voiddoget (httpservletrequest request, httpservletresponse response) + throws Servletexception, IOException { -         //set the server side to output UTF-8 encoding +Response.setcharacterencoding ("UTF-8"); A         //set the browser to receive UTF-8 encoding to solve Chinese garbled problem atResponse.setcontenttype ("Text/html;charset=utf-8"); -PrintWriter out=Response.getwriter (); -         //gets the array of cookies passed over when the browser accesses the server -cookie[] Cookies =request.getcookies (); -         //If the user is a first-time access, then the resulting cookie will be null -         if(cookies!=NULL) { in              out. Write ("the last time you visited was:"); -              for(inti =0; i < cookies.length; i++) { toCookie cookie =Cookies[i]; +                 if(Cookie.getname (). Equals ("LastAccessTime")) { -Long LastAccessTime =Long.parselong (Cookie.getvalue ()); theDate Date =NewDate (lastaccesstime); *                      out. Write (Date.tolocalestring ()); $                 }Panax Notoginseng             } -}Else { the              out. Write ("This is your first time to visit this site! "); +         } A          the         //after the user has accessed, reset the user's access time, store it in a cookie, and then send it to the client browser +Cookie 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) the throws Servletexception, IOException { - doget (request, response);Wuyi     } the  -}

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:

//after the user has accessed, reset the user's access time, store it in a cookie, and then send it to the client browser2Cookie cookie =NewCookies ("LastAccessTime", System.currenttimemillis () +"");//Create a Cookie,cookie whose name is LastAccessTime3 //setting a cookie is valid for 1 days4Cookie.setmaxage ( -* -* -);5 //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.6Response.addcookie (cookie);

5.2 Cookie attention to detail

    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.

5.3 Deleting cookies

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

1  PackageGac.xdp.cookie;2 3 Importjava.io.IOException;4 5 Importjavax.servlet.ServletException;6 ImportJavax.servlet.http.Cookie;7 ImportJavax.servlet.http.HttpServlet;8 Importjavax.servlet.http.HttpServletRequest;9 ImportJavax.servlet.http.HttpServletResponse;Ten  One /** A  * @authorGaCl - * Delete Cookies -  */ the  Public classCookieDemo02extendsHttpServlet { -  -      Public voiddoget (httpservletrequest request, httpservletresponse response) -             throwsservletexception, IOException { +         //Create a cookie with the name LastAccessTime -Cookie cookie =NewCookie ("LastAccessTime", System.currenttimemillis () + ""); +         //set the cookie's validity period to 0 and the browser to delete the cookie ACookie.setmaxage (0); at Response.addcookie (cookie); -     } -  -      Public voidDoPost (httpservletrequest request, httpservletresponse response) -             throwsservletexception, IOException { - doget (request, response); in     } -}

5.4 access to 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  new Cookie ("UserName", Urlencoder.encode ("Aloof Pale 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:

Urldecoder.decode (Cookies[i].getvalue (), "UTF-8")

Javaweb the Cookie Object

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: info-contact@alibabacloud.com 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.