@RequestParam,@PathVariable和@RequestBody三者区别

Posted chengxiaodi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@RequestParam,@PathVariable和@RequestBody三者区别相关的知识,希望对你有一定的参考价值。

@RequestParam注解

顾名思义:获取参数,即是获取传送过来的参数;例如获取下面链接的id参数值:

//链接(注意链接格式区别)
http://localhost:8090/hello?id=2
//使用@RequestParam注解获取id
public String Demo1(@RequestParam String id)
    System.out.println("链接中请求参数的id:"+id);
    return null;

此时@RequestParam的作用就可以获取id下来并且作为形参传给方法体里面的id

@PathVariable注解

顾名思义:路径变量,即是获取链接路径上的变量,例如获取下面链接的id

//链接(注意比较上面一条链接)
http://localhost:8090/hello/2
//使用@PathVariable注解获取id
@RequestMapping(value = "/getBook/id", method = RequestMethod.GET)
public String getBook(@PathVariable Integer id) 
     try 
            system.out.println("路径上的id:"+id);
         catch (ParseException e) 
            e.printStackTrace();
    
    return null;

此时@PathVariable的作用是将路径上的id获取进来传递给方法体里面的形参id,但是变量名称必须一样,比如这里:value = "/getBook/id"@PathVariable Integer id;两个都要是id,如果不同则报错;

@RequestBody注解

首先说下,@RequestBody注解一般主要是用来处理content-type:"application/json charset=utf-8"或者content-type:"application/xml charset=utf-8"两种请求数据,一般是异步请求用的比较多些,例如:

//异步请求部分代码
$.ajax(
        url:"/hello",
        type:"POST",
        data:‘"id":"123","name":"chenyc"‘,
        content-type:"application/json charset=utf-8",
        success:function(data)
          alert(data);
        
    );
//@requestBody注解获取数据代码
@requestMapping("/hello")
    public String hello(@requestBody Integer id,@requestBody String name)
      System.out.println("id:"+id+";"+"name:"+name);
    

此时@requestBody注解就可以获取到请求中的各个参数然后赋值到相对应的方法形参上,另外,当有一个实体类User包含了idname的元素的话,在方法里面直接可以写@requestBody User user就会自动封装好给我们使用的了,不用麻烦像这样@requestBody Integer id,@requestBody String name一个一个的封装

以上是关于@RequestParam,@PathVariable和@RequestBody三者区别的主要内容,如果未能解决你的问题,请参考以下文章

@RequestParam 与 @PathVariable

@RequestBody和@RequestParam区别

@RequestBody和@RequestParam区别

@RequestBody和@RequestParam区别

@RequestParam注解

@RequestParam注解