@GetMapper 实现有参数和无参数同时访问(转)

    

@GetMapper 实现有参数和无参数同时访问

@GetMapper 实现有参数和无参数同时访问

在使用@GetMapper时,写过下面的代码:

@GetMapping("/getBincodeType/{whCode}")
public Result getBincodeType(@PathVariable String whCode) {...}

然后遇到了一个问题,如果whCode没有值时,我希望whCode是null或者是空字符串,但是我请求时,报404,找不到这个接口.
解决方法如下:

@GetMapping(value = {"/getBincodeType/{whCode}","/getBincodeType"})
public Result getBincodeType(@PathVariable(required = false) String whCode) {...}

解释:
查看@GetMapping源代码发现

 value是个数组,这说明value可以是多个值,也就是说@GetMapping可以设置多个接口.
而在@PathVariable的源代码中可以发现,其中有一个required属性,默认是true,也就是说whCode是必须的,如果希望接受值可以为空,就必须手动设置为false

原文地址:https://www.cnblogs.com/huanghongbo/p/13656594.html