Spring Boot has Tomcat built-in, which can easily provide Web Api externally. Sometimes it comes in handy, for example, when I write a background program to do some time-consuming tasks. And this functionality, it’s going to be open for the WEB front end to call, to be triggered by the WEB front end.
2019.08.04 This has nothing to do with whether Tomcat is built in
Spring Boot is handy. But if it is C# to do, the background is the background, but also write another WEB program to provide interface, background and WEB interface how to interact? Since these are two different processes, it is expected that message-oriented middleware will be used. Or in the background we’re going to support RPC, remote calls.
Back to the point. How to provide a WEB API in the Spring Boot project?
The code:
@RestController
@RequestMapping(value="/api")
public class ApiController {
// The submitted argument is JSON
@RequestMapping(value = "/authors/json/{id}", method = RequestMethod.POST)
public String test(@PathVariable int id, @RequestParam("t") int type,@RequestBody Author auth){
return String.format("id:%1$d,type:%2$d,name:%3$s; params type:json",id,type,auth.getName());
}
// The submitted arguments are key-value pairs
@RequestMapping(value = "/authors/kv/{id}", method = RequestMethod.POST)
public String test2(@PathVariable int id, @RequestParam("t") int type,Author auth){
return String.format("id:%1$d,type:%2$d,name:%3$s; params type:key-value",id,type,auth.getName()); }}Copy the code
Although this code is short, it contains a lot of information.
1, this is a POST API, GET is relatively simple, needless to say.
Parameters are passed in 3 ways: 1) path, corresponding to {id}
@PathVariable int id
Copy the code
2) QueryString, corresponding? t=
@RequestParam("t") int type
Copy the code
3) Submit, corresponding to Author Auth
@RequestBody Author auth
Copy the code
The @requestBody annotation indicates that the submission parameter is json and the corresponding contentType is Application/JSON
If not, it is the default key-value pair, and the corresponding contentType is Application/X-www-form-urlencoded
Front-end corresponding access code:
// Submit key-value pairs
var url1 = "http://localhost:8085/api/authors/kv/1? t=2";
var data1 = "name=chenqu&desc=foolish";
var ctype1 = "application/x-www-form-urlencoded; charset=utf-8";
/ / submit json
var url2 = "http://localhost:8085/api/authors/json/1? t=2";
var data2 = JSON.stringify({
"name":"chenqu"."desc":"foolish"
});
var ctype2 = "application/json; charset=utf-8";
$.ajax({
url: url2,
data: data2,
contentType: ctype2,
//dataType: "json",
type: "POST".success: function (data) {
alert(data);
},
error: function (rq, status, thrown) {
alert(rq.responseText + "," + status + ":"+ thrown); }});Copy the code