spring boot 常見http get ,post請求參數處理
在定義一個Rest接口時通常會利用GET、POST、PUT、DELETE來實現數據的增刪改查;這幾種方式有的需要傳遞參數,后台開發人員必須對接收到的參數進行參數驗證來確保程序的健壯性
GET
一般用於查詢數據,采用明文進行傳輸,一般用來獲取一些無關用戶信息的數據
POST
一般用於插入數據
PUT
一般用於數據更新
DELETE
一般用於數據刪除
一般都是進行邏輯刪除(即:僅僅改變記錄的狀態,而並非真正的刪除數據)
@PathVaribale 獲取url中的數據
@RequestParam 獲取請求參數的值
@GetMapping 組合注解,是 @RequestMapping(method = RequestMethod.GET) 的縮寫
@RequestBody 利用一個對象去獲取前端傳過來的數據
1. PathVaribale 獲取url路徑的數據
請求URL:
localhost:8080/hello/id 獲取id值
實現代碼如下:
@RestController public class HelloController { @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET) public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){ return "id:"+id+" name:"+name; } }
在瀏覽器中 輸入地址:
localhost:8080/hello/100/hello
輸出:
id:81name:hello
2. RequestParam 獲取請求參數的值
獲取url參數值,默認方式,需要方法參數名稱和url參數保持一致
localhost:8080/hello?id=1000
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(@RequestParam Integer id){ return "id:"+id; } }
輸出:
id:100
url中有多個參數時,如:
localhost:8080/hello?id=98&&name=helloworld
具體代碼如下:
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(@RequestParam Integer id,@RequestParam String name){ return "id:"+id+ " name:"+name; } }
獲取url參數值,執行參數名稱方式
localhost:8080/hello?userId=1000
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(@RequestParam("userId") Integer id){ return "id:"+id; } }
輸出:
id:100
注意
不輸入id的具體值,此時返回的結果為null。具體測試結果如下:
id:null
不輸入id參數,則會報如下錯誤:
whitelable Error Page錯誤
3. GET參數校驗
用法:不輸入id時,使用默認值
具體代碼如下:
localhost:8080/hello
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) //required=false 表示url中可以無id參數,此時就使用默認參數 public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){ return "id:"+id; } }
輸出
id:1
參考:https://blog.csdn.net/yunfeng482/article/details/79756233