Restful 是一种前后台请求的一种方式、风格
具体定义自行百度
POST:创建资源
PUT: 修改资源
GET:获取资源
DELETE:删除资源
以下是测试接口
请注意每个方法上的请求注解
@RestController
@RequestMapping("/api/restful")
public class TestRestfulController {
@PostMapping(produces = "application/json")
public AjaxResult post(@RequestBody User user) {
System.out.println(user.getPassword());
System.out.println(user.getUsername());
return new AjaxResult(200, "post 创建成功");
}
@GetMapping(value = "/{id}",produces = "application/json")
public AjaxResult get(@PathVariable("id")Integer id) {
System.out.println(id);
return new AjaxResult(200, "get 查询成功");
}
@PutMapping(produces = "application/json")
public AjaxResult put(@RequestBody User user) {
System.out.println(user.getPassword());
System.out.println(user.getUsername());
return new AjaxResult(200, "put 修改成功");
}
@DeleteMapping(value = "/{id}",produces = "application/json")
public AjaxResult delete(@PathVariable("id")Integer id) {
System.out.println(id);
return new AjaxResult(200, "delete 删除成功");
}
}
下面是每个方法的postman请求的方式
@PostMapping(produces = "application/json")
public AjaxResult post(@RequestBody User user) {
System.out.println(user.getPassword());
System.out.println(user.getUsername());
return new AjaxResult(200, "post 创建成功");
}
@GetMapping(value = "/{id}",produces = "application/json")
public AjaxResult get(@PathVariable("id")Integer id) {
System.out.println(id);
return new AjaxResult(200, "get 查询成功");
}
@PutMapping(produces = "application/json")
public AjaxResult put(@RequestBody User user) {
System.out.println(user.getPassword());
System.out.println(user.getUsername());
return new AjaxResult(200, "put 修改成功");
}
@DeleteMapping(value = "/{id}",produces = "application/json")
public AjaxResult delete(@PathVariable("id")Integer id) {
System.out.println(id);
return new AjaxResult(200, "delete 删除成功");
}
从上面可以看到 并没有通过请求路径去指定执行的方法,就可以执行到想要执行的方法,就是通过请求的方式来进行选择。
在某些方面可以减少我们请求路径的长度
在上面使用的注解也可以使用以下方式
在 method 属性中确定该请求的方式
//在 method 属性中确定该请求的方式
@RequestMapping(value = "", method = GET, produces = "application/json")
@RequestMapping(value = "", method = POST, produces = "application/json")
@RequestMapping(value = "", method = PUT, produces = "application/json")
@RequestMapping(value = "", method = DELETE, produces = "application/json")
以上两类注解区别不大 以@PostMapping为例 该注解上的注解使用的还是 @RequestMapping 其他几种也是这样
需要使用对象接收数据的时候记得不要忘了添加 @RequestBody注解
在对象中有Date类型的字段时记得添加@JsonFormat(shape=JsonFormat.Shape.STRING, pattern=“yyyy-MM-dd”)
以上是我在使用json接收数据时遇到的问题。如有错误,请各位大佬指点。