Spring boot RESTful接口
RESTful API是目前比较常见的前后端沟通接口,以下描述在spring boot中如何使用RESTful API的一些基本操作;
@RequestMapping(value = "/deviceControl")
public String deviceControl(@RequestBody Message message) throws JSONException, IOException, InterruptedException{
ObjectMapper mapper = new ObjectMapper();
String string = mapper.writeValueAsString(message);
JSONObject jsonObject = new JSONObject(string);
return server.Response(server.deviceControl(jsonObject)).toString();
}
如上图所示,是Limenamics_server的一个deviceControl API;
当网页或APP使用POST方法访问 “服务器ip:8080/deviceControl” 时会执行上述函数中的代码,且在参数中要求POST方法传送一份符合协议要求的json格式;
接下来对本段代码组成进行分析:
@RequestMapping(value = "/deviceControl")
- 表示访问路径为 “服务器ip:8080/deviceControl” ;
- 括号内还可加如 “method = RequestMethod.Post” 指明访问方法必须为POST
- RequestMapping 可改为 GetMapping 或 PostMapping 指明访问方法
public String deviceControl(@RequestBody Message message)
- RequestBody注解表示传入参数为一份json,而该json可转化为Message类,其中要求Message类的结构与json结构一致
ObjectMapper mapper = new ObjectMapper();
String string = mapper.writeValueAsString(message);
JSONObject jsonObject = new JSONObject(string);
return server.Response(server.deviceControl(jsonObject)).toString();
- 返回一份字符串,该字符串是一个json对象.toString();
- 返回给调用本API的客户端,网页或手机APP,其会收到一份json
注释:
- RESTful API 的 URL传参部分本文档不详细描述,想学习可自行百度
- 在接口类中public class上方必须加上@RestController的注解