In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "principle Analysis of TESTful Architecture in java". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "the principle Analysis of TESTful Architecture in java".
Catalogue
1. What is REST?
two。 Understand RESTful
2. 1 Resources and URI
2. 2 uniform resource interface
GET
POST
PUT
DELETE
2. 3 description of resources
Put the version number in the URI
Use the URI suffix to distinguish the presentation format
How to deal with unsupported expression formats
2. 4 links to resources
2. 5 state transfer
2. 5.1 Application status and resource status
2. 5.2 transfer of application status
1. What is REST?
The full name of REST is Representational State Transfer, which means to express sexual state transfer in Chinese. It first appeared in the doctoral thesis of Roy Fielding in 2000, and Roy Fielding is one of the main writers of the HTTP specification. He said in his paper: "the purpose of my article is to understand and evaluate the architecture design of web-based applications on the premise of architecture principles, and to get an architecture with strong function, good performance and suitable for communication. REST refers to a set of architectural constraints and principles." If an architecture conforms to the constraints and principles of REST, we call it RESTful architecture.
REST itself does not create new technologies, components, or services, but the idea behind RESTful is to use the existing features and capabilities of Web to make better use of some of the guidelines and constraints of existing Web standards. Although REST itself is deeply influenced by Web technology, theoretically, the REST architecture style is not bound to HTTP, but currently HTTP is the only instance related to REST. So the REST we describe here is also a REST implemented through HTTP.
two。 Understand RESTful
To understand the RESTful architecture, you need to understand exactly what the phrase Representational State Transfer means and what each word has. Based on the principle of REST, we discuss resources, enumerate some key concepts and explain them from the point of view of resource definition, acquisition, representation, relevance, state change and so on.
Resources and URI
Unified resource interface
Representation of resources
Links to resources
Transfer of state
2. 1 Resources and URI
The full name of REST is declarative state transfer. What exactly does it mean? It actually refers to resources. Anything, as long as it is necessary to be quoted, is a resource. A resource can be an entity (such as a mobile phone number) or just an abstract concept (such as value). Here are some examples of resources:
The mobile phone number of a user
The personal information of a user
GPRS package ordered by the most users
Dependency between two products
A discount package that can be handled by a user
The potential value of a mobile phone number
To make a resource identifiable, you need a unique identity, which in Web is URI (Uniform Resource Identifier). The URI can be seen as either the address or the name of the resource. If some information is not expressed in URI, then it is not a resource, it is only some information of the resource. The design of URI should follow the principle of addressability, be self-descriptive, and give people intuitive relevance in form. Here, taking the github website as an example, gives some pretty good URI:
Https://github.com/git
Https://github.com/git/git
Https://github.com/git/git/blob/master/block-sha1/sha1.h
Https://github.com/git/git/commit/e3af72cdafab5993d18fae056f87e1d675913d08
Https://github.com/git/git/pulls
Https://github.com/git/git/pulls?state=closed
Https://github.com/git/git/compare/master... Next
Let's take a look at some tips on URI design:
Use _ or-to make URI more readable
URI on Web used to be cold numbers or meaningless strings, but now more and more websites use _ or-to separate words to make URI look more human. For example, the news address above the well-known open source Chinese community in China adopts this style, such as
Http://www.oschina.net/news/38119/oschina-translate-reward-plan .
Use / to represent the hierarchical relationship of resources
For example, the above / git/git/commit/e3af72cdafab5993d18fae056f87e1d675913d08 represents a multi-level resource, which refers to a submission record of a git project of a git user, and for example, / orders/2012/10 can be used to represent the order record of October 2012.
Use? Used to filter resources
A lot of people just put? Simply as the passing of parameters, it is easy to make URI too complex and difficult to understand. May I? Used to filter resources, for example, / git/git/pulls is used to represent all push requests of git projects, and / pulls?state=closed is used to represent push requests that have been closed in git projects. This kind of URL usually corresponds to the query results or algorithm results of certain conditions.
Can be used to represent the relationship between sibling resources
Sometimes when we need to represent the relationship of sibling resources, we can use, or; to split. For example, one day github can compare the difference between two random commit records of a file or use / git/git / block-sha1/sha1.h/compare/e3af72cdafab5993d18fae056f87e1d675913d08;bd63e61bdf38e872d5215c07b264dcc16e4febca
As URI.
But now github uses... To do this, for example, / git/git/compare/master... Next .
2. 2 uniform resource interface
The RESTful architecture should follow the principle of unified interface, which contains a set of limited predefined operations, no matter what kind of resources are accessed by using the same interface. The interface should use standard HTTP methods such as GET,PUT and POST and follow the semantics of these methods.
If resources are exposed according to the semantics of the HTTP method, then the interface will have security and idempotent features, such as GET and HEAD requests are secure, no matter how many requests, will not change the server state. While GET, HEAD, PUT, and DELETE requests are all idempotent, no matter how many times you operate on the resource, the result is always the same, and the subsequent requests will not have more impact than the first one.
Typical uses of GET,DELETE,PUT and POST are listed below:
GET
Safe and idempotent
Get representation
Get representation on change (cache)
200 (OK)-indicates that it has been issued in the response
204 (no content)-indicates that resources are available
301 (Moved Permanently)-the URI of the resource has been updated
303 (See Other)-other (e.g., load balancing)
304 (not modified)-Resource has not changed (cache)
400 (bad request)-refers to a bad request (e.g., parameter error)
404 (not found)-Resource does not exist
406 (not acceptable)-the server does not support the required representation
500 (internal server error)-generic error response
503 (Service Unavailable)-the server cannot currently process the request
POST
Unsafe and non-idempotent
Create a resource using a server-managed (automatically generated) instance number
Create child resources
Partially update resources
If it has not been modified, only update the resource (optimistic lock)
200 (OK)-if existing resources have been changed
201 (created)-if a new resource is created
202 (accepted)-processing request accepted but not yet completed (asynchronous processing)
301 (Moved Permanently)-the URI of the resource is updated
303 (See Other)-other (e.g., load balancing)
400 (bad request)-refers to bad request
404 (not found)-Resource does not exist
406 (not acceptable)-the server does not support the required representation
409 (conflict)-generic conflict
412 (Precondition Failed)-precondition failure (such as a conflict while performing a condition update)
415 (unsupported media type)-received indication is not supported
500 (internal server error)-generic error response
503 (Service Unavailable)-the service cannot currently process the request
PUT
Unsafe but idempotent
Create a resource with a client-managed instance number
Update resources by replacement
If it is not modified, update the resource (optimistic lock)
200 (OK)-if an existing resource is changed
201 (created)-if a new resource is created
301 (Moved Permanently)-the URI of the resource has changed
303 (See Other)-other (e.g., load balancing)
400 (bad request)-refers to bad request
404 (not found)-Resource does not exist
406 (not acceptable)-the server does not support the required representation
409 (conflict)-generic conflict
412 (Precondition Failed)-precondition failure (such as a conflict while performing a condition update)
415 (unsupported media type)-received indication is not supported
500 (internal server error)-generic error response
503 (Service Unavailable)-the service cannot currently process the request
DELETE
Unsafe but idempotent
Delete a resource
200 (OK)-the resource has been deleted
301 (Moved Permanently)-the URI of the resource has changed
303 (See Other)-other, such as load balancing
400 (bad request)-refers to bad request
404 (not found)-Resource does not exist
409 (conflict)-generic conflict
500 (internal server error)-generic error response
503 (Service Unavailable)-the server cannot currently process the request
Let's look at some common problems in practice:
What is the difference between POST and PUT when used to create resources?
The difference between POST and PUT in creating a resource is whether the name (URI) of the created resource is determined by the client. For example, if I add a java category to my blog post, and the generated path is the category name / categories/java, then I can use the PUT method. However, many people directly correspond POST, GET, PUT, and DELETE to CRUD, for example, in a typical RESTful application implemented by rails. I think this is because rails uses server-generated ID as URI by default, and many people practice REST through rails, so it is easy to cause this misunderstanding.
These HTTP methods are not necessarily supported by the client, are they?
This is true, especially for some older browser-based clients, which can only support both GET and POST. In practice, both the client and the server may need to make some compromises. For example, the rails framework supports passing the real request method by hiding the parameter _ method=DELETE, while client-side MVC frameworks like Backbone allow you to pass the _ method transfer and set the X-HTTP-Method-Override header to circumvent this problem.
Does a unified interface mean that methods with special semantics cannot be extended?
A unified interface does not prevent you from extending the method, as long as the method has a specific and recognizable semantics for the operation of the resource, and can maintain the unity of the entire interface. For example, WebDAV extends the HTTP method by adding LOCK, UPLOCK and other methods. Github's API supports using the PATCH method to update issue, for example:
PATCH / repos/:owner/:repo/issues/:number
It should be noted, however, that PATCH is not a standard HTTP approach, and the server needs to consider whether the client can support it.
What is the guiding significance of the unified resource interface for URI?
The uniform resource interface requires the use of standard HTTP methods to manipulate resources, so URI should only represent the name of the resource, not the operation of the resource. Generally speaking, URI should not be described by actions. For example, here are some URI that do not meet the unified interface requirements:
GET / getUser/1
POST / createUser
PUT / updateUser/1
DELETE / deleteUser/1
If GET requests to increase the counter, is this a security violation?
Security does not mean that requests do not have side effects. For example, like many API development platforms, request traffic is limited. Github, for example, limits requests without authentication to 60 requests per hour. However, the client does not issue these GET or HEAD requests in pursuit of side effects, and the server makes its own decisions to produce side effects. In addition, the server should not allow too many side effects at design time, because the client believes that these requests will not cause side effects.
Directly ignore cache accessibility?
Even if you use the verbs as they are intended, you can easily disable the caching mechanism. The easiest thing to do is to add such a header to your HTTP response: Cache-control: no-cache. However, you also lose support for efficient caching and revalidation (using mechanisms such as Etag). For the client, when implementing a program client for a REST-style service, you should also make full use of the existing caching mechanism to avoid retrieving the representation every time.
Is the processing of the response code necessary?
The response code of HTTP can be used to cope with different situations, and the correct use of these status codes means that the client and server can communicate at a level with rich semantics. For example, the 201 ("Created") response code indicates that a new resource has been created with its URI in the Location response header. If you don't take advantage of the rich application semantics of HTTP status codes, you will miss the opportunity to improve reusability, interoperability, and loose coupling. If these so-called RESTful applications can only give error messages through the response entity, then SOAP is like this, and it can be satisfied.
2. 3 description of resources
As mentioned above, the client can get resources through the HTTP method, right? No, to be exact, what the client gets is the representation of the resource. The specific presentation of resources in the outside world, there can be a variety of expressions (or become performance, representation), the transmission between the client and the server is also the expression of the resources, rather than the resources themselves. For example, text resources can be in html, xml, json and other formats, and pictures can be displayed using PNG or JPG. The representation of resources includes data and metadata that describes the data. For example, the HTTP header "Content-Type" is such a metadata attribute.
So how does the client know which expression the server provides?
The answer is that it can be negotiated through HTTP content, the client can request a representation of a specific format through the Accept header, and the server can tell the client the representation of the resource through Content-Type.
Take github as an example, the json format of requesting an organization's resources:
If github can also support the presentation format in xml format, the result is this:
Let's take a look at some common designs in practice:
Put the version number in the URI
Some API have version numbers in the URI, for example:
Http://api.example.com/1.0/foo
Http://api.example.com/1.2/foo
Http://api.example.com/2.0/foo
If we understand the version number as a different representation of the resource, we should just use a URL and distinguish it by the Accept header, or take github as an example, the full format of its Accept is
Application/vnd.github [.version] .param [+ json]
For the v3 version, it is Accept: application/vnd.github.v3. For the above example, you can also use the following header:
Accept: vnd.example-com.foo+json; version=1.0
Accept: vnd.example-com.foo+json; version=1.2
Accept: vnd.example-com.foo+json; version=2.0
Use the URI suffix to distinguish the presentation format
For example, the rails framework supports the use of / users.xml or / users.json to distinguish between different formats. This approach is undoubtedly more intuitive for the client, but it confuses the name of the resource with the representation of the resource. I personally think that content negotiation should be given priority to distinguish between presentation formats.
How to deal with unsupported expression formats
What should I do when the server does not support the requested presentation format? If the server does not support it, it should return a HTTP 406 response that refuses to process the request. Taking github as an example, the following shows the result of requesting a XML representation resource:
2. 4 links to resources
We know that REST uses standard HTTP methods to manipulate resources, but it is simply too simple to understand Web database architecture with CURD. This anti-pattern ignores a core concept: hypermedia is the Application State engine (hypermedia as the engine of application state). What is hypermedia? When you browse a Web page, you jump from one link to another and from another to another, using the concept of hypermedia: linking resources one by one.
To achieve this, you need to include a link in the presentation format to guide the client. In RESTful Web Services, the author refers to this feature of linking as connectivity. Let's take a look at some specific examples.
The following shows github's request for a list of projects under an organization, and you can see the record of adding a link header to the response header telling the client how to access the next page and the last page. In the response body, url is used to link the project owner and the project address.
Another example is the following example, which guides the client how to pay through a link after creating an order.
The above example shows how to use hypermedia to enhance resource connectivity. When designing RESTful architectures, many people spend a lot of time looking for beautiful URI, ignoring hypermedia. Therefore, you should spend more time providing links to the representation of resources, rather than focusing on "CRUD of resources."
2. 5 state transfer
With the above groundwork, it is easy to understand when discussing the state transitions in REST. However, let's first discuss the principle of stateless communication in the REST principle. At first glance, it seems to be self-contradictory. Since there is no state, how can there be a state transfer?
In fact, the principle of stateless communication here does not mean that the client application cannot be stateful, but that the server should not save the client state.
2. 5.1 Application status and resource status
In fact, the state should distinguish between the application state and the resource state, the client is responsible for maintaining the application state, and the server maintains the resource state. The interaction between the client and the server must be stateless and contain all the information needed to process the request in each request. The server does not need to keep the application status between requests, and the server will pay attention to the application status only when the actual request is received. This stateless communication principle enables servers and mediations to understand independent requests and responses. In multiple requests, the same client no longer needs to rely on the same server to facilitate the implementation of highly scalable and highly available servers.
But sometimes we make designs that violate the principle of stateless communication, such as using Cookie to track the session state of a server, such as JSESSIONID in J2EE. This means that the Cookie sent by the browser with each request is used to build session state. Of course, if Cookie holds information that can be verified by the server without relying on session state (such as authentication tokens), such a Cookie is also in line with REST principles.
2. 5.2 transfer of application status
It is easy to understand that the "session" state is not saved on the server as a resource state, but is tracked by the client as an application state. The application state of the client changes under the guidance of the hypermedia provided by the server. The server uses hypermedia to tell the client what subsequent states can be entered in the current state. These links like "next page" play the role of this advancing state-- guiding you how to move from the current state to the next possible state.
At this point, I believe you have a deeper understanding of "the principle analysis of TESTful architecture in java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.