Java_web Learning (8) session and State tube

Source: Internet
Author: User
Tags html header session id sessions

Introduction to HTTP

A question-and-answer interaction between a Web browser and a Web server must follow a certain rule, which is the HTTP protocol.      HTTP is shorthand for the Hypertext Transfer Protocol (Hypertext Transfer Protocol), an application-layer protocol in the TCP/IP protocol that defines the process of exchanging data between a Web browser and a Web server and the format of the data itself. Version of the HTTP protocol: http/1.0, http/1.1, Http-ngthe process of HTTP session mode Browser accessing multi-graph Web pages     The connection between the browser and the Web server is short-lived, and each connection only processes one request and response. Access to each page, the browser and the Web server to establish a separate connection. All communication between the browser and the Web server is completely separate from the request and response pairs.HTTP request message and Response messageStructure of the request message: A request line, a number of message headers, and the entity content, where some of the message headers and entity contents are optional, separated by a blank line between the message header and the entity content.       A request message that uses a GET method cannot contain entity content, and only the content of the entity can be contained in a request message that uses post, put, and delete methods.                            The structure of the response message: A status line, a number of message headers, and the entity content, where some of the message headers and entity contents are optional, separated by a blank line between the message header and the entity content. The entity content of the response message is the content of the Web page file, which is what you see in the browser using the view source file.HTTP message Header1> uses the message header to implement conditional requests and responses between the HTTP client and the server, which is equivalent to some cipher instructions between the server and the browser.       2> Each message header contains a header field name, followed by a colon, a space, a value, a carriage return, and a newline character.       3> message header field names are case-insensitive, but are used to capitalize the first letter of each word.        4> the message headers of each line in the entire message header can be sorted in any order.       5> message header can be divided into general information header, request header, response header, entity first Class four classes.       6> many request header fields allow clients to specify multiple acceptable options in the Value section, with multiple items separated by commas. 7> Some header fields can appear multiple times.request line and status lineRequest Line

Format: Request way Resource Path HTTP version number <CRLF> example: get/test.html http/1.1

Request method: POST, HEAD, OPTIONS, DELETE, TRACE, PUT

Status line

Format: HTTP version number status code reason description <CRLF> Example: http/1.1

passing parameters using get and postAfter the URL address can be appended with some parameters example: http://www.it315.org/servlet/ParamsServlet?param1=abc&param2=xyz get mode: 1) when When a user enters a URL address directly in the browser's address bar or clicks a hyperlink on a Web page, the browser uses get to send the request.
2) When the method property of a page line's form is set to "get", or the method property is not set (default is Get), the browser also sends the request using get when the form is submitted.

Format for passing parameters to the Web server using GET requests: http://www.it315.org/counter.jsp? name=zhangsan&password=123

The amount of data sent using get is generally limited to less than 1KB.

GET/SERVLET/PARAMSSERVLET?PARAM1=ABC&param2=xyz http/1.1   
Post mode: 1) The Post request method is mainly used to submit the data in form form to the Web server-side program, when the form is submitted, when the method property of the page line's form is set to "post", the browser uses POST to send the request.

2) The Post method sends the individual form field elements and their data to the Web server as the entity content of the HTTP message, which is much larger than the amount of data that is sent using the Get method.

The Enctype property of the <form> form element is used to specify which encoding method the browser uses to pass data from the form to the Web server, which can have two values:

Application/x-www-form-urlencodedmultipart/form-data
Post/servlet/paramsservlet http/1.1host:content-type:application/x-www-form-urlencodedcontent-length: 28PARAM1=ABC&param2=xyz

The difference between get mode and post mode:
When you submit a form by using GET, the browser attaches the individual form field elements and their data behind the resource of the request line as a URL parameter. The amount of data passed using get is limited and is generally limited to less than 1K.
When using post, the browser sends each form field element and its data to the Web server as the entity content of the HTTP message instead of being passed as a URL address parameter, so using post is much larger than using the Get method.

1>get is to fetch data from the server, and post is to transfer data to the server.

2> in the client, get mode in the URL to submit data, the data can be seen in the URL, post, data placed in the HTML header submitted.

3> for Get mode, the server side uses Request.QueryString to get the value of the variable, and for post, the server side uses Request.Form to get the submitted data.

The data submitted by the 4>get method can only have up to 1024 bytes, while post does not have this limitation.

5> security issues. As mentioned in 1>, when you use GET, the parameters are displayed on the address bar, and post does not. So, if the data is in Chinese and is non-sensitive, then use get; If the user enters data that is not a Chinese character and contains sensitive data, then it is better to use post.

Response Status Code

The response status code is used to represent the different processing results and status of the server to the request, which is a three-bit decimal number. Response status codes can be categorized into 5 categories, using the highest bits of 1 to 5来, as follows:

(1) 100~199 indicates that the request was successfully received, requiring the client to continue submitting the next request in order to complete the process. (2) 200~299 indicates that the request was successfully received and the entire process has been completed. (3) 300~399 to complete the request, the customer needs to further refine the request. For example, the requested resource has moved a new address. (4) The 400~499 client request has an error. (5) 500~599 server side error occurred.

200 (normal) indicates that everything is normal and returns the normal request result. 206 (partial) The client sends a GET request with a range header (which requires the server to return only a portion of the document), and the server completes the request as requested. 302/307 (Temporary redirect) indicates that the requested document has been temporarily moved elsewhere, and the new URL for this document is given in the location response header. 304 (unmodified) indicates that the client cache version is up-to-date and the client should continue to use it. 401 (unauthorized) indicates that the client is accessing a password-protected page with a www-authenticate response header prompting the client to re-issue a request message with a authorization header. 404 (Not found) the resource requested by the client does not exist on the server. 500 (internal server error) a server-side CGI, ASP, JSP, and other programs have an error.

General Information Header

The Common Information header field can be used both for request messages and for response messages, including some common message header fields that have no relation to the entity content being transferred.

Cache-control:no-cache    connection:close/keep-alive     date:tue, 18:23:51 gmtpragma:no-cache           Trailer:date transfer-encoding:chunked    upgrade:http/2.0, shttp/1.3 via:http/1.1 Proxy1, http/1.1 Proxy2   

Request Header

The Request header field is used by the client to pass additional information to the server in the request message, mainly including information such as the type of data that the client can accept, the compression method, the language, and the URL address of the webpage to which the requested hyperlink belongs.
accept:text/html,image/*    accept-charset:iso-8859-1,unicode-1-1  accept-encoding:gzip,compress  ACCEPT-LANGUAGE:EN-GB,ZH-CN authorization:basic enh4ojeymzq1ng== expect:100-continuefrom: [email protected] host:www . it315.org:80   If-match: "Xyzzy", "r2d2xxxx" If-modified-since:tue, Jul 18:23:51 GMT if-none-match: "Xyzzy", " R2d2xxxx "If-range:tue, One Jul 18:23:51 gmtif-unmodified-since:tue, one Jul 18:23:51 gmtmax-forwards:1 Proxy-Au Thorization:basic enh4ojeymzq1ng==range:bytes=100-599     range:bytes=100-     

Response Header

The Response header field is used by the server to pass additional information to the client in the response message, including information such as the name of the service program, the authentication method required by the requested resource, and the new address to which the requested resource has been moved.

Solid Head

Entity headers are used as meta-information for entity content, describing the attributes of entity content, including entity information type, length, compression method, last modification time, data expiration, and so on.
Allow:get,postcontent-encoding:gzip CONTENT-LANGUAGE:ZH-CN content-length:80 content-location:http:// www.it315.org/java_cn.html content-md5:abcdabcdabcdabcdabcdab== content-range:bytes 2543-4532/7898 content-type: text/html; charset=gb2312 expires:tue, One Jul 18:23:51 gmtlast-modified:tue, one Jul 18:23:51 GMT

Expansion Head

In the HTTP message, you can also use some header fields that are not defined in the HTTP 1.1 formal specification, which are collectively referred to as custom HTTP headers or extension headers, which are often treated as a solid header. Today's popular browsers actually support several commonly used extension header fields such as cookies, Set-cookie, refresh, and content-disposition.
// Refresh header field        Refresh:1         1;url=http://www.it315.org//content-disposition header field           content-type:application/octet-stream        Content-disposition:attachment; filename= Aaa.zip

problem

The HTTP protocol is a stateless protocol, and the Web server itself does not recognize which requests are made by the same browser, and every request from the browser is completely isolated.       Even though the HTTP1.1 supports persistent connections, the connection is closed when the user has not submitted a request for a period of time. How to realize the shopping cart in the online store: When a user logs in from the login page of the website and then enters the shopping page, the server program responsible for processing the purchase request must know the user information from the program that processed the last request. As a Web server, you must be able to use a mechanism to uniquely identify a user and record the state of that user.      sessions and Session state

A session in a web app is a sequence of request and response processes that occur continuously between a client browser and a Web server. the session state of a Web application refers to the state information generated by the Web server and the browser during the session, and with the use of Session state, the Web server can associate a series of request and response processes that are part of the same session.

To implement a stateful session

The Web server-side program is able to distinguish from a large number of request messages which request messages belong to the same session, that is, to identify access requests from the same browser, which requires the browser to identify each request message it sends: The same identification number is included in the request message that belongs to the same session. A request message that belongs to a different session always comes with a different identification number, which is called the session ID (SessionID). in the Servlet specification, the following two mechanisms are used to complete session tracking cookies and sessions.

Cookie mechanism

The cookie mechanism uses a scheme that maintains HTTP status information on the client.

A cookie is a small text file that is delivered to the browser by the Web server in the HTTP response message header when a browser accesses a resource on the Web server. Once a cookie has been saved by the Web browser, it will be passed back to the Web server in the HTTP request header each time it accesses the Web server.

The underlying implementation principle: The Web server sends cookie information to the browser by adding the Set-cookie response Header field to the HTTP response message, and the browser passes the cookie back to the Web server by adding the cookie Request header field to the HTTP request message.

A cookie can only identify a single message that contains at least one name and set value (value) that identifies the information. A Web site can send multiple cookies to a Web browser, and a Web browser can store cookies provided by multiple Web sites. Browsers generally allow only 300 cookies, with a maximum of 20 cookies per site and a limit of 4KB per cookie size.

using cookies in a servlet program

A Javax.servlet.http.Cookie class is provided in the Servlet API to encapsulate cookie information, which contains methods for generating cookie information and extracting individual attributes of cookie information.

 //Public  
A Addcookie method is defined in the HttpServletResponse interface that is used to add a Set-cookie response header field to the HTTP response message sent to the browser. The HttpServletRequest interface defines a getcookies method that is used to read all cookie entries from the cookie Request header field of an HTTP request message.Sending of Cookies1> Create a Cookie object 2> set maximum aging 3> Put a cookie into the HTTP response header if a cookie is created and sent to the browser, by default it is a session-level COO Kie 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 maximum aging to 0 is the command browser to delete the cookie. Sending a cookie requires the use of the HttpServletResponse Addcookie method to insert the cookie into a Set-cookie HTTP response header. Since this method does not modify any of the previously specified Set-cookie headers, it creates a new header, so this method is called Addcookie, not Setcookie.the difference between a session cookie and a persistent cookieIf you do not set an expiration time, the cookie disappears when the browser window is closed as long as the cookie's lifetime is the browser session. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not saved on the hard disk but in memory. If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and these cookies remain valid until the set expiration time expires. 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 ways of handling them.reading of Cookies1>.      Call Request.getcookies, to get the cookie sent by the browser, you need to call HttpServletRequest's GetCookies method, which returns an array of cookie objects corresponding to the value entered by the cookie header in the HTTP request. 2> loops the array, invoking the GetName method of each cookie until the cookie of interest is found.notes on using cookie attributesProperties are part of the header that is sent from the server to the browser, but they do not belong to the header returned to the server by the browser. Therefore, in addition to the name and value, the cookie attribute applies only to cookies exported from the server to the client, and the server-side cookie from the browser does not have these attributes set.session mechanismThe session mechanism uses theServer-SideScenarios that maintain HTTP status information. The server uses a hash-like structure (or perhaps a hash table) to hold the information. When a program needs to create a session for a client's request, the server first checks to see if the client's request contains a session ID (that is, SessionID), and if it already contains a SessionID, it has previously created a session for this customer. , the server will use the session ID to retrieve this session (if it is not retrieved, may create a new one, this situation may appear on the service side has deleted the user corresponding Session object, However, the user manually appends the previous jsession parameter to the requested URL. If a customer request does not contain SessionID, a session is created for this customer and a SessionID associated with this session is generated, and the session ID is returned to the client in this response.

Java_web Learning (8) session and State tube

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.