Servlet and JSP reading notes (iii) cookies

Source: Internet
Author: User
Tags set cookie

I. A brief introduction to communication between the browser and the server leads to cookies and sessions (just a brief introduction that does not include knowledge of the Protocol)

  1. When we enter an address in the browser, we can see the beautiful page that the browser showed us after the carriage return. What does the browser and server do in this process? The following explanation is just between the browser and the server

The simplest form of communication, also known as a session.

① First we enter the URL we want to open on the Address bar and press ENTER. Such a request is sent by the browser to the server.

after the network device of the ② server receives the data, it is transmitted to the server software.

After the ③ service software has been requested, a series of logical processing is made, and then the response is generated and sent to the browser.

④ responding to network devices through the server, network devices that are transmitted to the client through a network cable.

The network device of the ⑤ client will parse the response and pass it on to the browser software, and the browser will parse the response so that we see the page we want to see on the browser.

2. The Web language HTTP is stateless, so when the server finishes processing the customer's request and receives the customer's response, the connection to the client is immediately disconnected. However, when we visit a website, we do not only do one thing, but

There are a lot of things to do, but this stateless connection makes it impossible for the server to recognize that subsequent requests and previous requests were made by the same person, or that when many people visited the same site, they could not identify who was who. Therefore, the

Both the cookie and session technologies. These two techniques are the two techniques for maintaining client and server session processes.

How is the cookie implemented specifically? When you are browsing the site, the Web server sends some data to your computer, which is called a cookie. The Cookie will put the text you have on the website or

Some of the choices are recorded. The next time you visit the same website, the Web server will first see if it has the last cookie information, and if so, it will be based on the contents of the cookie to determine the user, send out a specific page

To you. Cookies are therefore a client-side technology that resides on the client side.

Session is another mechanism for recording customer status. The server can create a single Session object for each user's browser at run time, because the session is exclusive to the user's browser, so the user accesses the service

Server Web resources, you can put their own data in the session, when the user to access other Web resources on the servers, other Web resources from the user's session to take out data for the user Service.

Session is a server-side technology that resides on the server side.

Two. Introduction to Cookies

A cookie is a data stored on a user's local terminal in the form of a key-value pair (Key/value) for the purpose of identifying user identities and for session tracking purposes.

Cookies are generated by the server, sent to the browser, the browser will save the cookie key/value to a text file in a directory, the next time you request the same website to send the cookie to the server (if the browser is set

Cookies are enabled). This allows the server to know whether the user is a legitimate user and whether or not to log on again, and the server can set or read the information contained in the cookie to maintain the state of the user and server session.

Three. The Cookie in Java is the Javax.servlet.http.Cookie provided in the servlet API

 1. The specific information for cookies is: public class Cookie extends Java.lang.Objectimplements java.lang.Cloneable

2. The Main method

①public Cookie(java.lang.String name,java.lang.string value)

     constructor that instantiates a cookie, passing in the key (name) and the value, (value).

②public java.lang.String getName()

Gets the name of the cookie.

③public java.lang.String getValue()

Gets the value of the cookie.

public void SetValue(java.lang.String newvalue)

Set the value of a cookie

④public void setmaxage(int expiry)

Sets the maximum save time for a cookie, which is the lifetime 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,

Then the validity period of a cookie is only valid during one session, when a user opens a browser, accesses a Web site, accesses multiple Web resources on the server, and then closes the browser, the entire process is called a session.

When the user closes the browser, the session ends and the cookie expires.

public int Getmaxage()

Get the validity of cookies

⑥public void setpath(java.lang.String URI)

Setting a valid path to the cookie, such as setting the valid path of the cookie to "/ABC", will bring a cookie when the browser accesses the Web resource under the "ABC" directory.

If the valid path of the cookie is set to "/ABC/ABCD", then the browser will only be accessed with a cookie if it accesses the Web resource in the "ABCD" directory under "ABC".

Public java.lang.String GetPath()

Get a valid path to a cookie

⑦public void setdomain(java.lang.String pattern)

Set a valid domain for a cookie

Public java.lang.String GetDomain()

Get the valid domain of the cookie

3. Public interface httpservletrequest extends ServletRequest This interface has a way to manipulate cookies

Public cookie[] getcookies()

Get Cookie Instance

4. Public interface httpservletresponse extends Servletresponse This interface also has the method of manipulating cookies

public void Addcookie(Cookie cookie)

Add a cookie to a response

Four. Cookie small instance 1____ server side does not set cookie expiration time

 PackageCom.hjj.servlet.three;Importjava.io.IOException;ImportJava.io.PrintWriter;ImportJava.text.DateFormat;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.Cookie;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;Importjavax.servlet.http.HttpServletResponse; @WebServlet (name= "Testcookies", urlpatterns= "/testcookies") Public classTestcookiesextendshttpservlet{protected voidDoget (httpservletrequest request,httpservletresponse response)throwsioexception{Response.setcontenttype ("Text/html"); Response.setcharacterencoding ("UTF-8"); Cookie[] Cookies= Request.getcookies ();//first access, result is emptyPrintWriter PW =Response.getwriter (); if(Cookies = =NULL) {pw.println ("Hello, you are the first time to visit the site." "); Pw.println ("We will add the cookie object to the response object so that the server will export the cookie to the client browser when outputting the contents of the Response object"); //If this is the first time you have visited the Web site, create a cookie object and add it to the response. This will bring a cookie in the response returned to the browserCookie cookie =NewCookie ("LastAccessTime", System.currenttimemillis () + "");                    Response.addcookie (cookie); }Else{pw.print ("Hello, you are not the first to visit the site. The last time you visited the website was: ");  for(Cookie cookie:cookies) {//get the name of the cookieString name =Cookie.getname (); if(Name.equals ("LastAccessTime")){                                        //get the value of the cookieString value =Cookie.getvalue (); //Converts a string of type value to a time type, and converts a string of type "1234567" into a string of type "2016-2-2 2:02:02".String time =NewSimpleDateFormat ("Yyyy-mm-dd hh:mm"). Format (NewDate (Long.parselong (value)));                Pw.println (time); }                            }        }                        }        protected voidDoPost (httpservletrequest request,httpservletresponse response)throwsioexception{ This. Doget (request, response); }}

1. Enter http://localhost:8080/one/testCookies in the browser for the first time

Page display:

The request and response are:

      

2. Refresh the browser again

Page display:

        

        Hello, you are not the first time to visit the site. The first time to visit the site is: 2016-04-30 17:16

The request and response are:

      

3.1 and 22 experiments do not set the cookie expiration time on the server side. So when you're done with the first two trials, close the browser and the cookie is dead. Open the browser again,

then re-request http://localhost:8080/one/testCookies the same as the results of experiment 1, re-refresh is the same as the results of experiment 2.

Five. Cookie small instance 1____ server-side manually set cookie expiration time 

    

 PackageCom.hjj.servlet.three;Importjava.io.IOException;ImportJava.io.PrintWriter;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.Cookie;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;Importjavax.servlet.http.HttpServletResponse; @WebServlet (Urlpatterns= "/testsetmaxage") Public classTestsetmaxageextendshttpservlet{protected voidDoget (httpservletrequest request,httpservletresponse response)throwsioexception{Response.setcontenttype ("Text/html"); Response.setcharacterencoding ("UTF-8"); Cookie[] Cookies= Request.getcookies ();//first access, result is emptyPrintWriter PW =Response.getwriter (); if(Cookies = =NULL) {pw.println ("Visit this site for the first time"); Cookie Cookie=NewCookie ("LastAccessTime", System.currenttimemillis () + ""); intTime =Cookie.getmaxage (); Pw.println ("The default cookie expiration time is:" +Time ); //set cookies to expire in 24 hours, that is, one dayPW.PRINTLN ("Manually set the cookie expiration time on the server side"); Cookie.setmaxage (86400); Pw.println ("The cookie expires after setting:" +cookie.getmaxage ());                    Response.addcookie (cookie); }Else{pw.print ("Is not the first time to visit the site. The last time you visited the website was: ");  for(Cookie cookie:cookies) {//get the name of the cookieString name =Cookie.getname (); if(Name.equals ("LastAccessTime") ) {String value=Cookie.getvalue (); String Time=NewSimpleDateFormat ("Yyyy-mm-dd hh:mm"). Format (NewDate (Long.parselong (value)));                Pw.println (time); }                            }        }                        }        protected voidDoPost (httpservletrequest request,httpservletresponse response)throwsioexception{ This. Doget (request, response); }}

1. First request Browser input: Http://localhost:8080/one/testSetMaxAge

Page display:

The request and response are:

response Header

2. Refresh the page

Page display:

The request and response are:

      

    

3. Close the browser and reopen the browser again, because the cookie is set to expire for 24 hours, so the cookie is still valid until it is accessed again.

The page appears as follows:

The request and response are:

Six. Cookies Summary

    1. A cookie exists in the form of a key-value pair, and setting a cookie must contain name and value.
    2. A Web site can send multiple cookies to a single browser, and a browser can store cookies provided by multiple websites.
    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.

Seven. Delete cooike

  

 PackageCom.hjj.servlet.three;Importjava.io.IOException;ImportJava.io.PrintWriter;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.Cookie;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;Importjavax.servlet.http.HttpServletResponse; @WebServlet (Urlpatterns= "/testdeletecookie") Public classTestdeletecookieextendsHttpServlet {protected voidDoget (httpservletrequest request,httpservletresponse response)throwsioexception{Response.setcontenttype ("Text/html"); Response.setcharacterencoding ("UTF-8"); Cookie[] Cookies= Request.getcookies ();//first access, result is emptyPrintWriter PW =Response.getwriter (); Cookie Cookie=NewCookie ("LastAccessTime", System.currenttimemillis () + ""); //ways to delete cookiesCookie.setmaxage (0);        Response.addcookie (cookie); Pw.print ("I deleted the cookie."); }        protected voidDoPost (httpservletrequest request,httpservletresponse response)throwsioexception{ This. Doget (request, response); }}

1. Browser Request: Http://localhost:8080/one/testDeleteCookie

Page display:

        

The request and response are:

      

2. Each time the page is refreshed, the server returns a response with Set-cookie.

    

Cookies for servlet and JSP reading notes (iii)

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.