controller層方法上@pathvariable注解中required=false作用失效


一.問題背景

  通過get請求訪問controll層方法報錯,代碼和報錯如下圖:

  代碼:

 1 @RestController
 2 @RequestMapping("category")
 3 @Api(tags = "分類管理API")
 4 public class CategoryController {
 5 
 6     @Autowired
 7     private CategoryService categoryService;
 8 
 9 
10 
11     @ApiOperation(value = "請求商品分類列表",notes = "該方法后續待增強,提供搜索和分頁功能實現")
12     @ApiResponses({
13             @ApiResponse(code = 0,message = "請求成功"),
14             @ApiResponse(code = 900,message = "請求失敗")
15     })
16     @GetMapping({"{page}/{limit}/{search}"})
17     public ResultData<Page<TbCategory>> getCategories(@PathVariable("page") Integer page,
18                                                       @PathVariable("limit") Integer limit,
19                                                       @PathVariable(value = "search",required = false) String search){
20         Page<TbCategory> categoryPage = categoryService.selectCategory(page, limit, search);
21         if (categoryPage != null) {
22             return new ResultData(0,"success",categoryPage);
23         }
24         return new ResultData<>(900,"failed");
25     }
26 }

  報錯:

 

   url上不添加第三個參數就會報錯404,似乎這個注解@pathvariable中required=false參數指定沒有效果,在路徑上指定這個參數,就能正常訪問到后台數據。

二.解決思路

  在@GetMapping中指定多種訪問url路徑,可以解決,如下:

 1 @GetMapping({"{page}/{limit}/{search}","{page}/{limit}"}) 

  再次測試,成功訪問,問題解決。

 


免責聲明!

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



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