Discussion on the client and application server-side interaction principle of Java Web Program

Source: Internet
Author: User
Tags object serialization response code file transfer protocol

Recently, I've been thinking about a question why Formbean need to be serialized when developing with the struts framework, That is, the realization of java.io.Serializable interface, the spirit of diligent to ask me Google the next object serialization aspects of the article, although the general understanding of how to do, but still do not know why to do so; Finally, I want to solve a problem to find the root and nature of the problem, and then from the Web application client and server side The principle of mutual, and finally found the answer I want.
1. What is Object serialization?
Simply put, Java object serialization is to save the Java objects in memory (persisted) so that the data in this object can be transmitted over the network or continue to be used in the future. The process of serialization is that the object writes the byte stream and reads the object from the byte stream. After you convert the object state to a byte stream, you can save it to a file with various byte stream classes in the Java.io package, pipe to another thread, or send the object data to another host over a network connection. Serialization consists of two parts: serialization and deserialization. Serialization is the first part of this process that decomposes data into a byte stream for storage in a file or on a network. Deserialization is the opening of a byte stream and refactoring the object.
2. Agreement
A. Overview of the overall architecture of TCP/IP
The TCP/IP protocol does not fully conform to the OSI seven-layer reference model. The traditional open System Interconnect Reference Model is a 7-layer abstract reference Model for communication protocols, where each layer performs a specific task. The purpose of this model is to enable various hardware to communicate with each other at the same level. These 7 layers are: Physical layer, Data link layer, network layer, transport layer, Session layer, presentation layer and application layer. The TCP/IP protocol uses a 4-tier hierarchy, each of which calls the network provided by its next layer to fulfill its own needs. These 4 layers are:
I. Application layer: Layers of communication between applications, such as Hypertext Transfer Protocol (HTTP), simple e-mail Transport (SMTP), File Transfer Protocol (FTP), Network Remote Access Protocol (Telnet), and so on.
II. Transport layer: In this layer, it provides data transfer services between nodes, such as Transmission Control Protocol (TCP), User Datagram Protocol (UDP), and so on, TCP and UDP to the packet into the transmission of data and transfer it to the next layer, this layer is responsible for transmitting data, and to determine that the data has been delivered and received.
III. Interconnection Network layer: responsible for providing basic data packet transfer function, so that each packet can reach the destination host (but not check whether it is received correctly), such as Internet Protocol (IP).
Iv. Network Interface layer: the management of the actual network media, define how to use the actual network (such as Ethernet, Serial line, etc.) to transfer data.
B. Introduction to the HTTP protocol:
I. HTTP is a Hypertext Transfer Protocol (hypertext Transfer Protocol), which is a set of rules for computers to communicate in a network. In the TCP/IP architecture, HTTP belongs to the application-layer protocol, at the top level of the TCP/IP protocol
II. HTTP is a stateless protocol that means that there is no need to establish a persistent connection between a Web browser (client) and a Web server. The whole process is when a client sends a request to the server, and then the Web server returns a response (response), then the connection is closed and the connection is not retained at the end of the service.
III. HTTP follows the request/response (Request/response) model, and all communication interactions are constructed in a set of request and response models.
Iv. when browsing the web, the browser exchanges information with the Web server through the HTTP protocol, and the files returned by the Web server to the Web browser have types associated with them, and the format of the information types is defined by MIME.
C. The Java implementation of the Protocol whether it is TCP/IP protocol or HTTP protocol, Java is through the socket (java.net.Socket) to achieve, you can refer to my other technical blog: a project look at Java TCP/IP Socket programming ( Version 1.3)
3. HTTP message interface and client and server-side interaction principles
A. HTTP-defined transactions consist of the following four steps:
I. Establish a connection:
For example, when I enter http://cuishen.javaeye.com in a browser, the client requests this address by opening a socket on the Web server HTTP port. Because in the middle of the network as the transmission of data is the physical media is the network cable, the data is essentially through the IO stream output and input, it is not difficult to understand why we write a servlet to reference the import java.io.*; , including the println () method of the PrintWriter object when we send the results back to the client. In fact, the address of the request to add the port number 80,80 can not write, because the default browser port number is 80.
This is true in Java's underlying code, except that they have done it for us.

[Java]View Plaincopyprint?
    1. Socket socket = new socket ("cuishen.javaeye.com",80);
    2. InputStream in = Socket.getinputstream ();
    3. OutputStream out = Socket.getoutputstream ();
Socket socket = new Socket ("cuishen.javaeye.com"), InputStream in = Socket.getinputstream (); OutputStream out = Socket.getoutputstream ();

II. Client sending HTTP request message (requests)
Once a TCP connection is established, the Web browser sends a request command to the Web server, which is an ASCII text request line followed by 0 or more HTTP headers, a blank line, and any data that implements the request.
That is, the message is divided into four parts: the request line, the request header, the blank line and the request data
1) The request line request line consists of three tokens: The request method, the request URL, and the HTTP version, separated by a space
Example: GET cuishen.javaeye.com/blog/242842 http/1.1
The HTTP specification defines 8 possible request methods: (most commonly, GET and POST two methods)
Get--Retrieves a simple request to identify a resource in the URI HEAD--As with the Get method, the server returns only the status line and header, and does not return the request document POST--the server accepts a request to be written to the data in the client output stream--the server holds the request data as the new content of the specified URI. Request Delete--The server removes requests for resources named in the URI OPTIONS--Requests for information about the requested methods supported by the server TRACE--Web server feedback HTTP request and its header request CONNECT--a method that has been documented but is not currently implemented, which is reserved for tunneling Road processing
2) Request Header
Request Header: Consists of key:value health values, one pair per line. The request header is used to inform the server about the functionality and identity of the client.
Host--which server-side address, primary address of the request, such as: My technology blog:cuishen.javaeye.com user-agent-The user is the client can use the browser, such as: mozilla/4.0 Accept-- The list of MIME types that the client can accept, such as Image/gif, text/html, Application/msword Content-length--Applies only to post requests, with bytes giving the size of the post data
3) Blank line
Send carriage returns and regressions, notifying the server that the header is no longer available.
4) Request data
Using post to transmit data, the most commonly used is the Content-type and content-length headers.
Request Message Summary: We can write a standard HTTP request like this:
post/blog/242842 HTTP1.1 host:cuishen.javaeye.com/
user-agent:mozilla/4.0 accpt:image/gif,text/html,application/pdf,image/png ...
Key=value&key=value&key=value ... (POST () requested data)
One example of this above means that the server-side address I'm going to visit is cuishen.javaeye.com/resources under it/blog/242842
Connect up is: cuishen.javaeye.com/blog/242842 This page with the HTTP1.1 specification, my browser version is mozilla/4.0 can support the MIME format for image/gif,text/html, Application/pdf,image/png ... Wait a minute
The MIME format we are writing in the servlet is: Response.setcontenttype ("text/html;charset=gb2312");
Or in JSP, the wording is: <%@ page contenttype= "text/html;charset=gb2312"%>
or the wording in HTML is: <meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
The most intuitive difference between get and POST is that the Get method follows the requested URL, which is what we do in the request line:
Get/blog/242842?key=value&key=value&key=value ... HTTP1.1
Actually, the data is passed in this way with GET:
http://cuishen.javaeye.com/?page=2 ...
Iii. server-side response requests generate results and postback (response)
The WEB server resolves the request and locates the specified resource http://cuishen.javaeye.com/blog/242842
1) According to the get/post of the request, the doget ()/DoPost () method in the servlet is used to deal with (there may be some business logic, there may be some validation, and so on, there may be some data query, submit, etc.) its valid data is derived from Key=value &key=value&key=value ..., and some other data resources encapsulated in the request object.
2) After processing the request, the response object gets the Java.io.PrintWriter output stream object out, through the out.println (); Outputs the data to the output stream in the specified format, such as in accordance with Response.setcontenttype ("text/html;charset=gb2312");
Its response message is very similar to the request message, and the difference is that the request line in the request phase is replaced by the state line, and then the response message:

3) A response message consists of four parts: status line, response header, blank line, response data:
(a). Status line:
The status line consists of three tokens: HTTP version, response code, and response description.
HTTP1.1------continue//continue to append HTTP1.1------OK//all normal HTTP1.1---301---Moved permanently//requested documents in other place will automatically connect HTTP1.1---403---Forbidden//absolutely deny you access to this resource, regardless of the authorization HTTP1.1------Bad request//client requests poor syntax HTTP1.1---404 ---not Found//The most common, is definitely the famous can't find
HTTP response code:
1XX: Informational, tells the client to respond to some other action 2xx: these represent the successful request.
3xx: Redirect, in order to complete the request, the action must be performed further 4xx: Client error 500-599: server-side error
(b). Response headers: Like request headers, they indicate the functionality of the server and identify the details of the response data.
Date:sat, Dec 2005 23:59:59 GMT--Response generation date and time ContentType: ' text/html;charset=gb2312 '
content-length:122-The number of bytes in the response, only required when the browser is using a permanent (keep-alive) HTTP connection.
(c). Blank line: The last response header is followed by a blank line, which sends a carriage return and a regression indicating that the server no longer has a header label.
(d). Response data: HTML documents and images, and so on, the HTML itself. Out.println ("&LT;HTML&GT; ..."); Write to client.

[HTML]View Plaincopyprint?
  1. <html>
  2. <head>
  3. <title>welcome to Cuishen ' s IT blog</title>
  4. </head>
  5. <body>
  6. <!--here is the concrete content that saw here
  7. I believe everyone has a clear idea of how HTTP works and how the client interacts with the server.
  8. -->
  9. </body>
  10. </html>

Iv. server-side shutdown connection, client resolution postback response message, Recovery page
1) The browser parses the status line first to see if the request is successful status Code--http response code: 404 400 200 ....
2) Resolve each response header, such as:
contenttype:text/html;charset=gb2312
content-length:122---The number of bytes in the response, only required if the browser is using a permanent (keep-alive) HTTP connection.
3) Read the response data HTML, restore the standard HTML format page or other according to the contents of the tag 4) An HTML document may contain other resources that need to be loaded, the browser will recognize it and make additional requests for those resources, and the process can be looping all the way up to the time that all the data is restored to the page in the format specified in the response header.
5) The data transfer is complete, the server side closes the connection, namely the stateless Protocol.
4. Summary
Do not be intimidated by the advanced terminology and theory, in fact, the HTTP client and server-side interaction principle is simple: that is, the browser and server-side to establish a socket stateless connection, that is, a short connection, and then through the IO stream for message information (this message is strictly follow the HTTP message interface) of the interaction, Close the connection after the last session is finished. For these low-level protocols and packets of packet unpacking interaction implementation, in fact, Java and the browser has already encapsulated, programmers just focus on the implementation of the business logic is OK, these do not have to care!!
To understand the interaction principle, we look back at the original question, in fact, this question is not difficult to answer: JSP is ultimately compiled by the Java Web server into a servlet to execute, the nature of the struts framework is the servlet + JavaBean do a lightweight package, So the final server sends the response data to the client browser by calling Out.println ("&LT;HTML&GT; ..."), and the method is written to the client by IO stream. Essentially, Formbean is translated into a byte stream and then written to the client, as long as the object's attributes are stored as a byte stream (string is also) is serialized, the object is persisted is the process of serialization. This is why actionform needs to be forced to serialize.

Reference: http://blog.csdn.net/billdai/article/details/4563878

Discussion on the client and application server-side interaction principle of Java Web Program

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.