用过SpringMVC框架的小伙伴们都知道,@RequestParam就是用来处理入参的,但可能你会奇怪,平时不使用这个参数也可以获取到参数呀,加与不加都可以获取参数,是这样吗?
1、不添加@RequestParam注解
首先我们创建测试的控制器类,方法中添加一个参数name,此时参数没有添加@RequestParam注解,如下:
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam("name") String name){
String str = "name:"+name;
return str;
}
启动项目后,通过浏览器访问测试效果,不带参数则获取的参数为null,但页面可以正常显示,请求可以正常的执行,带上参数之后,参数可以正常的获取并打印出来了,如下:


2、添加@RequestParam注解,没有任何注解设置参数
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam String name){
String str = "name:"+name;
return str;
}
再次启动项目后,通过浏览器访问查看效果,此时带上name参数页面可以正常显示并打印出结果值,但如图所示,不带参数的时候,页面报错,返回400,并提示name不存在,如下:

3、@RequestParam注解参数说明和使用
3.1、参数required表示该参数是否为必须要提交的,默认为true,即必须要提交的,如果没有提交该参数则会报错;false表示不是必须的,如果没有提交该参数不会报错。
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam(required=true) String name){
String str = "name:"+name;
return str;
}
此时参数required=true,name参数提交则正常显示,不提交则会报错,如下:

如果将参数改为required=false,name参数提交则正常显示,不提交则会显示null,不会报错
3.2、参数defaultValue用来在参数为空的情况下为该参数设置一个默认值,如果参数不为空,则正常获取参数值,如果为空,则参数值为该默认值,如下:
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam(defaultValue="我是默认值") String name){
String str = "name:"+name;
return str;
}
浏览器访问效果如下:

3.3、参数value是在提交的参数名和方法中接收参数的变量名不一致时使用,如果页面提交的参数名为inputName,而方法中定义的接收参数的变量名为name,此时就用到参数value了,如下:
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam("inputName") String name){
String str = "name:"+name;
return str;
}
4、此时我们会发现,@RequestParam注解加与不加参数都能正常获取到,那么接下来我们来修改一个eclipse的配置,再来看一下,修改的配置如下图:

我们将图中标出的这个配置取消勾选,保存修改后再启动项目,在没有添加@RequestParam注解和只是添加了@RequestParam注解,而没有添加注解的value参数时。
//没有添加@RequestParam注解
@RequestMapping("/testRequestParam")
public String testRequestParam(String name){
String str = "name:"+name;
return str;
}
//只是添加了@RequestParam注解,而没有添加注解的value参数
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam String name){
String str = "name:"+name;
return str;
}
你会发现页面会报500错误,而eclipse同样也会报错,结果如下:

eclipse的该设置表示:将变量属性添加到生成的类文件里面;
当然在我们开发阶段不会去修改这些配置,不会出现问题,但是当项目发布到真实环境中,不知道它是如何编译的,配置是否相同,如果不同,那么系统将会出现问题,无法运行。所以为了养成良好的习惯,不给自己埋坑,在开发时将@RequestParam注解写上为好!
网友评论