1.是什么
@RequestParam和@PathVariable是SpringMVC中控制层获取Request里参数用到的注解,起到配置、说明参数传递方式的作用。
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: 参数的默认值,如果本次请求没有携带这个参数或者参数为空,将会启用默认值;
@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 表示参数必须传