@PathVariable路径变量接收空值处理方案

在Spring框架中,默认@PathVariable的required属性为true,意味着路径变量必须有值,否则会抛出404错误。若将required设置为false,即使URL不带值也能访问接口。通过调整@PathVariable的required属性为false,可以解决路径变量为空时无法访问的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@PathVariable注解的required属性值默认为ture,表示必须有值,不能接收空值,false为可以为空值。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dC2FuYzj-1645500749393)(D:\Markdown图片\image-20220222112141650.png)]

单路径或多路径为@RequestMapping注解value属性可以接收URL字符串数组。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yETcuc4J-1645500749394)(D:\Markdown图片\image-20220222112956218.png)]

单路径,无论@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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王景清

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值