今天在项目中书写分页接口的时候,在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);
复制代码
建议在书写代码的时候,保持良好的书写习惯,不随意书写代码,便能避开很多不必要的坑!
积少成多,滴水穿石!