@pathvariable 和 @Requestparam的详细区别

前言

使用springboot项目的时候,经常看到这两个注解的在项目中的混用 对于springboot的基础知识点可看我之前的文章:

今天详细分析下@pathvariable 和 @Requestparam(都归属spring注解)

    @PathVariable:/manongyanjiuseng/18 @RequestParam:/manongyanjiuseng?age=18

区别在于一个是用?,一个使用/进行传输数据 这种格式类似:

1. 源码解析

查看@pathvariable注解的源码:

@Target({
          
   ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {
          
   
    @AliasFor("name")
    String value() default "";

    @AliasFor("value")
    String name() default "";

    boolean required() default true;
}

查看@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 "
		
		
ue000ue001ue002
				
";
}

对比两者的源码 @Requestparam 比 @pathvariable多了一个参数String defaultValue() 大致意思:如果请求体中没有对应的参数变量,使用default对该参数变量赋值,赋上默认值

@pathvariable 和 @Requestparam 这两个注解一般配合如下注解进行联动:

总的来说: @pathvariable 接收url路径上的参数 @RequestParam 接收参数请求的params

对于源码中的其他参数讲解:

    @Target 作用于参数中 @Retention作用是定义被它所注解的注解保留多久,RetentionPolicy.RUNTIME注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在 @Documented,生成javadoc的时候就会把@Documented注解给显示出来,但其实也没啥用处,一个标识而已

2. 实战讲解

以上两个注解都要配合请求体的参数

@PathVariable 注解

@GetMapping ("/manongyanjiuseng/{age}")
@ResponseBody
public String xx( @PathVariable ( "age" ) String age)

@Requestparam注解

@RGetMapping ("/manongyanjiuseng")
@ResponseBody
public String xx( @RequestParam ( "age" ) String age)

具体的传参如下:

    @PathVariable:/manongyanjiuseng/18 @RequestParam:/manongyanjiuseng?age=18
经验分享 程序员 微信小程序 职场和发展