1. 程式人生 > >restful風格url Get請求查詢所有和根據id查詢的合併成一個controller

restful風格url Get請求查詢所有和根據id查詢的合併成一個controller

restful風格url Get請求查詢所有和根據id查詢的合併成一個controller的方法

原始碼

    // 127.0.0.1:8080/dep/s
   @ApiOperation(value="查詢所有", notes="查詢所有") @RequestMapping(value = "/s",method = RequestMethod.POST) public List<Dep> deps() { return depService.queryAll(); }   

   // 127.0.0.1:8080/dep/1 @GetMapping(value
= "/{id}") public Dep get(@PathVariable Long id){ return depService.queryById(id); }

  該種寫法不夠完美,寫多個方法並且匹配的不是相同的url.強迫症表示不能接受

改寫

   // 127.0.0.1:8080/dep/test  查詢全部
// 127.0.0.1:8880/dep/test/1 查詢ID為1
   @ApiOperation(value="測試同時實現查詢所有和根據id查詢", notes="測試同時實現查詢所有和根據id查詢") @RequestMapping(value
= {"/test/{id}","/test"},method = RequestMethod.GET) public Object deps(@PathVariable( value = "id",required = false) String id) { if(StringUtils.isEmpty(id)){ // ID為空查全部 return depService.queryAll(); }else { // 不為空根據id查詢 return depService.queryById(id); } }

 也可以直接對映兩個不同方法,這裡是不同的url對映同一個方法

  必須匹配多個url時requird = false才能生效(我猜的!)

  參考[1].https://www.imooc.com/qadetail/268268?t=436798