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

2021/9/3 23:36:11

本文主要是介绍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}"}) 

  再次测试,成功访问,问题解决。

 



这篇关于controller层方法上@pathvariable注解中required=false作用失效的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程