不加@RequestParam引用类型参数
@GetMapping("/add")
public String add(String name) {
return "success "+name;
}
传递参数:
URL: http://localhost:8080/add?name=ckj
结果: success ckj
不传递参数:
URL: http://localhost:8080/add
结果 success null
传递空参数:
URL: http://localhost:8080/add?name=
结果: success
结论:传递参数但值为空,本质是传递了空串
不加@RequestParam引用类型参数(数值型)
Integer
传递参数:
URL: http://localhost:8080/add?age=12
结果: success 12
不传参数:
URL: http://localhost:8080/add
结果:success null
传递空参数:
URL: http://localhost:8080/add?age=
结果:success null
传递类型错误的参数:
URL: http://localhost:8080/add?age=ckj
结果
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Aug 18 13:17:28 ULAT 2021
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "ckj"
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "ckj"
结论:非字符串会产生类型转换,由于Integer可以为空,所以为null
不加@RequestParam 基本类型参数
@GetMapping("/add")
public String add(int age) {
return "success "+age;
}
结论:只有传递且传递正确数值才有正常结果,不传递或传递空串都报错
加@RequestParam传递参数
public @interface RequestParam {
@AliasFor("name")
String value() default "";
@AliasFor("value")
String name() default "";
boolean required() default true;//加上注解默认为必须参数
String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
}
建议加该注解,依据源码spring会先解析有注解的参数,然后是Servlet的Api,然后是Model,最后才是普通参数和pojo对象
该注解值得注意的地方是require和defaultValue的关系
@GetMapping("/add")
public String add(@RequestParam(required = true,defaultValue = "7") int age) {
return "success "+age;
}
不传递参数传递空参数(int和Integer都一样):
结果 success 7
明明是必须参数,但是不传递参数 有默认值代替
默认参数都是字符串,前后端数据交互,本质都是字符串
required = false 和上述结果都一样,我们来测试一下没有默认值的
直接给出结论
只要加了defaultValue那么required的取值如何,毫无意义
@RequestParam(defaultValue = "1") Integer age
所以想要有默认参数,直接写成上面的就可以,想要必须传递参数, @RequestParam Integer即可实现!!!