@PathVariable注解的required属性值默认为ture,表示必须有值,不能接收空值,false为可以为空值。
单路径或多路径为@RequestMapping注解value属性可以接收URL字符串数组。
单路径,无论@PathVariable注解required值为ture或false,都不可以接收空值,如果URL没带值,则报404:
路径:localhost:8001/op-project-service/v1/op_proj_plans_ext/queryDemandList
localhost:8001/op-project-service/v1/op_proj_plans_ext/queryDemandList/
@GetMapping(value = {"/queryDemandList/{versionId}"})
public WsgResult<List<Map<String, Object>>> queryDemandList(@PathVariable(value = "versionId", required = false) String versionId) {
return new WsgResult<>(opProjPlanExtApp.queryDemandList(versionId));
}
{
"timestamp": "2022-02-22 11:13:36",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/op-project-service/v1/op_proj_plans_ext/queryDemandList"
}
多路径,如果@PathVariable注解的required属性值为true,而接口URL没带值报以下错误:
路径:localhost:8001/op-project-service/v1/op_proj_plans_ext/queryDemandList
localhost:8001/op-project-service/v1/op_proj_plans_ext/queryDemandList/
@GetMapping(value = {"/queryDemandList/{versionId}", "/queryDemandList"})
public WsgResult<List<Map<String, Object>>> queryDemandList(@PathVariable(value = "versionId", required = true) String versionId) {
return new WsgResult<>(opProjPlanExtApp.queryDemandList(versionId));
}
返回:org.springframework.web.bind.MissingPathVariableException 丢失路径变量异常
{
"timestamp": "2022-02-22 11:05:33",
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.web.bind.MissingPathVariableException",
"message": "Missing URI template variable 'versionId' for method parameter of type String",
"path": "/op-project-service/v1/op_proj_plans_ext/queryDemandList/"
}
解决:
@PathVariable注解的required属性值改为false,URL不带值也可访问。
如以下三种:
localhost:8001/op-project-service/v1/op_proj_plans_ext/queryDemandList
localhost:8001/op-project-service/v1/op_proj_plans_ext/queryDemandList/
localhost:8001/op-project-service/v1/op_proj_plans_ext/queryDemandList/123