Java cookies and sessions

Source: Internet
Author: User

I. Differences between cookie and session mechanisms

Specifically, the cookie mechanism adopts the client-side persistence scheme, while the session mechanism adopts the server-side persistence scheme.

At the same time, we can also see that the server-side persistence scheme also needs to save an identifier on the client, so the session

The cookie mechanism may be used to save the identity, but there are other options.

Ii. Differences between session cookies and persistent cookies

If no expiration time is set, it indicates that the life cycle of the cookie is the browser session period, and the cookie disappears as long as the browser window is closed. This cookie is called a session cookie. Session cookies are generally stored in memory instead of hard disks.

If the expiration time is set, the browser will save the cookie to the hard disk, and then open the browser again. These cookies are still valid until the preset expiration time is exceeded.

Cookies stored on hard disks can be shared among different browser processes, such as two IE Windows. For Cookies stored in the memory, different browsers have different processing methods.

Iii. How to Achieve Automatic Login

After a user registers for a website, the user will receive a cookie with a unique user ID. When the customer reconnects

The User ID will be automatically returned, and the server will check it to determine whether it is a registered user and has selected automatic logon, so that the user needs to give a clear user name and password, you can access resources on the server.

4. How to customize websites based on users' interests

Websites can use cookies to record users' wishes. For simple settings, websites can store page settings in cookies for customization. However, for more complex customization, the website only needs to send a unique identifier to the user, and the page settings corresponding to each identifier are stored in the database on the server side.

5. Sending cookies

1. Create a cookie object

2. Set the maximum validity period

3. Put the cookie in the HTTP Response Header

If you create a cookie and send it to the browser, It is a session-level cookie by default, which is stored in the browser memory and deleted after the user exits the browser. If you want your browser to store the cookie on a disk

You need to use maxage and give a time in seconds. If the maximum validity period is set to 0, the browser deletes the cookie.

To send a cookie, you must use the addcookie method of httpservletresponse to insert the cookie into a set-Cookie HTTP request header. Because this method does not modify any previously specified set-Cookie header, but creates a new header, we call this method addcookie instead of setcookie. Remember that the response header must be set before any document content is sent to the client.

6. Cookie reading

1. Call request. getcookie

To obtain a cookie sent by a browser, you need to call the getcookies method of httpservletrequest. This call returns an array of cookie objects, corresponding to the value entered by the cookie header in the HTTP request.

2. Loop the array and call the getname method of each cookie until the cookie is found.

Cookies are related to your host (domain), not your servlet or JSP page. Therefore, although your servlet may only send a single cookie, you may also get many irrelevant cookies.

For example:

String cookiename = "userid ";

Cookie Cookies [] = request. getcookies ();

If (cookies! = NULL ){

For (INT I = 0; I <cookies. length; I ++ ){

Cookie = Cookies [I];

If (cookiename. Equals (cookie. getname ())){

Dosomethingwith (cookie. getvalue ());

}

}

}

7. How to use cookies to detect new visitors

A. Call httpservletrequest. getcookies () to obtain the cookie Array

B. Check whether the cookie with the specified name exists and whether the corresponding value is correct in the loop.

C. If yes, exit the loop and set the differential identifier.

D. Determine whether the user is the first visitor Based on the Difference Identification to perform different operations.

8. Use cookies to detect Common Errors of new visitors

The user cannot be considered as a new visitor simply because the cookie array does not exist in a specific data item. If the cookie array is null, the client may be a first-time visitor, or the result may be caused by the deletion or disabling of cookies.

However, if the array is not null, it only shows that the customer has visited your website or domain. It does not indicate that they have visited your servlet. Other Servlets, JSP pages, and non-Java Web applications can set cookies. Based on the path settings, any cookies may be returned to the user's browser.

The correct method is to determine whether the cookie array is empty and whether the specified cookie object exists and the value is correct.

IX. Notes on cookie attributes

Attributes are part of the header sent from the server to the browser, but they do not belong to the header returned by the browser to the server.

Therefore, except for the name and value, the cookie attribute only applies to the cookies that are output from the server to the client. The cookies from the browser on the server are not set.

Therefore, do not expect this attribute to be used in cookies obtained through request. getcookies. This means that you cannot just set the maximum validity period of a cookie, send it, search for the appropriate cookie in the subsequent input array, and read its value, modify it and save it back to the cookie to realize the continuously changing cookie value.

10. How to use cookies to record the access count of each user

1. Obtain the cookie value used by the cookie array to count the number of user visits

2. Convert the value to the int type.

3. Add Value 1 and create a cookie object with the original name.

4. Reset the maximum validity period.

5. Output new cookies

11. Different definitions of sessions in different environments

Session, which is often translated into sessions in Chinese. Its original meaning refers to a series of actions/messages that start and end, for example, a call is a process from picking up a phone call and dialing to hanging up a phone call.

However, when a session is associated with a network protocol, it often implies two meanings: "connection-oriented" and "/" persistence.

The semantics of a session in the Web development environment has been expanded. The meaning of a session refers to a solution for maintaining the status between the client and the server. Sometimes session refers to the storage structure of this solution.

12. session mechanism

The session mechanism is a server-side mechanism. The server uses a structure similar to a hash (or a hash) to save information.

However, when the program needs to create a session for a client request, the server first checks whether the client request contains a session ID called session ID, if a session ID already exists, it indicates that a session has been created for this customer. Then, the server uses the session ID to retrieve the session. (If NO session ID is found, a new session may be created, this situation may occur when the server has deleted the session object corresponding to the user, but the user manually attaches a jsession parameter to the request URL ).

If the client request does not contain the session ID, the client creates a session and generates a session ID associated with the session. The session ID will be returned to the client for saving in this response.

13. Several Methods for saving session IDs

A. The cookie can be used to save the session ID. In this way, the browser can automatically send the ID to the server according to the Rules during the interaction process.

B. because the cookie can be artificially disabled, there must be other mechanisms so that the session ID can still be passed back to the server when the cookie is disabled. a frequently used technology is called URL rewriting, the session ID is appended to the URL path. There are two additional methods, the other is appended to the URL as a query string. The network remains in the State throughout the interaction process, and the session ID must be included after the path that each client may request.

C. Another technique is form hidden fields. The server automatically modifies the form and adds a hidden field so that the session ID can be passed back to the server when the form is submitted.

14. When will a session be created?

A common error is that the session is created when a client accesses the session. However, the fact is that the session is created until a server program (such as servlet) calls httpservletrequest. A statement such as getsession (true) is created.

15. When the session will be deleted

Sessions are deleted in the following situations:

A. The program calls httpsession. invalidate ()

B. The interval between the last session ID sent by the client and the previous one exceeds the maximum validity period of the session.

C. The server process is stopped.

Once again, closing the browser will only invalidate the session cookie stored in the browser memory of the client, and will not invalidate the session object on the server.

16. What are the disadvantages of URL rewriting?

Use URL rewriting for all URLs, including hyperlinks, form actions, and redirection URLs. Add additional information for each URL that references your site and the URL returned to the user (even through indirect means, such as the location field in server redirection.

This means that there cannot be any static html page on your site (at least there cannot be any link to the dynamic page of the site ). Therefore, each page must be dynamically generated using Servlet or JSP. Even if all pages are dynamically generated, if the user leaves the session and returns again through bookmarks or links, the session information will be lost, because the stored Link contains the wrong identifier information-the session ID after the URL has expired.

17. What are the disadvantages of using hidden form fields?

This method can be used only when forms are submitted and generated dynamically on each page. Click <a href...> hypertext links do not generate form submissions. Therefore, hidden form fields cannot support normal session tracking and can only be used in a series of specific operations, such as the checkout process of online stores.

18. basic steps of session tracking

1. Access the session object related to the current request

2. Search for session-related information

3. Store session information

4. Discard session data

19. Differences between getsession (), getsession (true), and getsession (false)

Getsession ()/getsession (true): This session is returned when the session exists. Otherwise, a new session is created and the object is returned.

Getsession (false): This session is returned when the session exists. Otherwise, no new session is created and null is returned.

20. How to associate information with sessions

Setattribute replaces any previously set value. If you want to remove a value without providing any replacement, you should use removeattribute. This method triggers all valueunbound that implements the value of the httpsessionbindinglistener interface.

Method.

21. Are there any restrictions on the type of session attributes?

Generally, the session attribute type can be as long as it is an object. Except null or basic types, such as int, double, and Boolean.

To use a value of the basic type as an attribute, you must convert it to the corresponding encapsulation class object.

22. How to discard session data

A. Only the data created by the self-compiled servlet is removed:

Call removeattribute ("key") to discard the value associated with the specified key

B. Delete the entire session (in the current web application ):

Call invalidate to discard the entire session. In this way, all session data of this user will be lost, not just from us

Session data created on the servlet or JSP page

C. unregister a user from the system and delete all sessions belonging to him or her

Call logout to log out from the Web server and discard all sessions associated with the user (one web application at most ). This operation may affect multiple different Web applications on the server.

23. Use isnew to determine whether a user is a new or old user.

Public Boolean isnew () method returns true if the session has not been in contact with the client program (browser). This is generally because the session is created, it is not caused by input customer requests.

However, if isnew returns false, it means that it has previously accessed the web application and does not mean that they have visited our servlet or JSP page.

Because the session is related to the user, a session may be created on every page accessed by the user. Therefore, if isnew is false, the user can only access the Web application before. The session can be created on the current page or on the previous page.

The correct method is to determine whether a specific key exists in a session and whether its value is correct.

24. What is the difference between cookie expiration and Session Timeout?

Session Timeout is maintained by the server, which is different from the cookie expiration date. First, the session is generally based on the cookie of the resident memory.

Because it is not a persistent cookie, there is no end date. Even if the cookie is intercepted to JSESSIONID and a expiry date is set for it to be sent. Browser sessions and Server sessions are also quite different.

25. Is the life cycle of session cookies the same as that of session objects?

When the user closes the browser, although the session cookie has disappeared, the session object is still stored on the server.

26. Does the session disappear as long as the browser is closed?

Generally, a program sends a command to delete a session when the user logs off. However, the browser never proactively notifies the server that the session will be closed before it closes, therefore, the server has no chance to know that the browser is closed. The server keeps the session object until it is inactive and exceeds the specified interval.

The reason for this error is that most session mechanisms use session cookies to store session IDs. When the browser is closed, the session ID disappears, the original session cannot be found when you connect to the server again.

If the cookie set by the server is saved to the hard disk, or the HTTP request header sent by the browser is rewritten by some means, the original session ID is sent to the server, then you can still find the original session when you open the browser again.

It is precisely because closing the browser will not cause the session to be deleted, forcing the server to set an expiration time for the session. When the last time the client used the session exceeds this expiration time, the server considers that the client has stopped the activity before deleting the session to save storage space.

Therefore, we can draw the following conclusions:

When the browser is closed, only session cookies in the browser memory will disappear, but the session objects stored on the server will not disappear, or the persistent cookies saved on the hard disk will not disappear.

. When you open two browser windows to access the application, the same session or different session will be used.

Generally, session cookies cannot be used across windows. When you open a new browser window to enter the same page, the system will give you a new session ID, in this way, we cannot achieve the purpose of information sharing.

In this case, we can first save the session ID in the persistent cookie (by setting the maximum session validity period), and then read it out in the new window, you can get the session ID of the previous window, so that we can achieve cross-window session tracking through the combination of session cookies and persistent cookies.

. How to Use sessions to display the number of visits per customer

Because the customer's access times are an integer variable, but the session attribute type cannot use int, double, Boolean and other basic types of variables, therefore, we need to use these basic types of encapsulation type objects as the attribute values of the session object.

However, integer is an immutable data structure that cannot be changed after being built. This means that each request must create a new integer object, and then use setattribute to replace the existing attribute values. For example:

Httpsession session = request. getsession ();

Someimmutalbeclass value = (someimmutableclass) Session. getattribute ("someidentifier ");

If (value = NULL ){

Value = new someimmutableclass (...); // Create a new unchangeable object

} Else {

Value = new someimmutableclass (calculatedfrom (value); // create an object after recalculating the value

}

Session. setattribute ("someidentifier", value); // use the newly created object to overwrite the old one.

19th. How to Use session accumulative user data

Use variable data structures, such as arrays, lists, maps, or proprietary data structures of applications containing writable fields. In this way, you do not need to call setattribute unless the object is assigned for the first time. For example

Httpsession session = request. getsession ();

Somemutableclass value = (somemutableclass) Session. getattribute ("someidentifier ");

If (value = NULL ){

Value = new somemutableclass (...);

Session. setattribute ("someidentifier", value );

} Else {

Value. updateinternalattribute (...); // If the object already exists, update its attributes without resetting the attributes.

}

Thirty. Different Processes of unchangeable objects and changeable objects when session data is updated

The object cannot be changed because it cannot be changed once created. Therefore, each time you want to modify the attribute value of a session, you must

Call setattribute ("someidentifier", newvalue) to replace the value of the original attribute. Otherwise, the attribute value will not be updated.

You can change an object because it generally provides a method to modify its own attributes.

You only need to call the method for modifying the attributes of the object. This means we do not need to call

The setattribute method is used.

Related Article

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.