Java后端避坑——@RequestParam和@Param注解

今天在项目中书写分页接口的时候,在Controller层和dao层分别用了@RequestParam和@Param这两个注解。简单说一下对这两个注解的理解。

@RequestParam:

一般用在Controller层,用来解决前端与后端参数不一致的问题,在参数上加上@RequestParam,那么前端的参数必须和后端参数一致,否则会报错。当只有一个参数的时候,Controller层中@RequestParam和@Param可以互用,当有多个参数的时候,Controller层中@RequestParam和@Param不能互用

示例程序如下:
@GetMapping("/")
public RespPageBean getAllEmployeeByPage(@RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "10")Integer size){
     return salaryService.getAllEmployeeByPage(page,size);
}
复制代码

另一个作用是指定Value或name的参数名,或者指定参数是否必传 ####该注解的底层代码如下:

@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";
}
复制代码
@Param:

一般用在dao层,用来给参数命名,在Mybatis的mapper中加上该注解,传递的参数与Sql中的字段名一致。

示例程序如下:
 List<Employee> getAllEmployeeByPage(@Param("page") Integer page, @Param("size") Integer size);
复制代码
该注解的底层代码如下:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface Param {
    String value();
}
复制代码

笔者测试了一下将上面程序中的@Param注解更换为@RequestParam,程序编译没有报错,但是点击前端页面的分页组件时,出现了如下错误:

2019-04-25 21:23:48.703 ERROR 9148 --- [nio-8082-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'page' not found. Available parameters are [arg1, arg0, param1, param2]] with root cause org.apache.ibatis.binding.BindingException: Parameter 'page' not found. Available parameters are [arg1, arg0, param1, param2]

错误代码示例如下:
 List<Employee> getAllEmployeeByPage(@RequestParam("page") Integer page, @RequestParam("size") Integer size);
复制代码

建议在书写代码的时候,保持良好的书写习惯,不随意书写代码,便能避开很多不必要的坑!

积少成多,滴水穿石!

转载于:https://juejin.im/post/5cc1c6015188252dc725d100

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值