RESTful
是⼀种 Web api 的标准,也就是⼀种 url 设计⻛格 / 规范
每个URL请求路径代表服务器上的唯⼀资源
传统的URL设计:
http://localhost:8080/goods/delete?goodsId=1 商品1
http://localhost:8080/goods/delete?goodsId=2 商品2
RESTful设计:
http://localhost:8080/goods/delete/1 商品1
http://localhost:8080/goods/delete/2 商品2
@RequestMapping("/delete/{gid}")
public ResultVO deleteGoods(@PathVariable("gid") int goodsId){
System.out.println("-----"+goodsId);
return new ResultVO(10000,"delete success",null);
}
使⽤不同的请求⽅式表示不同的操作
SpringMVC 对 RESTful ⻛格提供了很好的⽀持,在我们定义⼀个接⼝的 URL 时,可以通过 @RequestMapping(value=“/{id}”,method=RequestMethod.GET)形式指定请求⽅式,也可使⽤特定请求⽅式的注解设定 URL
@PostMapping(“/add”)
@DeleteMapping(“/{id}”)
@PutMapping(“/{id}”)
@GetMapping(“/{id}”)
- post 添加
- get 查询
- put 修改
- delete 删除
- option (预检)
根据ID删除⼀个商品:
//http://localhost:8080/goods/1 [delete]
@RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
public ResultVO deleteGoods(@PathVariable("id") int goodsId){
System.out.println("-----"+goodsId);
return new ResultVO(10000,"delete success",null);
}
根据ID查询⼀个商品:
//http://localhost:8080/goods/1 [get]
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public ResultVO getGoods(@PathVariable("id") int goodsId){
return null;
}
- 接⼝响应的资源的表现形式采⽤JSON(或者XML)
- 在控制类或者每个接⼝⽅法添加 @ResponseBody 注解将返回的对象格式为json
- 或者直接在控制器类使⽤ @RestController 注解声明控制器
- 前端(Android\ios\pc)通过⽆状态的HTTP协议与后端接⼝进⾏交互