rest demo下载地址:https://download.csdn.net/download/yanhhuan/13101768
@PathVariable
获取url中的数据
该注解是实现RESTFull最主要的一个注解
eg:
package com.example.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* restfull
*/
@RestController
public class RESTFullController {
//访问地址http://localhost:8080//boot/restfullstudent/id/status
@RequestMapping("/boot/restfullstudent/{id}/{status}")
public Object restfullstudent(@PathVariable("id") Integer id,@PathVariable("status") Integer status){
Map<String,Object> map=new HashMap<String,Object>();
map.put("id",id);
map.put("status",status);
return map;
}
}
放参数的位置也可以改变
//访问地址http://localhost:8080//boot/id/restfullstudent/status
@RequestMapping("/boot/{id}/restfullstudent/{status}")
public Object restfullstudent01(@PathVariable("id") Integer id,@PathVariable("status") Integer status){
Map<String,Object> map=new HashMap<String,Object>();
map.put("id",id);
map.put("status",status);
return map;
}
注:同一个类中如果存在两个方法,路径中的http一致
restfull访问参数位置是不一致的
那参数位置可以不一致但是顺序要一致,如果顺序不一致方法会报错
eg:
@RequestMapping("/boot/restfullstudent/{id}/{status}")
@RequestMapping("/boot/{id}/restfullstudent/{status}")
这样在同一个类中是可以的
但是
@RequestMapping("/boot/restfullstudent/{id}/{status}")
@RequestMapping("/boot/{status}/restfullstudent/{id}")
这样在同一个类中是不可以的
解决冲突的2个方法:
1.路径改为不一样的
@RequestMapping("/boot/restfullstudent/{id}/{status}")
@RequestMapping("/boot/{status}/restfullstudentsn/{id}")
2.修改请求方式
eg:第二个方法改为
@PostMapping
RESTFull原则:
1.增post请求,删delete请求,改put请求,查get请求
@PostMapping
@DeleteMapping
@PutMapping
@GetMapping
2.请求路径不要出现动词,比如查询订单:/boot/order/1/1021 (正确),/boot/queryOrder/1/1021 (不建议)
3.分页、排序等操作,不需要采用斜杠传参数,订单列表接口:/boot/orders?p=1&sort=desc,传的参数不是数据库的字段,可以不采用斜杠