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

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

@RequestParam:

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

示例程序以下:

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

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

@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中的字段名一致。apache

示例程序以下:

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]mybatis

错误代码示例以下:

List<Employee> getAllEmployeeByPage(@RequestParam("page") Integer page, @RequestParam("size") Integer size);
复制代码

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

聚沙成塔,滴水穿石!测试

相关文章
相关标签/搜索