Java web Cookie and Session similarities and differences

Source: Internet
Author: User

When we use a browser to talk to the server, some data will inevitably be generated. In this case, you need to save the data. For example, the storage of shopping cart information on a common shopping website. Cookie and Session are two technologies used to store Session data between the client and the server.

1. Cookie 1. What is a Cookie?

Cookies are stored on the client and saved as names and values. When a user accesses the server using a browser to generate data, the server program sends the data of each user to the user's browser in the form of a cookie. When a user uses a browser to access the web resources on the server, the user will carry their own data. In this way, the web server can obtain user data from the request.

2. Implement the corresponding API for cookie in java

Javax. servlet. http. Cookie class is a class in java. It is used to create a Cookie. The java Response interface defines an addCookie method. It can add a corresponding Set-Cookie header field to its Response header. Similarly, the request interface also defines a getCookies method, which is used to obtain the Cookie submitted by the client. Cookie classes have the following common methods:

PublicCookie (String name, String value) constructor

SetValue and getValue

SetMaxAge and getMaxAge set and obtain the maximum cookie Time, in seconds.

The setPath and getPath methods can be used to set paths to share cookies on the same application server.

SetDomain and getDomain set hosts to implement cross-domain cookie sharing

The getName method obtains the cookie name.

3. Notes for cookie operations

The unit of the setMaxAge method of Cookie is seconds. When it is set to-1, the browser closes the cookie and automatically deletes it from the browser.

A Cookie can only identify one type of information. It must contain one name and one value. a web application can send multiple cookies to a WEB browser. Similarly, your browser can also store cookies written by multiple WEB sites.

The number and size of cookies stored by the browser are limited. Generally, only 300 cookies can be stored, and each site can store up to 20 cookies. The size of each cookie is limited to 4 kB.

By default, a cookie is deleted after you exit the browser. If you want the browser to store the cookie on the disk, the server program needs to use maxAge and give a time in seconds. If it is set to 0, the browser is used to delete the cookie.

It is important and easy to ignore that the path and domin must be consistent when the cookie is deleted; otherwise, the cookie will not be deleted. so when we want to delete a cookie, we should not only set maxAge to 0, but also set its path and domin to be the same as the original one. When we were doing a project, I have encountered this problem.

II. Session 1. What is Session?

Different from cookie, Session is stored on the server. During runtime, the server can create an exclusive session object for each user's browser. session is exclusive to the user's browser, when the user's browser accesses the server, the generated data can also be stored in their respective sessions. When the user accesses other web resources on the server, other web resources then retrieve data from their respective sessions to serve users.

2. Session API

In java, there is an interface, javax. servlet. http. HttpSession. It mainly includes the following methods.

GetId this method returns unique identifiers generated for each session.

GetCreationTime () returns the time when the session was created. The return value is the number of milliseconds from January 1, January 1, 1970 to the creation time of the long type, that is, the timestamp.

GetLastAccessedTime returns the time when the session was last sent by the customer. The minimum unit is 1‰ seconds.

GetAttribute takes the value of an Object in the session. Because the returned value of this method is an Object, forced type conversion is required.

SetAttribute sets a key and value. If the key is the same, the new value replaces any previous value. Similar to HashMap, it is worth noting that when the value is set to a simple type, it is automatically packed into the corresponding packaging class.

3. Session details

The server creates a session object for each user's browser. By default, a browser exclusively occupies a session object. Therefore, when you need to save user data, the server program can write user data to the exclusive session of the user's browser. When the user uses the browser to access other resources of the web application, the user's data can be retrieved from the user's session to serve the user. The Session object is created by the server and saved in the server's memory. We can call the getSession method of the request object to obtain the session object of the server.

When a session is not active on the server for a long time, it is cleared from the server memory, and the Session becomes invalid. The default expiration time of the Session in Tomcat is 20 minutes.

The cookie passed by the user's browser contains a cookie that stores such as sessionID. Therefore, the server can identify the Session corresponding to the client browser. Therefore, when the client disables the Cookie, you can rewrite the URL to solve this problem. There are two main methods: response. encodeRedirectURL (java. lang. Stringurl) is used to rewrite the url address after the sendRedirect method. Response. encodeURL (java. lang. Stringurl) is used to overwrite the form action and hyperlink url.


III. Differences between cookies and Sessions

1. Cookie is to write user data to the user's browser and save it in the browser. A Session writes user data to a session exclusively owned by the user and stores the data on the server.

2. A Cookie object represents a cookie and can only represent one name and value. The cookie stores strings .. Session is similar to a HashMap-based cache on a server. You can put multiple attributes with key-value pairs. Value can be any object.

3. The Session does not have the path and domain. During the same user's access to a website, all sessions can be accessed anywhere. If path parameters are set in the cookie, the cookies in different paths of the same website cannot access each other.

4. The session is based on the cookie. The server needs to find the corresponding session through a cookie named JSESSIONID sent from the client.


Java web summary of cookie and session Technologies

Session is a server-side technology. A Session object is created on the server and usually uses a hash to store information. For example, the Session implementation of Tomcat uses a HashMap object to store attribute names and attribute values.

Cookie is a method invented by Netscape to track user sessions. A Cookie is a piece of information sent by the server to the client. It is stored in the memory or hard disk of the client browser and returned in the client's subsequent requests to the server.

Cookie summary

① Cookie create Cookie on the server cookie = new Cookie (name, value );

② Cookie is stored in the browser response. addCookie (cookie );

③ The life cycle of a Cookie can be set through cookie. setMaxAge (int second). The default life cycle of a Cookie is the session level (that is, stored in the browser's memory). If setMaxAge () is not set ()? The lifecycle of the cookie is suspended when the browser is closed. setMaxAge (0) + response. addCookie is equivalent to deleting a cookie. If the Cookie file contains only the cookie, the file is also deleted; otherwise, only the Cookie is deleted.

④ Cookies can be shared by multiple browsers

⑤ A web application can store multiple cookies (stored in the same file). A maximum of 20 cookies are allowed. Each cookie is limited to 4 kB. Therefore, the Cookie will not fill your hard disk? It will not be used as a "denial of service" attack. Browsers generally store no more than 300 cookies.

6. The Cookie stores Chinese characters and stores String val = java.net due to garbled characters. URLEncoder. encode ("Chinese name", "UTF-8"); Cookie cookie = new Cookie ("name", "val"); read? String val = java.net. URLDecoder. decode

(Cookie. getValue ("name"), "UTF-8"); out. println ("name =" + val)

Session Summary:

① The Session is stored in the server's memory.

② A user browser excludes a session domain object

③ The default life cycle of the attribute in the Session is 30 min, which can be modified through web. xml.

④ Multiple attributes (including objects) can be stored in the Session)

⑤ If session. setAttribute (name, value); has the same name, it will be replaced.

Session VS Cookie:

1. Different storage locations: the Cookie exists in the client (temporary folder) Session in the server memory, and a session domain object serves as a user browser.

2. Security: cookies are stored in the client in plaintext mode, which is less secure. The MD5 encryption algorithm can be used to store sessions in the server memory, so the security is better.

3. Network transmission volume: the attribute value that Cookie will pass information to the server Session will not be sent to the client

4. Life cycle: the Cookie declaration cycle is the cumulative time. The Session life cycle is the access session interval. In some cases, the session will also become invalid? Disable tomcat and reload web applications. When the time is up, call invalidate () [exit safely].

5. From the access scope: Session is an exclusive Cookie for a browser for multiple user browsers. Because session occupies the server's memory, do not store too many or too large objects in the session, which will affect the performance.




Differences between Cookie and Session in Java


The difference between Cookie and Session is an important knowledge point in Java. Today we will summarize some of them:


Differences between Cookie and Session

Cookie Session

Stored on the client and stored on the server

Two types of implementation methods

※There is a declaration cycle ※cookie-dependent
※No declaration cycle ※url rewriting
    
The parent path cannot access the cookie of the sub-path. The window of the same session shares a session.
    
Typical applications: typical applications:

※Login is not required for three months. ※User login
※Shopping cart ※the shopping cart can also be implemented using session.
    
Unreliable and reliable

    
The above table is a general introduction to the differences between cookies and sessions. The separate introduction of cookies and Sessions is also available in my previous articles. In general, the focus should be on the following two points:

1. Different storage locations: Cookie on the client and Session on the server.

2. Usage: the Cookie can only be the Cookie set by the sub-path to access the parent path, and the Session can access each other as long as it is in the same window.

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.