Objective:
SPRINGMVC Support for annotations is very flexible and elegant, but also web programming is a lot less than the previous configuration items. On the other hand, the advent of mobile internet has made REST API Popular and even mainstream. So let's take a look at the level of support that SPRINGMVC has for rest APIs, and the work evaluations that need to be done.
Sample Design and Preparation:
SPRINGMVC The article Directory of the Learning Notes series:
idea creating a SPRINGMVC project
The REST API's design principles follow the previous blog post to implement
• Mobile Internet combat--web Restful API design and infrastructure
Preliminary design a query system, through the UserID, returns the user details.
Request URL:
HTTP://{HOST}:{PORT}/REST/DEMO/QUERY_USER_BY_ID?USER_ID={USER_ID}
Response Result:
{success:true, errcode:0, errmsg: "OK", value:{username: "Lilei", UserId: "1001", Age:18}}
In the sample, the request parameters are flattened (HTTP request params), and the results are organized in JSON.
Programming:
Create the SPRINGMVC project by clicking on "Idea Creation Springmvc project" in the previous blog post.
First, in mvc-dispatcher-servlet.xml , add the following items
<context:annotation-config> <mvc:annotation-driven/>
Note: Support all kinds of annotation classes, such as Responsebody, Requestbody, json/xml conversion.
Add entity classes TResult and UserInfo classes.
The TResult class is designed as follows:
public class Tresult<t> {Private Boolean success = FALSE; private int errcode = 0; Private String errmsg = "OK"; Private T value = null;}
Note: The getter and setter for each attribute member are omitted here, and need to be filled in.
The UserInfo class is defined as follows:
public class UserInfo {private String userId; Private String username; private int age;}
Note: The getter and setter for each attribute member are omitted here, and need to be filled in.
Write a custom controller class Restcontroller.
@Controller @requestmapping (value = "/rest/demo") public class Restcontroller {@RequestMapping (value= "/query_user_by_ ID ", method=requestmethod.get) public @ResponseBody tresult<userinfo> Queryuserbyid (@RequestParam (value=" user _id ") String userId) {tresult<userinfo> result = new tresult<userinfo> (); UserInfo UserInfo = new UserInfo (); Userinfo.setuserid (USERID); Userinfo.setusername ("Li Lei"); Userinfo.setage (18); Result.setvalue (UserInfo); Result.setsuccess (TRUE); return result; }}
Defines the method of Queryuesrbyid, returns the entity Tresult<userinfo>, specifies the annotation @responsebody, SPRINGMVC helps to convert it to JSON format by default.
Tests and Iterations:
In the browser, enter http://127.0.0.1:8080/rest/demo/query_user_by_id?user_id=1001, The results are as follows:
appears HTTP status 406 (not acceptable) error."
After searching the internet for a round, after trying various panacea, most of them are not brilliant. The reason for this is that SPRINGMVC version inconsistent .
because my Springmvc is 4.1.1 , which is caused by the "Spring WEBMVC 4.1 return JSON 406 (not acceptable) question " add Fasterxml's Jackson bag to resolve .
in Pom.xml, add the following dependencies:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactid>jackson-core</ Artifactid> <version>2.5.4</version></dependency><dependency> <groupId> Com.fasterxml.jackson.core</groupid> <artifactId>jackson-annotations</artifactId> <version >2.5.4</version></dependency><dependency> <groupid>com.fasterxml.jackson.core</ Groupid> <artifactId>jackson-databind</artifactId> <version>2.5.1</version></ Dependency>
Re-deploy, test again, this time it's normal.
The case was formally passed and thankfully.
Summary of issues:
Web development, the most headache is the Chinese garbled problem , fortunately this time did not touch. But to be in danger, to prevent. Here is also summarized below.
If the returned JSON string is garbled in Chinese, you can add the item produces = "Application/json;charset=utf-8"in the @requestmapping , which forms the following form:
@RequestMapping (value= "/query_user_by_id", method=requestmethod.get, produces = "application/json;charset=utf-8")
Of course, the character encoding itself is not UTF-8 caused, such as the editor's text encoding for GBK, you press UTF-8 return, it is possible garbled.
This can be modified by the right-hand corner encoding type of artifact idea.
For Java entity classes to be converted to JSON format, the Java Pojo class needs to be complete and the Getter/setter method of the class is needed . Avoid the inexplicable situation.
Summarize:
SPRINGMVC Writing the rest API is really handy, especially with the extensive use of annotation classes, which makes the configuration streamlined and coding flexible. If there is a chance, try testing the SPRINGMVC overall QPS to see how much of it serves as the access layer, and how it is optimized.
Written at the end:
If you think this article is helpful to you, please give it a little reward. In fact, I would like to try to see if blogging can bring me a little bit of revenue. No matter how much, is a kind of sincere affirmation to the landlord.
SPRINGMVC Learning Notes---Support rest API for mobile side