详解@RequestBody,@RequestParam,@PathVariable的区别

一,@RequestBody

官方注释为:

 Annotation indicating a method parameter should be bound to the body of the web request.
 * The body of the request is passed through an {@link HttpMessageConverter} to resolve the
 * method argument depending on the content type of the request. Optionally, automatic
 * validation can be applied by annotating the argument with {@code @Valid}

即:此注解表明方法参数应该和请求体绑定,换句话说就是@RequestBody接收的是请求体中的参数(当是post请求时,数据就会在请求体中),在接收参数的过程中HttpMessageConverter会根据请求的contentType值去解析方法参数,还可以有选择的给参数加一些验证。因此,这个注解需要注意的点就是,ajax中contentType值的设置与Controller中对应方法的参数类型要对应,一般来说,如果Controller中是实体接收,那么contentType值要设为application/json。(ps:请求体中的数据是通过获取的噢~)

二,@RequestParam

官方注释为:

Annotation which indicates that a method parameter should be bound to a web
 * request parameter.
......

即:方法参数和请求参数绑定,在SpringMVC中,这个请求参数指的是,query parameters, form data,
 and parts in multipart requests。

  1. query parammeters:如果是get请求,那么参数都是以query parameters的形式存在
  2. form data:post请求的一般表单数据,例如,当contentType=application/x-www-form-urlencoded时
  3. multipart requests:还不太了解(后续知道了会重新更新)

@RequestParam接收的是以上三种形式的参数。

三,@PathVariable

官方注释为:

Annotation which indicates that a method parameter should be bound to a URI template
 * variable. Supported for {@link RequestMapping} annotated handler methods.

即:方法参数与URI模板变量绑定,与@RequestMapping一起,形如:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值