spring boot 常見http請求url引數獲取
在定義一個Rest介面時通常會利用GET、POST、PUT、DELETE來實作資料的增刪改查;這幾種方式有的需要傳遞引數,后臺開發人員必須對接收到的引數進行引數驗證來確保程式的健壯性
-
GET:一般用于查詢資料,采用明文進行傳輸,一般用來獲取一些無關用戶資訊的資料
-
POST:一般用于插入資料
-
PUT:一般用于資料更新
-
DELETE:一般用于資料洗掉;一般都是進行邏輯洗掉(即:僅僅改變記錄的狀態,而并非真正的洗掉資料)
1、@PathVaribale 獲取url中的資料
請求URL:localhost:8080/hello/id 獲取id值
實作代碼如下:
@RestController
publicclass HelloController {
@RequestMapping(value="https://www.cnblogs.com/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引數保持一致
請求URL:localhost:8080/hello?id=1000
@RestController
publicclass HelloController {
@RequestMapping(value="https://www.cnblogs.com/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam Integer id){
return"id:"+id;
}
}
輸出:id:100
url中有多個引數時,如:
localhost:8080/hello?id=98&&name=helloworld
具體代碼如下:
@RestController
publicclass HelloController {
@RequestMapping(value="https://www.cnblogs.com/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
publicclass HelloController {
@RequestMapping(value="https://www.cnblogs.com/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam("userId") Integer id){
return"id:"+id;
}
}
輸出:id:100
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/265575.html
標籤:其他
