栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot中@RequestParam和@PathVariable的用法与区别

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot中@RequestParam和@PathVariable的用法与区别

今天编写代码时发现路径参数和查询参数的问题 ,不知道用哪个,写篇文章记录一下

RESTful API设计的最佳实践是使用路径参数来标识一个或多个特定资源,而使用查询参数来对这些资源进行排序/过滤

@PathVariable

会用在单个对象的查询上,比如要根据ID值查询学生信息,就会在Postman发送GET请求,后台使用@PathVariable接收

后端是

@RequestMapping(value="/page/{name}/{age}",method=RequestMethod.GET)
public String getName(ModelMap map,@PathVariable("name") String name,@PathVariable("age") int age)
{
    map.addAttribute("name",name);
    map.addAttribute("age",age);
    return "name";
}

接口样式是

http://localhost:8080/page/xiaoming/18
@RequestParam

会用在组合查询多个对象,比如跟据姓名模糊查询和性别组合查询筛选学生,就会发送POST请求,后台使用RequestParam接收
后端:

@RequestMapping(value="/result",method=RequestMethod.GET)
public String resultParam(ModelMap map,@RequestParam String name,@RequestParam int age)
{
    map.addAttribute("name",name);
    map.addAttribute("age",age);
    return "result";
}

接口样式:

http://localhost:8080/result?name=xiaoming&age=20
区别:

1、当URL指向的是某一具体业务资源(或资源列表),例如博客,用户时,使用@PathVariable

这个是举例是为了获取具体某一个缺陷或者用户的时候用

2、当URL需要对资源或者资源列表进行过滤,筛选时,用@RequestParam

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/969970.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号