上一篇SpringBoot實戰(二)Restful風格API接口中寫了一個控制器,擷取了前端請求的參數,現在我們就參數的擷取與校驗做一個介紹:
一:擷取參數
SpringBoot提供的擷取參數注解包括:@PathVariable,@RequestParam,@RequestBody,三者的差別如下表:
示例代碼:
Order:
1 packagecom.example.demo.controller.user.entity;2
3 public classOrder {4 privateInteger id;5 privateString name;6 privateInteger price;7
8 publicInteger getId() {9 returnid;10 }11
12 public voidsetId(Integer id) {13 this.id =id;14 }15
16 publicString getName() {17 returnname;18 }19
20 public voidsetName(String name) {21 this.name =name;22 }23
24 publicInteger getPrice() {25 returnprice;26 }27
28 public voidsetPrice(Integer price) {29 this.price =price;30 }31 }
OrderController
1 packagecom.example.demo.controller.user.controller;2
3 importcom.example.demo.controller.user.entity.Order;4 import org.springframework.web.bind.annotation.*;5
6 @RestController7 public classOrderController {8
9
16 @GetMapping("/orders/{id}")17 public String getOrder(@PathVariable(value = "id")Integer id,18 @RequestParam(value = "name")String name,19 @RequestParam(value = "price",required = false,defaultValue = "0") Integer price){20 String result = "id:"+id+",name:"+name+",price:"+price;21 returnresult;22 }23
24
29 @PostMapping("/order/check")30 publicString checkOrder(@RequestBody Order order){31 String result = "id:"+order.getId()+",name:"+order.getName()+",price:"+order.getPrice();32 returnresult;33 }34
35
41 @PostMapping("/order/checkmore")42 public String checkMore(@RequestParam(value = "amount")Integer amount, @RequestParam(value = "discount")floatdiscount){43 String result = "amount:"+amount+",discount:"+discount;44 returnresult;45 }46
47
52 @PostMapping("/order/add")53 publicString addOrder(Order order){54 String result = "id:"+order.getId()+",name:"+order.getName()+",price:"+order.getPrice();55 returnresult;56 }57
58
64 @PutMapping("/order/{id}/update")65 public String updateOrder(@PathVariable(value = "id")Integer id,Order order){66 String result = "pathid:"+id+"===Order(id:"+order.getId()+",name:"+order.getName()+",price:"+order.getPrice()+")";67 returnresult;68 }69
70
71 }
注意點:
1.針對一些非必填的參數,可以使用required關鍵字來辨別,同時必須設定預設值defaultValue,如getOrder方法中對price參數的擷取:
@RequestParam(value = "price",required = false,defaultValue = "0") Integer price
2.參數可以直接與Entity類綁定,但不支援json格式,隻支援form-data和x-www.form-urlencoded格式
@PostMapping("/order/add")
public String addOrder(Order order){
3.使用的Postman做的測試,所有接口都測試通過,也推薦大家使用Postman作為日常的接口測試工具,安裝和操作都很簡單。
附部分截圖:
Get:@PathVariable,@RequestParam
Post:@RequestBody
擷取到參數以後就是要對資料做校驗了,在下一篇中進行介紹