注解@RequestParam方法原理解析

我从做CS转到BS,经常使用@RequestParam这个注解,那么@RequestParam的原理到底是什么呢?
文中对该注解进行原理解析,需要的可以参照一下文中解释 。

1.作用

该注解的作用在方法传递的参数前,用于接收所传参数,适用于get请求。

例如:http://127.0.0.1:61308/tiap_ems_basic_mgt/v1/wdm/links_page?page=2&start=0&limit=1
可以用来接收问号后面的参数值(允许多个参数)

postman中是这样子的。
在这里插入图片描述

2.支持的4个属性

2.1 name

指定传入的参数名称,其后面跟的参数名称一定要与前端传入的参数名称一致。

2.2 value

指定传入的参数名称,其后面跟的参数名称一定要与前端传入的参数名称一致。

2.3 required

指定参数是否是必传参数,如果不指定,默认为true。

2.4 defaultValue

指定参数的默认值。

注意:其中name和value属性的作用等同的.其源码中name的别名就是value,value的别名就是name 。

2.5 参见@RequestParam源码
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
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";
}

3.使用的时候需要注意的一些问题

3.1 @RequestParam可以解决前后端定义的参数名不一致的问题

例如前端传入的参数名是name,后端方法接收的参数名是userName,这时可以通过@RequestParam指定value的值为name,实现name与userName的映射。

@RequestMapping(method = RequestMethod.GET, value = "selectCourseAndTeacherByStudent")
 public Course selectCourseAndCourseByStudent(@RequestParam(value = "name") String userName) {
   Course course = studentService.selectCourseAndTeacherByStudent(userName);
   return course;
 }
3.2 如果后端使用的是基本数据类型来接收参数,那么一定要设置required=false,并且要设置一个默认值
@RequestMapping(method = RequestMethod.GET,value = "selectStudentById")
 public Student selectStudentById(@RequestParam(value = "id",required = false,defaultValue = "01") int id){
   return studentService.selectStudentById(id);
 }

因为考虑到前端没有传值的情况,如果此时仅仅设置了required=false,会报500错误(下图异常)因为基本数据类型无法接收null,
在这里插入图片描述

3.3 如果后端使用的是引用数据类型,则无需设置required=false和defaultValue

因为即使前端没有传入参数值,引用数据类型是可以接收null的。

@RequestMapping(method = RequestMethod.GET,value = "selectStudentById")
 public Student selectStudentById(@RequestParam(value = "id") Integer id){
   return studentService.selectStudentById(id);
 }

建议使用这种方式来写。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值