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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM