Ajax and rest

Source: Internet
Author: User
Tags representational state transfer dojo toolkit

November 09, 2006

Server Web ApplicationsProgramBecause of the adoption of rich Application Models and delivery of personalized contentImmersive)The more prominent this feature is, the more the application architecture violates the representational state transfer. This violation will reduce the scalability of the application and increase the complexity of the system. Through coordination with rest, the Ajax architecture will eliminate these negative effects for integrated web applications and enjoy the outstanding features of rest.

In just 15 years, World Wide Web has grown from a research experiment to a technical pillar of modern society. The purpose of the Web was originally invented to enable people to easily publish and link information, and now it has evolved into a viable platform for software applications. However, as applications get more integration by using rich Application Models and generating personalized content, their architecture has a restful Web architecture style (representational state transfer) more and more violations. This violation will reduce the scalability of the application and increase the complexity of the system.

The emerging Ajax Web client architecture style makes the integrated web applications consistent with the rest architecture style. So that they can enjoy the excellent features of rest, while eliminating the bad features of applications that violate the rest rules. This article describes how to integrate Ajax and rest into a web application.

Please visitAjax Technical Resource CenterThis is an all-in-one center for Ajax programming model information, including many documents, tutorials, forums, blogs, wikis, and news. Any new information can be found here.

Rest: Web architecture

Although World Wide Web was established on the basis of decades of research, its effective date was December 1990, when Tim Berners-Lee completed the prototype of the main web components: unified Resource Identifier (URI), HTTP, HTML, browser, and server. The rapid adoption of Web far exceeds the expectations of pioneers. The most famous series in Roy FieldingArticle(SeeReferencesHe described his current mood:

"Despite being excited about its success, Internet developersCommunityGradually began to worry that the rapid growth of web usage and some poor network features of HTTP in the Early Days will quickly overwhelm the capacity that the Internet infrastructure can undertake, resulting in a sudden collapse ."

"An architecture should be designed with a set of features that can meet or even surpass system requirements. Ignoring these features may cause later changes to interfere with the entire architecture, as if replacing the load-bearing wall with a floor-to-ceiling window will undermine the reliability of the entire building structure ." -- Roy Fielding

Fielding and others reviewed the Web architecture and whether it could support various extensions and usage. The tangible results of this review include updating important standards such as Uri and HTTP. This review also produces some intangible but very meaningful results: a new architecture style is defined for super media applications, fielding named it rest (representational state transfer ). Fielding asserted that components deployed on the web that meet the rest design constraints can fully utilize the useful features of the web. He also warned that Web Components that violate the rest rules would not be able to take advantage of these advantages.

In the early days, most web sites and simple web applications actually followed the rest rules. However, with the increasing popularity of integrated web applications, the Web application architecture has gradually deviated from the rest rules, followed by a causal cycle, and the situation has deteriorated. It is difficult to analyze the problem of Integrated server-side Web architecture because the following belief has been established over the past decade: these problems are inherent in the Web application architecture. In fact, this is not a problem with the Web application architecture. It is caused by the architecture style of the Web application on the server side. To break this prejudice, let's review how the entire architecture has evolved to the present state, which will be very helpful. We will explain why many assumptions accepted in the past are no longer valid after Ajax applications are created commercially available.

 



Back to Top

 

A Brief History of Web Applications

Berners-Lee created the web, which was initially a means for researchers to remotely share documents and create simple links between documents to accelerate the spread of knowledge and ideas. However, the architecture features of the URI standard quickly enable more content sharing besides static files.

Websites that provide static documents

The earliest content on the Web is composed of some static HTML documents. There are many links to other static documents, as shown in 1:

Figure 1. Web site that provides static documents

Rest makes the retrieval of static documents extremely efficient and scalable, because they can be easily cached Based on the URI and the last modification date. Soon, developers surpassed the field of static documents and began to provide dynamic documents.

Early Dynamic Web Applications

Berners-Lee and others have designed URI standards to provide support for uniform and unique resource identifiers and make their representation (HTML, text, etc.) based on web clients (usually Web browsers) and the web server. Because URI separates the Resource Identifier from the underlying storage mechanism of the resource, Web developers can create programs to check the URI syntax and generate documents dynamically, combine predefined UI elements with dynamically retrieved data (usually from relational databases), as shown in figure 2. Although these documents are generated, their cache features are exactly the same as those of static files.

Figure 2. embed an HTML TemplateCodeWeb site that provides database records

A simple example of such early applications is to unify the directory of Web applications. This type of application usually works as follows:

    1. Enter a name in a web form (for example,Bill Higgins), And click Submit.
    2. The form creates a URI based on the input name and requests the URI content from the server (for exampleGet http://psu.edu/Directory/Bill+Higgins).
    3. The server checks the URI and uses the student's phone number and address to generate a Web page.
    4. The server sends the generated page back to the user's browser.

An important feature of this interaction is thatIdempotent (idempotent)That is to say, unless the underlying resources change (for example, bill modifies his phone number), the results of the same request will always be the same. This means that both the browser and the proxy server can cache the bill Higgins documentation locally. as long as the underlying resources do not change, the resources can be retrieved from the local cache, instead of retrieval from a remote server. This method can improve the user's responsiveness and increase the overall efficiency and scalability of the system. These early Dynamic Web applications can work well and send a large amount of information to the user's fingertips.

Integrated Web Applications

The goal of the next generation of Web applications is to be highly integrated to provide personalized content and rich application models. Over the past decade, Web developers have successfully created these integrated applications. A very appropriate example is the Amazon.com e-commerce site. When a user interacts with an Amazon Web application, it creates a complex customer page to recommend targeted products, display browsing history, and display the prices of products in the user's shopping cart.

 



Back to Top

 

Integrated server applications and rest

Integrated web applications are indeed very useful, but the server-side integrated web application style is fundamentally not in line with the rest architecture principles. Specifically, it violates a key rest constraint and does not take advantage of some of the most important advantages of rest. Therefore, it creates a new set of problems.

Violating the "stateless server" Constraint

The "client-stateless-server" constraint of rest prohibits you from saving the session status on the server. Designing with this constraint improves system visibility, reliability, and scalability. However, the integrated server-side web application needs to provide a large amount of personalized content for a single user, so you must choose between the two designs. The first design requires that a large amount of status information be sent in each client request. Therefore, each request completely retains the context content, and the server is stateless. The second solution is relatively simple on the surface. application developers and middleware vendors prefer this method. It simply sends a user ID, and associate a "user session" (3) for this identifier on the server side ). The second design directly violates the client-stateless-server constraints. Although it can indeed implement the user features we want (specifically, personalization), it has made great changes to this architecture.

Figure 3. Integrated server-side Web applications, including a large number of server-side session states

The httpsession API of Java Servlet is an example of such changes. Httpsession allows us to establish associations between statuses and specific users. This API seems very simple for new developers. In fact, it seems that any object can be saved to httpsession, and these objects can be retrieved without any specific search logic. However, when we start to add more objects to httpsession, we will begin to notice that our application servers are occupying more and more memory and processing resources. Soon, we decided we needed to deploy the application to the cluster environment to meet the increasing resource demands. Then we will realize that every object must implement the JavaSerializableInterface, so that session data can be transmitted between servers in the cluster environment. Then, you must determine whether the application server will continue to maintain session data during Shutdown/restart. Soon you will question whether it is a good idea to violate the client-stateless-server constraints. (In fact, many developers do not understand this constraint .)

Make distributed cache impossible

The second serious consequence of an integrated server-side web application is that it cannot actually use rest's first type of support for resource caching. By referencing Fielding, "the advantage of adding cache constraints is that some interactive operations can be partially or completely avoided, this improves efficiency, scalability, and performance that users can feel by reducing the average latency of a series of interactions. However, the cost is that if there is a big difference between the old data in the cache and the data obtained by directly sending the request to the server, the reliability of the cache will be reduced ."

We can regard an integrated web application as an active entity, it is constantly changing based on the new input content provided by the user, the new content input by others, and the new background data. Because the server must generate each page based on the interaction between multiple users and applications, we cannot generate the same document twice. Therefore, Web browsers or proxies cannot cache server resources.

There are several solutions that can be used to solve the problem that resources cannot be cached. One is to create fine-grained Resources in the cache on the server, so that the server can build a coarse-grained page through pre-combined parts, instead of using basic elements (HTML and data) build this page step by step from the beginning. But the problem persists: each request will lead to a large number of server processing, which will damage the scalability of the system and may have a negative impact on the user's responsiveness.

Another result that cannot provide cache resources is that Web applications with a high degree of dynamics must explicitly prohibit search engines from making requests with other types of robots, because the cost of processing such requests is very high, and in applications that comply with the rest rules, you only need to provide a single resource to that type of "robot" at a time ", then, send a simple "not-modified" message for their subsequent access.

processing without Ajax clients

as more and more users access web applications, the resources required by the system will gradually increase. The server can handle all this, but it will need a server or cluster server with a larger capacity (the server status is not suitable in the Cluster Environment ). However, if the processing is distributed to the client, each time a new user is added, you have a new computer that supports some new loads. If the session state is distributed to the client, a stateless server is available-a satisfactory feature in scalable Web applications. This seems to be a wise practice. Why not design all integrated web applications in this way? Before Ajax appears, the answer is very simple: each time a user accesses a new web page, the application state is destroyed.

each time you access a Web page, you must download one or more files containing the content (the data contained in the structured information, such as tables and lists) and styles that affect the appearance of the content (such as red text ). In a Web browser, the information is viewed as an abstract set of document objects. The following list is used as an example:

  • Ford
  • BMW
  • Toyota

the browser considers this HTML as an unordered list object, which contains three list elements. Each list element contains text. The entire document can be viewed as a complex Related Object Tree. When we browse from one page to another, the browser will destroy the Object Tree of the current page and create a new object tree for the next page.

But why is it necessary to concentrate so much resource consumption on an overloaded server? Theoretically, when can we distribute processing and memory requirements to the client? The simple answer is that given the constraints of traditional Web browsers, this is not feasible (seeClient processing without Ajax). However, the Ajax architecture allows developers to distribute processing and status requirements to clients. Continue to read and learn why Ajax-style integrated applications can continue to follow rest rules and take full advantage of them.

Ajax and rest

As we have seen before, traditional server-side Web applications combine data identifiers with dynamic data elements on servers, return the complete HTML document to the browser. Ajax applications differ in their main UI and the main logic in the browser. browser-based application code can obtain new server data when necessary, and weave the data into the current page (seeReferencesJesse James Garret's Ajax-related first article ). The presentation and Data Binding locations may look like implementation details, but this difference will lead to completely different architectural styles.

Advantages of stateful web clients

People usually describe Ajax applications as web pages that do not need to be completely refreshed every time they click. Although this description is very accurate, the root motivation is that refreshing the entire page will make users impatient and fail to get a pleasant and integrated user experience. From the perspective of architecture, it is even very dangerous to refresh the whole page. This design makes it impossible for you to choose to store the application status on the client, this may cause application programs to make full use of the design decisions of the most powerful Web architecture design point.

Ajax allows us to interact with the server without a full refresh. This fact makes a stateful client available again. This has a profound impact on the possibility of dynamic integrated web application architecture: As application resources and data resources are bound to the client, therefore, these applications can enjoy the best of both worlds-dynamic and personalized user experience in integrated web applications, as well as a simple and scalable architecture in applications that comply with rest standards.

Cache Ajax Engine

Imagine implementing Amazon.com as an Ajax application-a web page can dynamically retrieve all data from the server. (For commercial reasons, Amazon may not want to do this, but it is a topic discussed in other articles .) Because many UI and application logic can be run on the client rather than on the server, according to Garret, Amazon's Ajax "engine" needs to be downloaded when loading the page initially ". This engine contains a large number of application logic (implemented using JavaScript code), and a UI framework that will be populated with data asynchronously obtained from the server (see figure 4 ):

Figure 4. Integrated Ajax application

An interesting feature of the Ajax engine is that, although it contains many application logic and representation framework elements, it can not contain any business data or personalized content after proper design. The application and representation are frozen at deployment. In a typical web environment, application resources may change once every six months. This means that the Ajax engine responsible for isolating application resources and data resources is highly cacheable.

Dojo toolkit is a good example (seeReferences). Dojo provides a build-time tool to create a compressed Javascript file that contains all application logic, representations, and styles. Since it is only a file after all, the Web browser can cache it, which means that when we access the Web application that enables dojo for the second time, it is very likely that Ajax will be loaded from the browser cache rather than from the server. We can compare this situation with highly integrated server-side Web applications. Each request of the latter will cause a large number of server processes, because browsers and network intermediaries cannot cache constantly changing resources.

Since the Ajax application engine is just a file, it is alsoYou can use the Proxy Cache. In a large enterprise intranet, as long as an employee has downloaded a specific version of the application's Ajax engine, anyone else can obtain a cached copy from the Intranet gateway.

Therefore, for application resources, the well-defined Ajax application engine complies with the rest rules, which has significant scalability advantages over server-side web applications.

Cache Ajax data

A user browses an Ajax web site and loads the Ajax application engine, preferably from the browser cache. Otherwise, the user loads the data from the local proxy server. What is the situation for business data? Because the logic and status of the application reside and run on the browser, the interaction between the application and the server is very different from that of traditional Web applications. You do not need to obtain a hybrid content page. You only need to obtain business data.

Now let's go back to the example of Amazon.com. Suppose we click a link to view a book about the design pattern. In the current application of Amazon.com, clicking a link will send a lot of information that identifies the requested resource. It also sends a lot of session status information, which allows the server to create a new page, including the previous status (such as recently viewed content), personalized information (such as the books you purchased in March 1999) and the actual business resources. Applications are dynamic and highly personalized-but they cannot be cached or scaled (as demonstrated by Amazon, these architecture problems can be overcome by investing a lot of money to build the infrastructure ). Now let's take a look at the situation of this operation in the (hypothetical) Ajax version of the application. "Recently viewed content" does not need to be processed. When we click a link, the existing information on the page will not disappear. Two requests may be related to the design patterns book:

    • /Books/0201633612(Where0201633612ISBN number of the Design Model Book)
    • /Purchasehistory/0201633612/bhiggins@us.ibm.com

The First hypothetical request will return information about the book (author, title, profile, etc.), which does not contain user-specific data. User-specific data means that when more users request the same resource, the Cache version may be retrieved from the intermediate node on the Internet, rather than from the original server. This feature reduces server and overall network load. On the other hand, the second request contains user-specific information (History of Bill Higgins's purchase book ). Because the data includes some personalized information, only one user needs to obtain and cache the data from this URI. Although such personalized data is not scalable, it is important that the information is obtained directly from the URL, so it has such positive characteristics:They do not affect the caching of other cacheable applications and data resources..

Ajax and robustness

Another advantage of the Ajax architecture is that it can easily handle server faults. As we have discussed earlier, server-side Web applications with integrated user experience usually save a large number of user session statuses on the server. If the server fails, the session state will be lost, and the user will experience a very strange browser behavior ("Why did I go back to the home page? Where did everything in my shopping cart go ?"). In Ajax applications using stateful clients and stateless services, server crashes/restarts are completely transparent to users, because server crashes do not affect the session status, these are all stored in the user's browser. The stateless service behavior is idempotent and can be determined separately by the content requested by the user.

 



Back to Top

 

Commitment and Problems

For Web applications called integrated web applications, well-designed ajax/rest applications far surpass traditional server-side Web applications in terms of user experience, responsiveness, and scalability. However, an architecture-style runtime feature is not the only factor that determines success for software projects and Web applications. There are some very difficult non-runtime issues when creating ajax/rest applications, including large-scale Javascript development, cultural issues, and packaging issues. We will discuss cultural issues in another article, which will be left to my Ajax colleagues.

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.