Home > Java > javaTutorial > body text

Explanation of sessions and session states of cookies and sessions

巴扎黑
Release: 2017-07-17 14:30:29
Original
2012 people have browsed it

1. Session Overview

1)Phenomenon:HTTP protocol is a stateless protocol, which cannot be recognized by the Web server itself Which requests are issued by the same browser, each request of the browser is completely isolated.

2) Solution: With the help of session state, the Web server can associate a series of requests and response processes belonging to the same session.

3) Implementation: Requires the browser to identify each request message it sends. This identification is called session ID (SessionID).

2. Cookie

1: There are two types Type of cookie:

1> Session cookie (session cookie)

If no expiration time is set, it means that the life cycle of this cookie is during the browser session. As long as the browser window is closed, the cookie will disappear. .

The lifetime is the browser session.

Generally it is not saved on the hard disk but in the memory.

2>Persistent cookies (persistent cookies)

If the expiration time is set, the browser will save the cookies to the hard disk. After closing and opening the browser again, these cookies will still be valid until the expiration date is exceeded. The set expiration time.

Saved on the user's hard drive and can be obtained by the same browser.

2: Session related knowledge

2.1: What is session?

Session is a mechanism for saving contextual information. It is for each user. The value of the variable is saved on the server side. Different clients are distinguished through sessionid. Session is based on cookie or url rewriting. .

2.2: How session works

client————>1.request————————->server

              2. session_start( );

|<————-3.reponse(SESSION_ID)<——–|

|————->4.request(SESSION_ID)—— —>|

                5. session_start();

  |<————-6.reponse(SESSION_ID)<———|

 | ————->7. request(SESSION_ID + logout)–>|

              8. session_destroy();

|<————-9. response(delete cookie File)<——-|

client opens the web page and makes a request to the server. Since there is no corresponding cookie file on the client, it is not sent in the request. SESSION_ID

After receiving the client's request, the server starts processing the session by executing the session_start() function. First, confirm whether there is a SESSION_ID in the request. If not, issue a new SESSION_ID; if so, , then call the file containing SESSION_ID, write the information into $_SESSION, and store it in the file starting with sess_.

Send the $_SESSION parameter of the written information back to the client. After the client gets the information sent by the server, it saves the information in the cookie.

The client writes the SESSION_ID in the cookie into the header and sends a request to the server again. Repeat operations 1-3

client issues a logout request

After the server accepts the request, it starts deleting the session file by executing the session_destroy() function

The server sends a delete request to the client Command to save the cookie file on the client: setcookie(session_name(), ”, time()-60, '/');

2.3: Note

Normally, it cannot be used across windows, but the sessionid is saved in a persistent cookie, and then read from a new window to get the sessionid to achieve cross-window use.

In websites with large page views, Session is not safe, and there may be duplicate sessionid.

Session ID cannot be obtained from the cookie file on the hard disk. If you want to know your Session ID on the client, you can only read it through Javascrīpt.

2.4 PHP usage and settings

Session_start(): Start a session or return an existing session. The browser cannot have any output before using Session_start(), otherwise it will The following error occurred. You can enable session.auto_start=1 in php.ini, so that you do not need to call session_start() every time you use the session.

If session.auto_start=1, session_save_path (‘./t/’); will become invalid. Because the latter statement must be placed first.

2.5 Increase PHP’s Session storage and processing capabilities

;session.save_path = “N;MODE;/path” This setting allows us to store the session The directory performs multi-level hashing, where "N" represents the directory level to be set,

"MODE" represents the permission attribute of the directory, the default is 600

2.6 :Multiple servers sharing php SESSION

1. NFS or Samba sharing method allows the disks storing session files on each server to be shared. This method is simple and feasible.

2. Centralized storage in the database. This is a relatively common implementation method. The session function is redefined through the session_set_save_handler() function provided by PHP. This method is recommended.

3: Cookie knowledge

What is Cookie? How does it work? A cookie is a small piece of text information that is passed between a web server and a browser along with user requests and pages. The information contained in the cookie can be read by the web application each time the user visits the site. Basics of How Cookies Work If a user returns to a page on the site and enters the URL www.*****.com, the browser looks for a cookie associated with that URL on the local hard drive. If the cookie exists, the browser sends it to your site with the page request. What are the uses of cookies? The most fundamental purpose is: Cookies can help Web sites save information about visitors. More generally, cookies are a way to maintain the continuity of Web applications (that is, perform "state management"). Let the Web site remember you.

1. The client executes the program and requests the server to send back a request As a result, a cookie is generated to the client, so the cookie will appear when refreshing for the second time.
2. The session is stored in the memory and exists at the same time as the process, but at this time the server still saves the session cookie. The session file needs to set the time to delete the session file
3. Cookie saves some information in the local Cookie file, and the Cookie file saves key-value pairs. Cookie files are stored in the Document and Settings/Username directories of your local computer system disk. If the name of the website you visit is www.abc.com, then generally speaking, the name of the cookie file is username@abc.com. You can open the folder and take a look. The getName you mentioned obtains the key value of a cookie stored in the cookie file.

We know that session is a method to maintain user session data on the server side, and the corresponding cookie is to maintain user data on the client side. The HTTP protocol is a stateless protocol. After the server responds, it loses contact with the browser. At the earliest, Netscape introduced cookies into the browser so that data can be exchanged across pages by the client. So how does the server remember the sessions of many users? What about data?
First of all, the client and server must be contacted one by one. Each client must have a unique identifier so that the server can identify it. It is recommended that there are two methods of unique identification: cookie or specified through GET. The default configuration of PHP will create a cookie named "PHPSESSID" when using a session (can be specified by modifying the session.name value in php.ini). If the client disables cookies, you can also specify to pass the session id to via GET. Server (modify parameters such as session.use_trans_sid in php.ini).
When we look at the server-side session.save_path directory, we will find many files similar to sess_vv9lpgf0nmkurgvkba1vbvj915. This is actually the data corresponding to the session id "vv9lpgf0nmkurgvkba1vbvj915". The truth is here, the client passes the session id to the server, and the server uses the session id Find the corresponding file, deserialize the file content when reading, and get the session value. When saving, serialize first and then write.

1. Concept

1)

Meaning: In the Web development environment, session refers to a class used on the client The solution for maintaining state with the server is sometimes used to refer to the storage structure of this solution.

#2) Mechanism: is adopted on the server side. Keep HTTP status information

3) Principle:

##When creating a session. Check whether the client's request contains a session identifier (i.e. sessionID), that is, whether the request stores a cookie

    named "JESESSIONID" with a value of sessionID.
  • If it already exists, retrieve it and use it,

  • Otherwise, create a session for this client, generate a sessionID associated with this session, and pass it to the request using set-cookie. Then the next request will be used. This sessionID is passed as a value in the cookie named "JESESSIONID".

4) Save method: The most commonly used is to save with cookies. But if cokkie is disabled, there must be another mechanism for preservation. Such as URL rewriting: append sessionID to the end of the URL path.

5) Note: Since it is usually saved using cookies, if you make the cookie persistent, you can get it even after restarting the browser. sessionID.

//用持久化cookie保存sessionIDCookie cookie = new Cookie("JESESSIONID",session.getId());
cookie.setMaxAge(20);
response.addCookie(cookie);
Copy after login

2. Session creation

1) Session attribute :

  • If the Session attribute specified by page defaults to true, then the first time you access a JSP page of a WEB application , the page must have a Session object associated with this request.

  • Otherwise, the JSP page will not require that there must be a Session object associated with the current JSP page, so a Session will not be created when the JSP page is accessed for the first time. .

2) request.getSession(boolean flag):

  • ##true, an HttpSession object will be returned. If there is already an HttpSession object associated with the current JSP page, it will be returned directly; if not, a new one will be created.

  • #false, if there is no HttpSession object associated with the current JSP page, return null, otherwise return the obtained HttpSession object.

  • request.getSession() is equivalent to request.getSession(true).

3. Destruction of Session object

1) Call HttpSession invalidate() method.

2) The HttpSession is automatically destroyed after the expiration time. You can configure the maximum session aging in Tomcat's web.xml file, in minutes.

<!-- apache-tomcat-x.x.xx\conf\web.xml --><session-config><session-timeout>30</session-timeout></session-config></p>
<div class="cnblogs_code">
<p> </p>
<p><span style="color: #000000"><em>相关方法签名:</em></span></p>
<ul class=" list-paddingleft-2">
<li><p><span style="color: #000000">int getMaxInactiveInterval()                         //返回最大时效,单位:秒</span></p></li>
<li><p><span style="color: #000000">void setMaxInactiveInterval(int interval)      //设置最大时效</span></p></li>
</ul>
<p><span style="color: #000000">3)服务器卸载当前 WEB 应用。</span></p>
<p> </p>
<h2><span style="color: #000000">4.Session相关方法</span></h2>
<p><span style="color: #000000">String getId()                                                       //得到sessionID</span></p>
<p><span style="color: #000000">boolean isNew()                                                  //该session是不是新创建的<br></span></p>
<p><span style="color: #000000">long getCreationTime()                                       //该session被创建的时间<br></span></p>
<p><span style="color: #000000">long getLastAccessedTime()                              //该session最后一次被访问的时间</span></p>
<p><span style="color: #000000">void <span style="color: #ff0000">setAttribute</span>(String key, Object value)         //存放值,相当于哈希表<br></span></p>
<p><span style="color: #000000">Object <span style="color: #ff0000">getAttrbute</span>(String key)                           //根据键从session中取得对应的值</span></p>
<p> </p>
<h2><span style="color: #000000">5.URL重写实现Session跟踪</span></h2>
<p><span style="color: #000000"><em>方法签名:</em>String encodeURL(String url)  //该方法会在URL后面加上sessionID</span></p>
<div class="cnblogs_code"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">重新登录
Copy after login
Copy after login
重新登录
Copy after login

 

The above is the detailed content of Explanation of sessions and session states of cookies and sessions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Previous article:Example analysis of two methods in Java to realize centered display of form Next article:Java compression and decompression of files
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template