前言
项目中遇到文件下载的功能,前后台联调时发现请求的url是这个样的:‘http://localhost:8084/datumManager/downLoadDatum/information.xlsx?datumUrl=Libgroup1/M00/00/02/wKgWQFqWeR-AGH5BAAA8gzGPs5o20.xlsx“’ ,再看后台接口请求参数一个是@RequestParam,一个是@PathVariable,这两个有什么不同?一起来看看。
正文
1、是什么
@RequestParam和@PathVariable是SpringMVC中控制层获取Reques里参数用到的注解,起到配置、说明参数传递方式的作用。
2、怎么用
@RequestParam
参数绑定说明:当方法中带有参数时,可以采用@RequestParam 绑定单个请求参数值
@RequestMapping(value = {"/selectPaperDatum}"}, method = RequestMethod.GET)
public ItooResult selectPaperDatum(@RequestParm("studentId") String studentId) {
}
对应的URL:
http://localhost:8084/.../selectPaperDatum?studentId=123
@RequestParam 支持的参数
- value/name : 参数名字,可以不写,默认为“”; 上例中的studentId作为参数值将传入;
- required : 参数是否为必须,默认为true,可以不写;
- defaultValue: 参数的默认值,如果本次请求没有携带这个参数或者参数为空,将会启用默认值;
@RequestMapping(value = {"/selectPaperDatum}"}, method = RequestMethod.GET)
public ItooResult selectPaperDatum(@RequestParm(required = false,defaultValue = "")String studentId) {
}
@PathVariable
参数绑定说明:当方法中带有参数时,可以采用@PathVariable将URL中的占位符参数传入到方法参数变量中。
@RequestMapping(value = "copyPaperByPaperId/{paperId}/{paperName}", method = RequestMethod.POST)
public ItooResult copyPaperByPaperId(@PathVariable String paperId, @PathVariable String paperName) {
}
对应的URL
http://localhost:8084/papersManager/copyPaperByPaperId/123/测试
3、区别
@RequestParam 用来获得静态URL中传入的参数,@PathVariable 用来获得动态URL中的参数
@RequestParam 表示参数可传可不穿,@PathVariable 表示参数必须传
总结
关于@RequestParam 和@PathVariable 的使用,暂且介绍到这里,在看代码的时候,大部分人用的是@PathVariable ,请看到这篇博客的人分享下经验。