一、@RequestParam
RequestParam的意思是请求参数,顾名思义,这是需要传入url的参数,在百度上搜索淘宝后,网址可能会跳转到https://www.baidu.com/?xxx=百度&xxx=nnn,在这里,问号之后的xxx=百度&xxx=nnn便是我们输入的请求参数,参数之间用&分隔,参数形如key=value。
1、这里的请求参数可以当做用户自定义输入的,所以根据不同的用户输入,网页会有不同的处理输出。
在代码中的书写格式如下:
/**
* 语法:@RequestParam(value="参数名",required="true/false",defaultValue="")
* value可以省略,省略时根据会定义的变量名进行绑定,也可以绑定指定参数名
* 例如:@RequestParam String name等价于@RequestParam("name") String name
*/
@RequestMapping("/index/param")
public String requestBodyTest(@RequestParam String name, @RequestParam String sex){
return name+":"+sex;
}
在网址中输入:localhost:8080/index/param?name=NAME&sex=SEX
PS:还有个注解和@RequestParam相似,叫@RequestBody,这个注解和@Request的区别就是传入的参数是一个整的对象,而不是参数。
2、可以通过required=false或者true来要求@RequestParam配置的前端参数是否一定要传
/**
* 是否必须接收该请求参数
* 默认required = ture,如果设置了flase,则表示该参数可以不传,并且被赋值为null
* 如果注解的参数是int基本类型,但是required=false,这时如果不传参数值会报错,因为不传值,会赋值
* 为null给int,是非法的,可以用包装类Interge代替基本类型int
*/
@GetMapping("/param/required")
public String requestParamRequiredTest(@RequestParam(required = false) String name){
LOG.info("url:localhost:8080/index/param/required");
if (name == null)
return "没有传name";
return name;
}
2、defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值
@GetMapping("/param/defaultValue")
public String requestParamDefaultValueTest(@RequestParam(defaultValue = "默认值") String name){
LOG.info("url:localhost:8080/index/param/defaultValue");
return name;
}
二、@PathVariable
PathVariable的意思是路径变量,顾名思义,这是需要传入url的路径变量,因为路径不一定是一成不变的,可能会有相同的源,只是部分路径不一样,比如张三的个人主页路径是system/user/张三/page,李四的个人主页路径是system/user/李四/page,在处理这种问题时,不可能给每个人都手动分配url,这时,可以通过注解@PathVariable来处理
这里的路径变量也是可以当做用户自定义输入的,所以根据不同的用户输入,网页会有不同的处理输出。
在代码中的书写格式如下:
@RequestMapping("/index/{username}/page")
public String pathVariableTest(@PathVariable String username){
return username;
}
在网址中输入:http://localhost:8080/index/张三/page
在网址中输入:http://localhost:8080/index/李四/page
@RequestParam和@PathVariable都能够完成类似的功能——因为本质上,它们都是用户的输入,只不过输入的部分不同,一个在URL路径部分,另一个在参数部分。要访问一篇博客文章,这两种URL设计都是可以的:
- 通过@PathVariable,例如/blogs/1
- 通过@RequestParam,例如blogs?blogId=1
那么究竟应该选择哪一种呢?建议:
- 当URL指向的是某一具体业务资源(或者资源列表),例如博客,用户时,使用@PathVariable
- 当URL需要对资源或者资源列表进行过滤,筛选时,用@RequestParam
例如我们会这样设计URL:
- /blogs/{blogId}
- /blogs?state=publish而不是/blogs/state/publish来表示处于发布状态的博客文章