Spring Combat Reading Notes-building the rest API with SPRINGMVC

Source: Internet
Author: User
Tags representational state transfer unsupported

Spring Combat Reading Notes-build rest API1 with SPRINGMVC. Rest Introduction

REST (Representational state Transfer): Representational status transfer, which is a Web software architecture based on HTTP, URI, MIME (HTML, JSON, etc.) protocol. Unlike SOAP Web service (RPC), which focuses on processing, behavior-oriented, it is more concerned about the data to be processed and resource-oriented.

1.1 "Spring Combat" describes rest in this way :

In order to understand what rest is, we split its initials into different constituent parts:

    • Presentation (representational): rest resources can actually be expressed in a variety of forms, including XML, HTML, JSON, and HTML---most suitable for any form of resource user.
    • State: When using rest, we focus more on the state of the resource than on the behavior of the resource.
    • Transfer (Transfer): Rest involves transferring resource data, which is transferred from one application to another in some form of representation.

In rest, resources are identified and positioned through URLs. There are behaviors in rest that are defined by the HTTP method. These HTTP methods usually match the following curd actions:

    • Create:post
    • Read:get
    • Update:put or patch
    • Delete:delete

I am the split line of Meng Meng

The 1.2 Wiki describes rest in this way :

    • A resource is specified by a URI.
    • Operations on resources include acquiring, creating, modifying, and deleting resources that correspond exactly to the get, POST, put, and Delete methods provided by the HTTP protocol.
    • Manipulate resources by manipulating their representations.
    • The expression of a resource is either XML or HTML, depending on whether the reader is a machine or a person, a client software that consumes a Web service, or a Web browser. Of course, it can be any other format.

RESTful API: A restful design-style Web API that is defined from the following three resources:

    • Intuitive short resource address: URI, for example:http://example.com/resources/
    • Transmitted resources: Web Services accept and return the Internet media type, such as: json,xml,yaml,html, etc.
    • Action on a resource: a series of request methods (such as post,get,put or delete) supported by the Web service on that resource.

Typical application of the HTTP request method in the RESTful API:

resources get put post delete
A URI for a set of resources, such as http://example.com/resources/ Lists the URI, along with the details of each resource in the resource group (the latter is optional). Replaces the current entire set of resources with a given set of resources. Create/Append a new resource in this group of resources. This operation often returns the URL of the new resource. Delete the entire group of resources.
URI of a single resource, such as http://example.com/resources/142 Get the details of the specified resource, format can choose a suitable network media type (such as: XML, JSON, etc.) replace/create the specified resource. and append it to the appropriate resource group. Take the specified resource as a resource group, and under it create/append a new element that is subordinate to the current resource. Deletes the specified element.

Implementation examples:
List all items:GET http://www.store.com/products
To render a product:GET http://www.store.com/product/12345
Present some products (filter rules):GET http://www.store.com/product/1022?limit=10(id为1022后的10件商品)
Order Purchase:
POST http://www.store.com/order <purchase-order> <item> ... </item> </purchase-order>

1.3 Implementing a Web site (I looked for a few sites to look at, there are several sites personally feel that the API is quite consistent with the RESTful API):
Xiaomi official website: Read several shopping websites, think Xiaomi official website besides login (estimate security reason), other design quite accord with restful API
Arrested: A music website, its recommended small crowd music is very good. Because its functionality is simpler, its API looks simple and looks like a restful API at a glance

I am the split line of Meng Meng
1.4 Private thought :
In fact, after looking at it, the feeling is not too understand, vague. Here are some simple words to understand:

    • Based on the RESTful API's ability to separate the front and back ends, the frontend is able to obtain the appropriate resources, whether it is a Web browser or a mobile terminal, as long as the API accesses the response.
    • RPC (remote process scheduling) sense is service-based, more value behavior, generally directly from the service layer exposed interface. While rest is based on resources, which generally exposes interfaces from the Web layer (RESTful APIs), it values the behavior of the resources (through HTTP request methods), which means that we do not see the behavior in the RESTful API, but only the operational resources can be seen.

1.5 well-designed RESTful API interface
Design principles for RESTful APIs

Rest in 2.SpringMVC

2.1 Gross Structure
The process flow in the general SPRINGMVC framework is as follows:
When the HTTP request arrives at Dispatcherservlet, Dispatcherservlet finds the controller for that URL by handlermapping, Dispatcherservlet will transfer httpservletrequest to controller processing (SPRINGMVC has made a lot of improvements here). When the controller finishes processing, it passes the model and view to Dispatcherservlet, which finds the physical view through Viewresolver, then sends the model to the view for rendering, and the final view responds to the HTTP request. Sends the data for the response.

The process of rest in the SPRINGMVC framework is as follows:
When the HTTP request arrives at Dispatcherservlet, Dispatcherservlet finds the controller for that URL by handlermapping, Dispatcherservlet will transfer httpservletrequest to controller processing (SPRINGMVC has made a lot of improvements here), SPRINGMVC will pass the message converter Conversion) @RequestBody, @RequestMapping, @PathVariable the resources to receive responses, GET, post, and other methods labeling behavior. The controller then invokes the service to process the related resource behavior, and finally returns the data via message Conversion (@ResponseBody).

2.2 supported artifacts
Springmvc There are many artifacts in the controller that support rest:

    • http method widget. In the @requestmapping () parameter, you can specify the method of the response by Method=requestmethod.get.
    • Gets the data widget. @ReqeustParam () can get the query String Parameters, Form data, and so on, @PathVariable () can get the path variable. The
    • message Converter (msg Conversion) transforms the message. Through @requestbody () you can convert the request data through a related class library (such as Jackson) to a Java object, and through @responsebody () you can convert the Java object data to a JSON object through a related class library such as Jackson. The
    • can use @restcontroller at the class level. All methods of the class use the message converter by default, which is equivalent to each method having a @responsebody () annotation.

2.3 Spring Use
Import Jackson

1 <Dependency>2     <groupId>Com.fasterxml.jackson.core</groupId>3     <Artifactid>Jackson-databind</Artifactid>4     <version>2.4.3</version>5 </Dependency>

Js

1 functionLogin () {2     varUsername = $ (' #username '). Val ();3     varPassword = $ (' #password '). Val ();4     varMessage = $ (' #message ');5     if(username.length<6 | | password.length <6){6Message.hide (). HTML (' user or password bits less than 6 bits ')). Show ();7}Else{8 $.ajax ({9URL: "/springmvc/hello",TenType: "POST", OneDataType: "Text", Atimeout:10000, -Data: {"username": username, "password":p Assword}, -Success:function(Result) { the Console.log (result); -             } -         }); -     } +}

Controller

1 @Controller2@RequestMapping (value= "/springmvc")3  Public classUsercontroller {4@RequestMapping (value= "/login", method=requestmethod.get)5      PublicString Login () {6     return"Login";7     }8 9@RequestMapping (value= "/hello")Ten @ResponseBody One      PublicUser Hello (@RequestParam (value= "username") String username, A@RequestParam (value= "username") String password) { -SYSTEM.OUT.PRINTLN (username + "\ T" +password); -User User =NewUser (5, username); the         returnuser; -     } -}

HTTP Request

1 Post/springmvc/hello http/1.12 Accept:text/plain, */*; q=0.013 accept-encoding:gzip, deflate, BR4 accept-language:zh-cn,zh;q=0.85 connection:keep-alive6 content-length:317 content-type:application/x-www-form-urlencoded; Charset=utf-88 cookie:jsessionid=1mnbs1bxxlxvblq759pgltl8q9 host:localhost:8080Ten origin:http://localhost:8080 One Referer:http://localhost:8080/springmvc/login A user-agent:mozilla/5.0 (Windows NT 10.0; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/57.0.2987.110 safari/537.36 - x-requested-with:xmlhttprequest - Form Data the View parsed -  -username=132456&password=123456

HTTP Response

1 http/1.1 OK 2 Content-type:application/json;charset=utf-8 3 date:wed, APR 15:27:27 GMT 4 Server:jetty (8.1.14.v20131031) 5 transfer-encoding:chunked 6 7 {"id": 5, "name": "132456"}
3.References

Https://zh.wikipedia.org/wiki/REST

Spring Combat Reading notes-building the rest API with SPRINGMVC

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.