Java Web Learning 11 (using Cookies for session management)

Source: Internet
Author: User
Tags browser cache

First, 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.

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

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.

V. Cookies use example 5.1, use cookies to record the time of the user's last visit
 PackageServlet.study;Importjavax.servlet.ServletException;ImportJavax.servlet.http.Cookie;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjava.io.IOException;ImportJava.io.PrintWriter;Importjava.util.Date;/*** Created by Lijia on 2016/1/6.*/ Public classCookieDemo1extendsHttpServlet {@Overrideprotected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//set the server to output to the browser in UTF-8 formatResponse.setcharacterencoding ("UTF-8"); //set the browser to accept in UTF-8 format, so as not to appear garbledResponse.setcontenttype ("Text/html;charset = UTF-8"); PrintWriter out=Response.getwriter (); //get an array of cookiescookie[] Cookies =request.getcookies (); //cookies will be null if they are first logged in        if(Cookies! =NULL) {Out.write ("The last time you logged in 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 ("First time Login"); }        //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 =NewCookie ("LastAccessTime", System.currenttimemillis () + ""); //cookie.setmaxage (24*60*60); //The cookie object is added to the response object, so that the server will output the cookie to the client browser when outputting the contents of the response object;Response.addcookie (cookie); } @Overrideprotected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}

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

 PackageGac.xdp.cookie;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.Cookie;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** Delete Cookies*/ Public classCookieDemo02extendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//Create a cookie with the name LastAccessTimeCookie cookie =NewCookie ("LastAccessTime", System.currenttimemillis () + ""); //set the cookie's validity period to 0 and the browser to delete the cookieCookie.setmaxage (0);    Response.addcookie (cookie); }     Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}

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 ("Lijia", "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")

Java Web Learning 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: 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.