一、问题描述
由于项目是前后端分离,因此后台使用的是spring boot,做成微服务,只暴露接口。接口设计风格为restful的风格,在get请求下,后台接收参数的注解为RequestBody时会报错;在post请求下,后台接收参数的注解为RequestParam时也会报错。
二、问题原因
由于spring的RequestParam注解接收的参数是来自于requestHeader中,即请求头,也就是在url中,格式为xxx?username=123&password=456,而RequestBody注解接收的参数则是来自于requestBody中,即请求体中。
三、解决方法
因此综上所述,如果为get请求时,后台接收参数的注解应该为RequestParam,如果为post请求时,则后台接收参数的注解就是为RequestBody。附上两个例子,截图如下:
get请求
post请求
另外,还有一种应用场景,接口规范为resultful风格时,举个例子:如果要获取某个id下此条问题答案的查询次数的话,则后台就需要动态获取参数,其注解为@PathVariable,并且requestMapping中的value应为value="/{id}/queryNum",截图如下:
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@ApiParam @PathVariable @RequestParam三者区别
[email protected] 顾名思义,是注解api的参数,也就是用于swagger提供开发者文档,文档中生成的注释内容。
@ApiOperation( value = "编辑公告", notes = "编辑公告", httpMethod = "POST" ) @RequestMapping( value = "/edit", method = RequestMethod.POST ) public RequestResult edit( @ApiParam(name = "title", value = "公告标题", required = true) @RequestParam("title") String title, @ApiParam(name = "content", value = "公告内容", required = true) @RequestParam("content") String content){
[email protected],是获取前端传递给后端的参数,可以是get方式,也可以是post方式。其中如果前端传递的参数和后端你接受的参数起的名字字段是一致的可以省略不写,也可以直接写@RequestParam String title,如果不一致一定要完整写,不然获取不到,如下面的bis_key就必须写。(必须是 ?key=value&key=value的URL中)
@ApiOperation( value = "编辑公告", notes = "编辑公告", httpMethod = "POST" ) @RequestMapping( value = "/edit", method = RequestMethod.POST ) public RequestResult edit( @ApiParam(name = "bis_key", value = "bis_key", required = true) String bisKey, @ApiParam(name = "title", value = "公告标题", required = true) @RequestParam String title, @ApiParam(name = "content", value = "公告内容", required = true) String content,
[email protected],是获取get方式,url后面参数,进行参数绑定
@ApiOperation(value = "删除公告", notes = "删除公告", httpMethod = "POST") @RequestMapping(value = "/delete/{bisKey}", method = RequestMethod.POST) public RequestResult remove(@ApiParam(name = "bisKey", value = "需要删除的公告ids", required = true) @PathVariable String bisKey) {
原文地址:https://www.cnblogs.com/kelelipeng/p/10170306.html