Spring Boot MVC 普通参数传递测试与总结

本文探讨了在Spring MVC中不使用@RequestParam注解处理请求参数的各种情况,包括字符串和数值类型。分析了参数传递为空、类型错误时的响应,并详细解释了@RequestParam注解的作用,如默认值和是否必需。建议在处理请求参数时使用@RequestParam注解以确保参数的正确解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不加@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都一样):

URL:http://localhost:8080/add

结果 success 7

明明是必须参数,但是不传递参数 有默认值代替

默认参数都是字符串,前后端数据交互,本质都是字符串


required = false 和上述结果都一样,我们来测试一下没有默认值的

直接给出结论

只要加了defaultValue那么required的取值如何,毫无意义

@RequestParam(defaultValue = "1") Integer age

所以想要有默认参数,直接写成上面的就可以,想要必须传递参数, @RequestParam Integer即可实现!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值