SpringBoot build RESTful service to complete Get and Post, springbootrestful
The most common request Method provided by a basic RESTfule service is Get and Post.
In Get, common requests include parameters or path parameters. Response Json.
In Post, form data or json data is often submitted as parameters to respond to Json.
1. Get request, url passing parameter, return json.
The response object after preparing a request.
package com.example.demo;public class Echo { private final long id; private final String content; public Echo(long id, String content) { this.id = id; this.content = content; } public long getId() { return this.id; } public String getContent() { return this.content; }}
Prepare an EchoController used to receive the request (the name can be written according to the actual situation) and add the @ RestController annotation to it, indicating that this is a response processing class for processing RESTful requests.
Add @ RequestMapping to provide a root url for this Controller. Of course, you can leave it empty. Write this url to better classify the same processing url into one category, the url corresponding to other Processing Methods of the Controller does not need to be repeatedly written.
package com.example.demo;import java.util.concurrent.atomic.AtomicLong;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.ModelAttribute;@RestController@RequestMapping("/echo")public class EchoController { private static final String echoTemplate1 = "received %s!"; private static final String echoTemplate2 = "%s speak to %s \'%s\'"; private final AtomicLong counter = new AtomicLong(); @RequestMapping(value="/getter/pattern1", method=RequestMethod.GET) public Echo getterPattern1(String content) { return new Echo(counter.incrementAndGet(), String.format(echoTemplate1, content)); } @RequestMapping(value="/getter/pattern2", method=RequestMethod.GET) public Echo getterPattern2(@RequestParam(value="content", required=false) String alias) { return new Echo(counter.incrementAndGet(), String.format(echoTemplate1, alias)); }}
The @ RequestMapping annotation is added to getterPattern1 to map the specified url to the processing method. The request corresponding to this url is processed by this method. The method can be omitted, if this parameter is omitted, the parameter corresponding to all Http Metho methods is mapped to the content parameter in the url by default.
The difference between getterPattern2 and gettern2 is that the @ RequestParam annotation is used to map url parameters and method parameters, @ RequesteParam the value of the value is the actual parameter in the url. required indicates whether the parameter is required. If it is true but the parameter is not included in the url, an exception is reported, to prevent exceptions, you can add the default value of the defaultValue specified parameter. We will find that the method parameter here is alias, which of course can be different from the url parameter name, as long as the RequestParam annotation maps their relationship, there is no problem.
After running, you can access the corresponding url in the browser to view the results. Here I use curl for access.
curl http://localhost:8080/echo/getter/pattern1?content=hellocurl http://localhost:8080/echo/getter/pattern2?content=hello
The access results of the above two URLs are consistent except that the IDs are auto-incrementing:
{"id":6,"content":"received hello!"}
2. Get request, pass url path parameters, and return json.
Add a response method to EchoController.
@RequestMapping(value="/getter/pattern3/{content}", method=RequestMethod.GET) public Echo getterPattern3(@PathVariable String content) { return new Echo(counter.incrementAndGet(), String.format(echoTemplate1, content)); }
We can see that there is "{content}" at the end of the url definition of @ RequestMapping, indicating that this is a path parameter. The @ PathVariable annotation is added to the content parameter of getterPattern3, the method parameters and path parameters are mapped.
Access url after running.
curl http://localhost:8080/echo/getter/pattern3/123456
Result:
{"id":8,"content":"received 123456!"}
3. Post request. The parameter submits Json data through the Http body.
First define an object corresponding to the submitted Json. Here it is defined as Message.
package com.example.demo;public class Message { private String from; private String to; private String content; public Message() {} public String getFrom() { return this.from; } public String getTo() { return this.to; } public String getContent() { return this.content; } public void setFrom(String value) { this.from = value; } public void setTo(String value) { this.to = value; } public void setContent(String value) { this.content = value; }}
Add the response method in EchoController and complete the ing.
@RequestMapping(value="/setter/message1", method=RequestMethod.POST) public Echo setterMessage1(@RequestBody Message message) { return new Echo(counter.incrementAndGet(), String.format(echoTemplate2, message.getFrom(), message.getTo(), message.getContent())); }
In the setterMessage1 method, @ RequestBody is used to map the Http Body of the request to the messge parameter.
After running, use curl to submit json data to the server. The submitted request header must contain "Content-Type: application/json", indicating that the request body is in Json format.
curl -i -H "Content-Type:application/json" -d "{\"from\":\"Tom\",\"to\":\"Sandy\",\"content\":\"hello buddy\"}" http://localhost:8080/echo/setter/message1
Result:
{"id":9,"content":"Tom speak to Sandy 'hello buddy'"}
4. Post request. The parameter submits form data through the Http body.
Add the response method in EchoController and complete the ing.
@RequestMapping(value="/setter/message2", method=RequestMethod.POST) public Echo setterMessage2(@ModelAttribute Message message) { return new Echo(counter.incrementAndGet(), String.format(echoTemplate2, message.getFrom(), message.getTo(), message.getContent())); }
In the parameters of the setterMessage2 method, @ ModelAttribute is used to map form data and messge parameters in the Http Body of the request.
After running, use curl to submit form data to the server. The submitted request header must contain "Content-Type: application/x-www-form-urlencoded", indicating that the request body is form data, the format is "key1 = value1 & key2 = value2 & key3 = value3 ".
curl -i -H "Content-Type:application/x-www-form-urlencoded" -d "from=sandy&to=aissen&content=go to" http://localhost:8080/echo/setter/message2
Result:
{"id":11,"content":"sandy speak to aissen 'go to'"}
End