Cookie, session and realize remembering password, automatic login

Under the login account and password boxes, there are three account login modes to choose from, and users can choose one of the modes that suits them according to their specific conditions.

  1. Internet cafe mode: After checking the Internet cafe mode, the logged-in account will be automatically cleared when you log out or log out, and will not be left in the login box, which can protect your account from being leaked to the outside world. It is recommended to use it when surfing the Internet in other places. For example, when logging in to an Internet cafe or other people's machines.

  2. Remember password: After checking Remember password, the system will remember the account and password you have logged in. After logging out, the account and password will be automatically saved in the login box. After logging out, the account and password will automatically appear in the login box. frame. To facilitate the next login, it is recommended to use it on your own computer to avoid unnecessary losses.

  3. Automatic login: After remembering the password, check "Auto login", so that the next time you log in, the account and password you remembered last time will be defaulted to automatically connect and log in.

 

1. The difference between the cookie mechanism and the session mechanism
  Specifically, the cookie mechanism adopts the scheme of maintaining the state on the client side, while the session mechanism adopts the scheme of maintaining the status on the server side.
  At the same time, we also see that since the solution of maintaining state on the server side also needs to save an identifier on the client side, the session mechanism may need to rely on the cookie mechanism to achieve the purpose of saving the identifier, but there are actually other options.
Second, the difference between session cookie and persistent cookie
  If the expiration time is not set, it means that the cookie life cycle is during the browser session , as long as the browser window is closed, the cookie will disappear. A cookie whose lifetime is the browsing session is called a session cookie . Session cookies are generally not stored on hard disk but in memory.
  If the expiration time is set, the browser will save the cookie to the hard disk. After closing and opening the browser again, these cookies are still valid until the set expiration time is exceeded .
  Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different handling methods.
3. How to use to achieve automatic login
  When a user registers on a website, he will receive a cookie with a unique user ID. When the client reconnects later, this user ID is automatically returned, and the server checks it to see if it is a registered user with automatic login selected, allowing the user to access resources on the server without giving an explicit username and password .
Fourth, how to customize the site according to the user's hobbies
  Websites may use cookies to record the wishes of users. For simple settings, the website can directly store the page's settings in a cookie to complete the customization. For more complex customizations, however, the website simply sends a unique identifier to the user, and the server-side database stores the page settings for each identifier.
Five, cookie sending
1. Create a cookie object
2. Set the maximum time
limit 3. Put the cookie into the HTTP response header
  If you create a cookie and send it to the browser, it is a session-level cookie by default : Stored in the browser's memory and 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 the maximum duration to 0 instructs the browser to delete the cookie.
  Sending a cookie requires inserting the cookie into a Set-Cookie HTTP request header using the addCookie method of HttpServletResponse. Since this method does not modify any previously specified Set-Cookie headers, but rather creates new ones, we call this method addCookie instead of setCookie. Also keep in mind that response headers must be set before any document content is sent to the client.
Six, cookie reading
1. Call request.getCookie
  To get the cookie sent by the 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 through the array and call the getName method of each cookie until the cookie of interest is found
  Cookies are associated with your host (domain), not your servlet or JSP page. Thus, although your servlet may only be sending a single cookie, you may also get many unrelated cookies.
For example:
  String cookieName = "userID";
    Cookie cookies[] = request.getCookies();
    if (cookies!=null){
        for(int i=0;i<cookies.length;i++){
    Cookie cookie = cookies[i ];
    if (cookieName.equals(cookie.getName())){
        doSomethingWith(cookie.getValue());
}
}
}
7. How to use cookies to detect first-time visitors
A. Call HttpServletRequest.getCookies() to get an array of cookies
B. Retrieve in the loop whether the cookie with the specified name exists and whether the corresponding value is correct
C. If so, exit the loop and set the distinguishing mark
D. Determine whether the user is a first-time visitor according to the distinguishing mark and perform different operations
Eight, use cookie to detect the initial Common visitor mistakes
  A user cannot be considered a first-time visitor just because a particular item of data is not present in the cookie array. If the cookie array is null, the client may be a first-time visitor, or it may be the result of the user deleting or disabling cookies.
  However, if the array is non-null, it just shows that customers have been to your website or domain, not that they have visited your servlet. Other servlets, JSP pages, and non-Java Web applications can set cookies, and depending on the path, any cookie may be returned to the user's browser.
  The correct way is to judge whether the cookie array is empty and whether the specified Cookie object exists and the value is correct.
9. Notes on using cookie attributes
  Attributes are part of the header sent from the server to the browser; but they are not part of the header returned by the browser to the server. 
  So aside from the name and value, the cookie attributes only apply to cookies sent from the server to the client; server-side cookies from the browser do not have these attributes set. 
  So don't expect this property to be used in cookies obtained via request.getCookies. This means that you can't achieve a constantly changing cookie value just by setting the maximum age of the cookie, issuing it, looking for the appropriate cookie in the subsequent input array, reading its value, modifying it and saving it back into the cookie .
10. How to use cookies to record the visit count of
each
user
Object 4.
Reset the maximum   duration A series of processes from picking up the phone and dialing to hanging up can be called a session.



  However, when the term session is associated with a network protocol, it often implies "connection-oriented" and/or "state-keeping".
  The semantics of session in the Web development environment has a new extension, and its meaning refers to a class of solutions used to maintain state between the client and the server. Sometimes Session is also used to refer 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 table (that is, a hash table may be used) to store information.
  But when the program needs to create a session for a client's request, the server first checks whether the client's request contains a session identifier - called session id. If it already contains a session id, it means that it has been created for this client before. session, the server retrieves and uses the session according to the session id (if it cannot be retrieved, it may create a new one, which may occur when the server has deleted the session object corresponding to the user, but the user artificially requests the URL followed by a JSESSION parameter).
  If the client request does not contain a session id, a session will be created for the client and a session id associated with the session will be generated. This session id will be returned to the client for saving in this response.
Thirteen, several ways to save session id
A. The way to save the session id can use a cookie, so that the browser can automatically send this identifier to the server according to the rules during the interaction process.
b. Since cookies can be artificially disabled, there must be some other mechanism to pass the session id back to the server when the cookie is disabled. A technique often used is called URL rewriting, which appends the session id to the URL path. There are also two ways of appending, one is as additional information of the URL path, and the other is as a query string appended to the URL. For the network to maintain state throughout the interaction, this session id must be included after every path a client might request.
c. Another technique is called form hidden fields. That is, the server will automatically modify the form to add a hidden field so that the session id can be passed back to the server when the form is submitted.
14. When is the session created?
  A common mistake is to think that the session is created when a client accesses it, but the fact is that it will not be created until a server-side program (such as Servlet) calls a statement such as HttpServletRequest.getSession(true) was created.
15. When is the session deleted
? The session is deleted under the following circumstances:
A. The program calls HttpSession.invalidate()
B. The time interval from the last time the session id sent by the client is received exceeds the maximum valid time of the session
C. The server process is stopped
  Note again that closing the browser will only invalidate the session cookie stored in the client browser's memory, not the server-side session object.
16. What are the disadvantages of URL rewriting?
  Use URL rewriting for all URLs, including hyperlinks, form actions, and redirected URLs. Add extra information to every URL that refers to your site, and those that are returned to the user (even by indirect means, such as the Location field in a server redirect).
  This means that you cannot have any static HTML pages on your site (at least the static pages cannot have any links to the dynamic pages of the site). Therefore, each page must be dynamically generated using servlets or JSPs. Even if all pages are dynamically generated, if the user leaves the session and comes back again via a bookmark or link, the session information will be lost because the stored link contains the wrong identification information - the SESSION ID after the URL has expired.  
17. What are the disadvantages of using hidden form fields?
    This method can only be used when each page is dynamically generated with a form submission. Clicking on a regular <A HREF..> hypertext link does not result in a form submission, so hidden form fields cannot support the usual session tracking and can only be used in a series of specific operations, such as the checkout process for an online store
. , The basic steps of session tracking
1. 2. Access the session object associated with the current request
. Find information related to the session
3 . 4. Store session information
. Abandoned session data
19. The difference between
getSession()/getSession(true) and getSession(false) getSession()/getSession(true): Return the session when the session exists, otherwise create a new session and return the object
getSession(false) : Return the session when the session exists, otherwise it will not create a new session and return null
20. How to associate information with the session
  setAttribute will replace any previously set value; if you want to remove it without providing any replacement a value, removeAttribute should be used. This method triggers the valueUnbound method of all values ​​that implement the HttpSessionBindingListener interface.
21. Are there any restrictions on the type of
  session attributes? Usually, the type of session attributes only needs to be Object. Except null or primitive types like int, double, boolean.
  If you want to use the value of the basic type as an attribute, it must be converted into the corresponding encapsulated class object
22. How to discard the session data
A. Only remove the data created by the servlet written by yourself:
   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. Doing so will lose all session data for that user, not just the session data created by our servlet or JSP page
C. Calls logOut to log the user out of the system and delete all sessions belonging to him (or her)
   , log the client out of the web server, and discard all sessions associated with the user (at most one per web application). This action has the potential to affect several different web applications on the server.
23. The wrong practice of using isNew to judge whether the user is a new or old user
  public boolean isNew() method If the session has not had any contact with the client program (browser), this method returns true, which is generally because the session is newly created , not caused by an incoming client request.
  But if isNew returns false, it just means that he has visited the web application before, not that they have visited our servlet or JSP page.
  Because sessions are associated with users, every page the user has visited before has the potential to create a session. Therefore, if isNew is false, it can only mean that the user has visited the web application before, and the session can be created by the current page or by a page the user has visited before.
  The correct way is to judge whether there is a specific key in a session and its value is correct
. 24. What is the difference between Cookie expiration and Session timeout?
  The session timeout is maintained by the server, which is different from the Cookie expiration date. . First, session-based cookies that reside in memory are generally not persistent cookies and therefore have no expiration date. Even if the JSESSIONID cookie is intercepted, and an expiration date is set for it, it is sent out. Browser sessions and server sessions are also distinct.
25. Is the life cycle of the session cookie and the session object the same?
  When the user closes the browser, although the session cookie has disappeared, the session object is still stored on the server side
26. Does the session disappear as long as the browser is closed ?
  The program generally sends an instruction to delete the session when the user logs off, but the browser never actively informs the server that it will be closed before closing, so the server has no chance to know that the browser has been closed. The server will keep this session object until it is inactive for more than a set interval.
  The reason for this misunderstanding is that most session mechanisms use session cookies to save the session id, and the session id disappears when the browser is closed, and the original session cannot be found when connecting to the server again.
  If the cookie set by the server is saved to the hard disk, or some method is used to rewrite the HTTP request header sent by the browser, and the original session id is sent to the server, the original session can still be found by opening 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 time since the client last used the session exceeds this expiration time, the server can consider that the client has stopped activities. The session will be deleted to save storage space.
  From this, we can draw the following conclusion:
  closing the browser will only make the session cookie in the memory of the browser disappear, but will not make the session object saved on the server disappear, nor will it make the persistent cookie saved on the hard disk. The cookie disappears.
27. Opening two browser windows to access the application will use the same session or different sessions.
  Usually, session cookies cannot be used across windows. When you open a new browser window and enter the same page, the system will grant you A new session id, so the purpose of our information sharing will not be achieved.
  At this point, we can first save the session id in the persistent cookie (by setting the maximum valid time of the session), and then read it in the new window to get the session id of the previous window, so that through the session cookie and persistent cookie Combined, we can achieve cross-window session tracking.
28. How to use session to display the number of visits of each customer
  Since the number of visits of a customer is an integer variable, but basic types of variables such as int, double, and boolean cannot be used in the attribute type of session, so we need to use These basic types of encapsulated type objects are used as the values ​​of properties in the session object,
  but like Integer is an immutable data structure: it cannot be changed after construction. This means that each request must create a new Integer object, and then use setAttribute to replace the value of the old attribute that existed before. E.g:
HttpSession session = request.getSession();
SomeImmutalbeClass value = (SomeImmutableClass)session.getAttribute("SomeIdentifier");
if (value= =null){
    value = new SomeImmutableClass(…); // create a new immutable object
}else {
    value = new SomeImmutableClass(calculatedFrom(value)); // recalculate the value to create a new object
}
session.setAttribute("someIdentifier",value); // overwrite the old object with the newly created object
twenty Nine, how to use the session to accumulate user data
  Use mutable data structures, such as arrays, Lists, Maps, or application-specific data structures with writable fields. In this way, you don't need to call setAttribute unless the object is allocated 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, unchangeable objects and changeable objects are in Different processing of session data update
  Unchangeable objects cannot be changed once they are created, so every time you want to modify the value of an attribute in the session, you need to call setAttribute("someIdentifier", newValue) to replace the original attribute value , otherwise the value of the attribute will not be updated. The modifiable object generally provides a method to modify its own attributes, so every time you want to modify the value of the attribute in the session, you only need to call the related method of the modifiable object to modify its own attribute. That's it. This means that we don't need to call the setAttribute method.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326772354&siteId=291194637