spring boot的@RequestParam和@RequestBody的区别

时间:2023-03-09 08:49:11
spring boot的@RequestParam和@RequestBody的区别

一、问题描述

由于项目是前后端分离,因此后台使用的是spring boot,做成微服务,只暴露接口。接口设计风格为restful的风格,在get请求下,后台接收参数的注解为RequestBody时会报错;在post请求下,后台接收参数的注解为RequestParam时也会报错。

二、问题原因

由于spring的RequestParam注解接收的参数是来自于requestHeader中,即请求头,也就是在url中,格式为xxx?username=123&password=456,而RequestBody注解接收的参数则是来自于requestBody中,即请求体中。

三、解决方法

因此综上所述,如果为get请求时,后台接收参数的注解应该为RequestParam,如果为post请求时,则后台接收参数的注解就是为RequestBody。附上两个例子,截图如下:

get请求

spring boot的@RequestParam和@RequestBody的区别

post请求

spring boot的@RequestParam和@RequestBody的区别

另外,还有一种应用场景,接口规范为resultful风格时,举个例子:如果要获取某个id下此条问题答案的查询次数的话,则后台就需要动态获取参数,其注解为@PathVariable,并且requestMapping中的value应为value="/{id}/queryNum",截图如下:

spring boot的@RequestParam和@RequestBody的区别